/* ============================================================
   FacilityOS — Documents + Checklists screens
   ============================================================ */
window.Screens = window.Screens || {};

/* ===================== DOCUMENTS ===================== */
Screens.Documents = function Documents({ go, search }) {
  const DB = window.DB;
  const { Card, Button } = UI;
  const [folder, setFolder] = useState("all");
  const [view, setView] = useState("grid");
  const q = (search || "").toLowerCase();

  const linkedLabel = (l) => {
    if (!l) return null;
    const a = DB.assetById(l); if (a) return a.name;
    const f = DB.facById(l); if (f) return f.name;
    return l;
  };
  const list = DB.documents.filter((d) =>
    (folder === "all" || d.folder === folder) &&
    (!q || d.name.toLowerCase().includes(q))
  );

  return (
    <div className="page fade-up">
      <div className="docs-layout" style={{ display: "grid", gridTemplateColumns: "236px minmax(0,1fr)", gap: 18, alignItems: "start" }}>
        {/* folder rail */}
        <Card pad={false} className="docs-rail" style={{ overflow: "hidden", position: "sticky", top: 0 }}>
          <div style={{ padding: "14px 16px 10px" }}>
            <Button variant="primary" icon="upload" size="sm" style={{ width: "100%" }}>Upload</Button>
          </div>
          <div style={{ padding: "0 8px 10px", display: "flex", flexDirection: "column", gap: 2 }}>
            <FolderRow active={folder === "all"} onClick={() => setFolder("all")} icon="layers" label="All documents" count={DB.documents.length} tok="--accent" />
            {DB.docFolders.map((f) => (
              <FolderRow key={f.id} active={folder === f.id} onClick={() => setFolder(f.id)} icon="folder" label={f.name} count={f.count} tok={f.token} />
            ))}
          </div>
          <div style={{ padding: "12px 16px", borderTop: "1px solid var(--border)", background: "var(--surface-2)" }}>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11.5, color: "var(--text-faint)", marginBottom: 6 }}><span>Storage</span><span className="tnum">6.4 / 20 GB</span></div>
            <div style={{ height: 6, borderRadius: 99, background: "var(--surface-3)", overflow: "hidden" }}><div style={{ height: "100%", width: "32%", background: "var(--accent)", borderRadius: 99 }} /></div>
          </div>
        </Card>

        {/* files */}
        <div style={{ minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 14 }}>
            <h3 style={{ margin: 0, fontSize: 15.5, fontWeight: 650 }}>{folder === "all" ? "All documents" : DB.docFolders.find((f) => f.id === folder).name}</h3>
            <span className="tnum" style={{ fontSize: 12.5, color: "var(--text-faint)" }}>{list.length} files</span>
            <div style={{ marginLeft: "auto", display: "inline-flex", background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: "var(--radius-sm)", padding: 3, gap: 2 }}>
              {[["grid", "grid"], ["list", "list"]].map(([v, ic]) => (
                <button key={v} onClick={() => setView(v)} style={{ width: 30, height: 28, display: "flex", alignItems: "center", justifyContent: "center", borderRadius: 6, cursor: "pointer", border: "none", background: view === v ? "var(--surface)" : "transparent", color: view === v ? "var(--accent-strong)" : "var(--text-faint)", boxShadow: view === v ? "var(--shadow-xs)" : "none" }}><Icon name={ic} size={16} /></button>
              ))}
            </div>
          </div>

          {view === "grid" ? (
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(190px, 1fr))", gap: 14 }}>
              {list.map((d) => {
                const dk = DB.DOC_KIND[d.kind];
                return (
                  <Card key={d.id} pad={false} hover style={{ overflow: "hidden", cursor: "pointer" }}>
                    <div style={{ aspectRatio: "5/3", background: `repeating-linear-gradient(135deg, var(--surface-3), var(--surface-3) 9px, color-mix(in oklch, var(${dk.token}) 8%, var(--surface-3)) 9px, color-mix(in oklch, var(${dk.token}) 8%, var(--surface-3)) 18px)`, display: "flex", alignItems: "center", justifyContent: "center", position: "relative" }}>
                      <span style={{ width: 44, height: 44, borderRadius: 11, background: "var(--surface)", display: "flex", alignItems: "center", justifyContent: "center", color: `var(${dk.token})`, boxShadow: "var(--shadow-sm)" }}><Icon name={dk.icon} size={22} /></span>
                      <span className="mono" style={{ position: "absolute", top: 9, right: 9, fontSize: 9.5, fontWeight: 700, color: `var(${dk.token})`, background: "var(--surface)", padding: "2px 6px", borderRadius: 5, letterSpacing: ".03em" }}>{dk.ext}</span>
                    </div>
                    <div style={{ padding: "11px 13px" }}>
                      <div style={{ fontSize: 13, fontWeight: 600, lineHeight: 1.35, overflow: "hidden", textOverflow: "ellipsis", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", minHeight: 35 }}>{d.name}</div>
                      <div style={{ display: "flex", alignItems: "center", gap: 7, marginTop: 8, fontSize: 11, color: "var(--text-faint)" }}>
                        <span className="tnum">{d.size}</span><span>·</span><span>{d.date}</span>
                      </div>
                      {linkedLabel(d.linked) && (
                        <div style={{ marginTop: 8, display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11, fontWeight: 600, color: "var(--accent-strong)", background: UI.tint("--accent", 10), padding: "2px 8px", borderRadius: 999, maxWidth: "100%" }}>
                          <Icon name={DB.assetById(d.linked) ? "box" : "building"} size={11} /><span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{linkedLabel(d.linked)}</span>
                        </div>
                      )}
                    </div>
                  </Card>
                );
              })}
            </div>
          ) : (
            <Card pad={false} style={{ overflow: "hidden" }}>
              {list.map((d, i) => {
                const dk = DB.DOC_KIND[d.kind];
                return (
                  <div key={d.id} style={{ display: "flex", alignItems: "center", gap: 13, padding: "11px 16px", borderBottom: i < list.length-1 ? "1px solid var(--border)" : "none", cursor: "pointer" }}
                    onMouseEnter={(e)=>e.currentTarget.style.background="var(--surface-2)"} onMouseLeave={(e)=>e.currentTarget.style.background="transparent"}>
                    <span style={{ width: 34, height: 34, borderRadius: 8, flex: "0 0 auto", display: "flex", alignItems: "center", justifyContent: "center", background: UI.tint(dk.token, 13), color: `var(${dk.token})` }}><Icon name={dk.icon} size={17} /></span>
                    <div style={{ minWidth: 0, flex: 1 }}>
                      <div style={{ fontSize: 13.5, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{d.name}</div>
                      <div style={{ fontSize: 11.5, color: "var(--text-faint)", marginTop: 1 }}>{linkedLabel(d.linked) || "Unlinked"}</div>
                    </div>
                    <span className="hide-sm tnum" style={{ fontSize: 12, color: "var(--text-faint)", width: 64, textAlign: "right" }}>{d.size}</span>
                    <span className="hide-md" style={{ fontSize: 12, color: "var(--text-faint)", width: 96, textAlign: "right" }}>{d.date}</span>
                    <UI.Avatar id={d.by} size={26} />
                    <Icon name="download" size={16} style={{ color: "var(--text-faint)" }} />
                  </div>
                );
              })}
            </Card>
          )}
        </div>
      </div>
    </div>
  );
};

function FolderRow({ active, onClick, icon, label, count, tok }) {
  return (
    <button onClick={onClick} style={{ display: "flex", alignItems: "center", gap: 11, padding: "9px 11px", borderRadius: "var(--radius-sm)", cursor: "pointer", textAlign: "left", width: "100%",
      background: active ? UI.tint(tok, 12) : "transparent", border: "1px solid", borderColor: active ? UI.tint(tok, 26) : "transparent", transition: "all .12s" }}
      onMouseEnter={(e)=>{ if(!active) e.currentTarget.style.background="var(--surface-2)"; }} onMouseLeave={(e)=>{ if(!active) e.currentTarget.style.background="transparent"; }}>
      <Icon name={icon} size={17} style={{ color: active ? `var(${tok})` : "var(--text-faint)" }} />
      <span style={{ flex: 1, fontSize: 13, fontWeight: active ? 650 : 500, color: active ? "var(--text)" : "var(--text-muted)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{label}</span>
      <span className="tnum" style={{ fontSize: 11.5, fontWeight: 600, color: "var(--text-faint)" }}>{count}</span>
    </button>
  );
}

/* ===================== CHECKLISTS ===================== */
function RunDrawer({ cl, onClose }) {
  const DB = window.DB;
  const [states, setStates] = useState(cl.sample.map(() => null)); // null | 'pass' | 'fail'
  const done = states.filter((s) => s !== null).length;
  const pct = Math.round((done / cl.sample.length) * 100);

  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(460px, 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)" }}>
        <div style={{ padding: "18px 22px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "flex-start", gap: 12 }}>
          <span style={{ width: 40, height: 40, borderRadius: "var(--radius-sm)", flex: "0 0 auto", display: "flex", alignItems: "center", justifyContent: "center", background: UI.tint(cl.token, 14), color: `var(${cl.token})` }}><Icon name="clipboard" size={20} /></span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="mono" style={{ fontSize: 11.5, color: "var(--text-faint)", fontWeight: 600 }}>{cl.id} · {cl.est}</div>
            <h2 style={{ margin: "2px 0 0", fontSize: 17, fontWeight: 700, letterSpacing: "-.01em" }}>{cl.name}</h2>
          </div>
          <UI.IconButton icon="x" onClick={onClose} />
        </div>

        <div style={{ padding: "14px 22px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "center", gap: 12 }}>
          <div style={{ flex: 1 }}>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, marginBottom: 6 }}><span style={{ color: "var(--text-muted)", fontWeight: 500 }}>Progress</span><span className="tnum" style={{ fontWeight: 700 }}>{done}/{cl.sample.length}</span></div>
            <div style={{ height: 7, borderRadius: 99, background: "var(--surface-3)", overflow: "hidden" }}><div style={{ height: "100%", width: `${pct}%`, background: "var(--accent)", borderRadius: 99, transition: "width .3s ease" }} /></div>
          </div>
        </div>

        <div style={{ flex: 1, overflowY: "auto", padding: "14px 18px", display: "flex", flexDirection: "column", gap: 8 }}>
          {cl.sample.map((item, i) => (
            <div key={i} style={{ padding: "12px 14px", borderRadius: "var(--radius-sm)", border: "1px solid var(--border)", background: states[i] === "pass" ? UI.tint("--c-done", 8) : states[i] === "fail" ? UI.tint("--c-critical", 8) : "var(--surface-2)" }}>
              <div style={{ display: "flex", alignItems: "flex-start", gap: 10 }}>
                <span className="tnum" style={{ fontSize: 12, fontWeight: 700, color: "var(--text-faint)", marginTop: 2, width: 18 }}>{i + 1}</span>
                <span style={{ flex: 1, fontSize: 13.5, fontWeight: 500, lineHeight: 1.4 }}>{item}</span>
              </div>
              <div style={{ display: "flex", gap: 7, marginTop: 10, paddingLeft: 28 }}>
                {[["pass", "Pass", "--c-done", "check"], ["fail", "Fail", "--c-critical", "x"]].map(([v, lbl, tok, ic]) => {
                  const on = states[i] === v;
                  return <button key={v} onClick={() => { const n = [...states]; n[i] = on ? null : v; setStates(n); }} style={{ display: "inline-flex", alignItems: "center", gap: 5, padding: "5px 12px", borderRadius: 999, fontSize: 12, fontWeight: 600, cursor: "pointer", color: on ? `var(${tok})` : "var(--text-muted)", background: on ? UI.tint(tok, 14) : "var(--surface)", border: `1px solid ${on ? UI.tint(tok, 32) : "var(--border)"}` }}><Icon name={ic} size={13} stroke={2.6} />{lbl}</button>;
                })}
                <button style={{ display: "inline-flex", alignItems: "center", gap: 5, padding: "5px 11px", borderRadius: 999, fontSize: 12, fontWeight: 600, cursor: "pointer", color: "var(--text-faint)", background: "var(--surface)", border: "1px solid var(--border)", marginLeft: "auto" }}><Icon name="photo" size={13} /></button>
              </div>
            </div>
          ))}
          <div style={{ textAlign: "center", padding: "10px 0", fontSize: 12, color: "var(--text-faint)" }}>+ {cl.items - cl.sample.length} more items in full checklist</div>
        </div>

        <div style={{ padding: "14px 22px", borderTop: "1px solid var(--border)", display: "flex", gap: 10 }}>
          <UI.Button variant="soft" style={{ flex: "0 0 auto" }}>Save draft</UI.Button>
          <UI.Button variant="primary" icon="check" style={{ flex: 1 }} onClick={onClose}>Complete & log</UI.Button>
        </div>
      </div>
    </React.Fragment>
  );
}

Screens.Checklists = function Checklists({ go }) {
  const DB = window.DB;
  const { Card, Button } = UI;
  const [run, setRun] = useState(null);

  return (
    <div className="page fade-up">
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 18, flexWrap: "wrap" }}>
        <p style={{ margin: 0, fontSize: 13.5, color: "var(--text-muted)" }}>Reusable inspection & task templates your team runs in the field.</p>
        <Button variant="primary" icon="plus" style={{ marginLeft: "auto" }}>New Checklist</Button>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(320px, 1fr))", gap: 18 }}>
        {DB.checklists.map((cl) => (
          <Card key={cl.id} hover style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
              <span style={{ width: 44, height: 44, borderRadius: "var(--radius-sm)", flex: "0 0 auto", display: "flex", alignItems: "center", justifyContent: "center", background: UI.tint(cl.token, 14), color: `var(${cl.token})` }}><Icon name="clipboard" size={22} /></span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <h3 style={{ margin: 0, fontSize: 15.5, fontWeight: 650, letterSpacing: "-.01em", lineHeight: 1.3 }}>{cl.name}</h3>
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 5 }}>
                  <span style={{ fontSize: 12, fontWeight: 600, color: `var(${cl.token})` }}>{cl.cat}</span>
                  <span style={{ width: 3, height: 3, borderRadius: 99, background: "var(--border-strong)" }} />
                  <span className="mono" style={{ fontSize: 11.5, color: "var(--text-faint)" }}>{cl.id}</span>
                </div>
              </div>
            </div>

            <div style={{ display: "flex", gap: 1, background: "var(--border)", borderRadius: "var(--radius-sm)", overflow: "hidden" }}>
              {[
                { label: "Items", val: cl.items, icon: "check" },
                { label: "Est. time", val: cl.est, icon: "clock" },
                { label: "Total runs", val: cl.runs, icon: "history" },
              ].map((s) => (
                <div key={s.label} style={{ flex: 1, background: "var(--surface-2)", padding: "10px 12px" }}>
                  <div className="tnum" style={{ fontSize: 16, fontWeight: 700 }}>{s.val}</div>
                  <div style={{ fontSize: 10.5, color: "var(--text-faint)", fontWeight: 500, marginTop: 1 }}>{s.label}</div>
                </div>
              ))}
            </div>

            <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: "auto" }}>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 7, fontSize: 12, color: "var(--text-faint)" }}>
                <UI.Avatar id={cl.assignee} size={24} /> Last run {cl.lastRun}
              </span>
              <Button size="sm" variant="primary" icon="play2" style={{ marginLeft: "auto" }} onClick={() => setRun(cl)}>Run</Button>
            </div>
          </Card>
        ))}
      </div>

      {run && <RunDrawer cl={run} onClose={() => setRun(null)} />}
    </div>
  );
};
