/* ============================================================
   FacilityOS — Assets registry + slide-over detail
   ============================================================ */
window.Screens = window.Screens || {};

const ASSET_STATUS = {
  operational: { label: "Operational", token: "--c-done" },
  maintenance: { label: "In Maintenance", token: "--c-medium" },
  down:        { label: "Down", token: "--c-critical" },
  retired:     { label: "Retired", token: "--c-low" },
};
const WARRANTY = {
  active:   { label: "Active", token: "--c-done" },
  expiring: { label: "Expiring", token: "--c-high" },
  expired:  { label: "Expired", token: "--c-critical" },
  none:     { label: "None", token: "--c-low" },
};

function HealthBar({ value }) {
  const tok = value >= 75 ? "--c-done" : value >= 50 ? "--c-medium" : "--c-critical";
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
      <span style={{ width: 54, height: 6, borderRadius: 99, background: "var(--surface-3)", overflow: "hidden", display: "block", flex: "0 0 auto" }}>
        <span style={{ display: "block", height: "100%", width: `${value}%`, background: `var(${tok})`, borderRadius: 99 }} />
      </span>
      <span className="tnum" style={{ fontSize: 12.5, fontWeight: 700, color: `var(${tok})` }}>{value}</span>
    </div>
  );
}

function QRGlyph({ size = 96 }) {
  // deterministic pseudo-QR from a fixed pattern
  const cells = "111111101010111111100000101110000001011101101010110111010110111011010100000010101000001111111010101111111000000000011110000110111011010011000010101110011100100100010111010100111011010010101011111010001100111000000110100110101111110010010101011101001010100110";
  const n = 16, s = size / n;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ display: "block" }}>
      <rect width={size} height={size} fill="#fff" rx="6" />
      {Array.from({ length: n * n }).map((_, i) => {
        const on = cells[i % cells.length] === "1";
        if (!on) return null;
        const x = (i % n) * s, y = Math.floor(i / n) * s;
        return <rect key={i} x={x + 4} y={y + 4} width={s} height={s} fill="#111" />;
      })}
    </svg>
  );
}

function AssetSlideOver({ id, onClose, go }) {
  const DB = window.DB;
  const a = DB.assetDetail(id);
  const f = DB.facById(a.facility);
  const cat = DB.ASSET_CATS[a.cat];
  const st = ASSET_STATUS[a.status], wr = WARRANTY[a.warranty];
  const depr = Math.round((a.health / 100) * a.value);

  return (
    <React.Fragment>
      <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "oklch(0 0 0 / 0.4)", zIndex: 60, animation: "fadeIn .2s ease" }} />
      <div style={{ position: "fixed", top: 0, right: 0, bottom: 0, width: "min(480px, 94vw)", background: "var(--surface)", borderLeft: "1px solid var(--border)", boxShadow: "var(--shadow-lg)", zIndex: 61, display: "flex", flexDirection: "column", animation: "slideOver .28s cubic-bezier(.4,0,.2,1)" }}>
        {/* header */}
        <div style={{ padding: "18px 22px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "flex-start", gap: 12 }}>
          <span style={{ width: 42, height: 42, borderRadius: "var(--radius-sm)", flex: "0 0 auto", display: "flex", alignItems: "center", justifyContent: "center", background: UI.tint(cat.token, 15), color: `var(${cat.token})` }}>
            <Icon name={window.catIcon(a.cat)} size={21} />
          </span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="mono" style={{ fontSize: 11.5, color: "var(--text-faint)", fontWeight: 600 }}>{a.id}</div>
            <h2 style={{ margin: "2px 0 0", fontSize: 18, fontWeight: 700, letterSpacing: "-.015em", lineHeight: 1.25 }}>{a.name}</h2>
          </div>
          <UI.IconButton icon="x" onClick={onClose} title="Close" />
        </div>

        <div style={{ flex: 1, overflowY: "auto", padding: 22, display: "flex", flexDirection: "column", gap: 22 }}>
          {/* status row */}
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "5px 11px", borderRadius: 999, fontSize: 12.5, fontWeight: 600, color: `var(${st.token})`, background: UI.tint(st.token, 13), border: `1px solid ${UI.tint(st.token, 28)}` }}>
              <span style={{ width: 7, height: 7, borderRadius: 99, background: `var(${st.token})` }} />{st.label}
            </span>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "5px 11px", borderRadius: 999, fontSize: 12.5, fontWeight: 600, color: `var(${cat.token})`, background: UI.tint(cat.token, 13) }}>{a.cat}</span>
          </div>

          {/* QR + health */}
          <div style={{ display: "flex", gap: 18, alignItems: "center" }}>
            <div style={{ padding: 10, background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: "var(--radius-sm)", flex: "0 0 auto" }}>
              <QRGlyph size={92} />
            </div>
            <div style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column", gap: 12 }}>
              <div>
                <div style={{ fontSize: 12, color: "var(--text-faint)", fontWeight: 500, marginBottom: 5 }}>Asset health</div>
                <HealthBar value={a.health} />
              </div>
              <div>
                <div style={{ fontSize: 12, color: "var(--text-faint)", fontWeight: 500, marginBottom: 3 }}>Warranty</div>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 13, fontWeight: 600, color: `var(${wr.token})` }}>
                  <Icon name={a.warranty === "active" ? "badgeCheck" : a.warranty === "expired" ? "warning" : "shield"} size={15} />{wr.label}
                </span>
              </div>
            </div>
          </div>

          {/* specs */}
          <div>
            <div style={{ fontSize: 11.5, fontWeight: 700, letterSpacing: ".05em", textTransform: "uppercase", color: "var(--text-faint)", marginBottom: 10 }}>Specifications</div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 1, background: "var(--border)", borderRadius: "var(--radius-sm)", overflow: "hidden" }}>
              {a.specs.map((s) => (
                <div key={s.k} style={{ background: "var(--surface-2)", padding: "10px 13px" }}>
                  <div style={{ fontSize: 11, color: "var(--text-faint)", fontWeight: 500 }}>{s.k}</div>
                  <div className={s.k === "Serial" || s.k === "Model" ? "mono" : ""} style={{ fontSize: 13, fontWeight: 600, marginTop: 2, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{s.v}</div>
                </div>
              ))}
            </div>
          </div>

          {/* value / depreciation */}
          <div style={{ display: "flex", gap: 12 }}>
            <div style={{ flex: 1, padding: "13px 15px", background: "var(--surface-2)", borderRadius: "var(--radius-sm)", border: "1px solid var(--border)" }}>
              <div style={{ fontSize: 11.5, color: "var(--text-faint)", fontWeight: 500 }}>Purchase value</div>
              <div className="tnum" style={{ fontSize: 21, fontWeight: 700, marginTop: 3 }}>${a.value.toLocaleString()}</div>
            </div>
            <div style={{ flex: 1, padding: "13px 15px", background: "var(--surface-2)", borderRadius: "var(--radius-sm)", border: "1px solid var(--border)" }}>
              <div style={{ fontSize: 11.5, color: "var(--text-faint)", fontWeight: 500 }}>Current book value</div>
              <div className="tnum" style={{ fontSize: 21, fontWeight: 700, marginTop: 3, color: "var(--accent-strong)" }}>${depr.toLocaleString()}</div>
            </div>
          </div>

          {/* maintenance history */}
          <div>
            <div style={{ fontSize: 11.5, fontWeight: 700, letterSpacing: ".05em", textTransform: "uppercase", color: "var(--text-faint)", marginBottom: 12 }}>Maintenance history</div>
            <div style={{ display: "flex", flexDirection: "column" }}>
              {a.history.map((h, i) => (
                <div key={i} style={{ display: "flex", gap: 12, paddingBottom: i === a.history.length-1 ? 0 : 14 }}>
                  <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
                    <span style={{ width: 10, height: 10, borderRadius: 99, background: `var(${h.tone})`, border: "2px solid var(--surface)", boxShadow: `0 0 0 1.5px var(${h.tone})`, flex: "0 0 auto", marginTop: 3 }} />
                    {i !== a.history.length-1 && <span style={{ flex: 1, width: 2, background: "var(--border)", marginTop: 4, borderRadius: 99 }} />}
                  </div>
                  <div style={{ minWidth: 0, paddingBottom: 2 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 600 }}>{h.text}</div>
                    <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 2 }}>
                      <span className="mono" style={{ fontSize: 11.5, fontWeight: 600, color: "var(--accent-strong)", cursor: "pointer" }} onClick={() => go("wo-detail", { id: h.wo })}>{h.wo}</span>
                      <span style={{ fontSize: 11.5, color: "var(--text-faint)" }}>· {h.date}</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* linked docs */}
          <div>
            <div style={{ fontSize: 11.5, fontWeight: 700, letterSpacing: ".05em", textTransform: "uppercase", color: "var(--text-faint)", marginBottom: 10 }}>Linked documents</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 7 }}>
              {a.docs.map((d) => {
                const dk = DB.DOC_KIND[d.kind];
                return (
                  <button key={d.name} onClick={() => go("documents")} style={{ display: "flex", alignItems: "center", gap: 11, padding: "9px 12px", borderRadius: "var(--radius-sm)", border: "1px solid var(--border)", background: "var(--surface-2)", cursor: "pointer", textAlign: "left" }}>
                    <span style={{ width: 28, height: 28, borderRadius: 7, flex: "0 0 auto", display: "flex", alignItems: "center", justifyContent: "center", background: UI.tint(dk.token, 14), color: `var(${dk.token})` }}><Icon name={dk.icon} size={15} /></span>
                    <span style={{ flex: 1, fontSize: 13, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{d.name}</span>
                    <Icon name="externalLink" size={15} style={{ color: "var(--text-faint)" }} />
                  </button>
                );
              })}
            </div>
          </div>
        </div>

        {/* footer */}
        <div style={{ padding: "14px 22px", borderTop: "1px solid var(--border)", display: "flex", gap: 10 }}>
          <UI.Button variant="primary" icon="wrench" style={{ flex: 1 }} onClick={() => go("work-orders")}>New Work Order</UI.Button>
          <UI.Button variant="soft" icon="qr">Print QR</UI.Button>
        </div>
      </div>
    </React.Fragment>
  );
}

Screens.Assets = function Assets({ go, search, params }) {
  const DB = window.DB;
  const { Card } = UI;
  const FilterSelect = window.FilterSelect;
  const [cat, setCat] = useState("all");
  const [facFilter, setFacFilter] = useState(params && params.facility ? params.facility : "all");
  const [openId, setOpenId] = useState(null);
  const q = (search || "").toLowerCase();

  const cats = ["all", ...Object.keys(DB.ASSET_CATS)];
  const list = DB.assets.filter((a) =>
    (cat === "all" || a.cat === cat) &&
    (facFilter === "all" || a.facility === facFilter) &&
    (!q || a.name.toLowerCase().includes(q) || a.id.toLowerCase().includes(q) || a.model.toLowerCase().includes(q))
  );

  return (
    <div className="page fade-up">
      {/* category chips */}
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 14, flexWrap: "wrap" }}>
        <div style={{ display: "flex", gap: 7, flexWrap: "wrap" }}>
          {cats.map((c) => {
            const on = cat === c;
            const tok = c === "all" ? "--accent" : DB.ASSET_CATS[c].token;
            const count = c === "all" ? DB.assets.length : DB.assets.filter((a) => a.cat === c).length;
            return (
              <button key={c} onClick={() => setCat(c)} style={{
                display: "inline-flex", alignItems: "center", gap: 7, padding: "6px 12px", borderRadius: 999, cursor: "pointer",
                fontSize: 12.5, fontWeight: 600, transition: "all .15s ease",
                color: on ? `var(${tok})` : "var(--text-muted)",
                background: on ? UI.tint(tok, 13) : "var(--surface)",
                border: `1px solid ${on ? UI.tint(tok, 30) : "var(--border)"}`,
              }}>
                {c !== "all" && <Icon name={window.catIcon(c)} size={14} />}
                {c === "all" ? "All categories" : c}
                <span className="tnum" style={{ fontSize: 11, fontWeight: 700, opacity: 0.7 }}>{count}</span>
              </button>
            );
          })}
        </div>
        <UI.Button variant="primary" icon="plus" style={{ marginLeft: "auto" }}>Add Asset</UI.Button>
      </div>

      {/* facility filter row */}
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14, flexWrap: "wrap" }}>
        <FilterSelect icon="building" label="Facility" value={facFilter} onChange={setFacFilter} options={DB.facilities.map((f) => ({ v: f.id, l: f.name }))} />
        <span className="tnum" style={{ marginLeft: "auto", fontSize: 12.5, color: "var(--text-faint)" }}>{list.length} assets · ${list.reduce((s,a)=>s+a.value,0).toLocaleString()} total value</span>
      </div>

      <Card pad={false} style={{ overflow: "hidden" }}>
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 920 }}>
            <thead>
              <tr>
                {["Asset", "Category", "Facility", "Status", "Health", "Warranty", "Purchased", "Value"].map((h, i) => (
                  <th key={h} style={{ position: "sticky", top: 0, zIndex: 2, background: "var(--surface-2)", textAlign: i >= 7 ? "right" : "left", padding: "11px 14px", fontSize: 11.5, fontWeight: 700, letterSpacing: ".04em", textTransform: "uppercase", color: "var(--text-faint)", borderBottom: "1px solid var(--border)", whiteSpace: "nowrap" }} className={i===2?"hide-md":i===6?"hide-sm":""}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {list.map((a, i) => {
                const f = DB.facById(a.facility);
                const catC = DB.ASSET_CATS[a.cat], st = ASSET_STATUS[a.status], wr = WARRANTY[a.warranty];
                return (
                  <tr key={a.id} onClick={() => setOpenId(a.id)}
                    style={{ cursor: "pointer", background: i % 2 ? "var(--surface)" : "color-mix(in oklch, var(--surface-2) 45%, var(--surface))" }}
                    onMouseEnter={(e) => e.currentTarget.style.background = "var(--surface-2)"}
                    onMouseLeave={(e) => e.currentTarget.style.background = i % 2 ? "var(--surface)" : "color-mix(in oklch, var(--surface-2) 45%, var(--surface))"}>
                    <td style={{ padding: "11px 14px" }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
                        <span style={{ width: 34, height: 34, borderRadius: 9, flex: "0 0 auto", display: "flex", alignItems: "center", justifyContent: "center", background: UI.tint(catC.token, 14), color: `var(${catC.token})` }}><Icon name={window.catIcon(a.cat)} size={17} /></span>
                        <div style={{ minWidth: 0 }}>
                          <div style={{ fontSize: 13.5, fontWeight: 650, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a.name}</div>
                          <div className="mono" style={{ fontSize: 11, color: "var(--text-faint)", marginTop: 1 }}>{a.id}</div>
                        </div>
                      </div>
                    </td>
                    <td style={{ padding: "11px 14px" }}><span style={{ fontSize: 12.5, fontWeight: 600, color: `var(${catC.token})` }}>{a.cat}</span></td>
                    <td className="hide-md" style={{ padding: "11px 14px", fontSize: 13, color: "var(--text-muted)", whiteSpace: "nowrap" }}>{f.name}</td>
                    <td style={{ padding: "11px 14px" }}>
                      <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12.5, fontWeight: 600, color: `var(${st.token})` }}>
                        <span style={{ width: 7, height: 7, borderRadius: 99, background: `var(${st.token})` }} />{st.label}
                      </span>
                    </td>
                    <td style={{ padding: "11px 14px" }}><HealthBar value={a.health} /></td>
                    <td style={{ padding: "11px 14px" }}>
                      <span style={{ fontSize: 12.5, fontWeight: 600, color: `var(${wr.token})` }}>{wr.label}</span>
                    </td>
                    <td className="hide-sm" style={{ padding: "11px 14px", fontSize: 13, color: "var(--text-muted)", whiteSpace: "nowrap" }}>{a.purchased}</td>
                    <td style={{ padding: "11px 14px", textAlign: "right" }}><span className="tnum" style={{ fontSize: 13, fontWeight: 700 }}>${a.value.toLocaleString()}</span></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        {list.length === 0 && <div style={{ padding: "52px 20px", textAlign: "center", color: "var(--text-faint)" }}><Icon name="box" size={26} /><div style={{ marginTop: 12, fontWeight: 650, color: "var(--text)" }}>No assets match</div><div style={{ fontSize: 13, marginTop: 3 }}>Try a different category or facility.</div></div>}
      </Card>

      {openId && <AssetSlideOver id={openId} onClose={() => setOpenId(null)} go={go} />}
    </div>
  );
};
