/* ============================================
   KNOWLEDGE MANAGEMENT — Manual table with bulk actions
   ============================================ */
const MANUALS = [
  { id: "DOC-CNC-204",   name: "CNC-Mazak-INTEGREX-i400 — Maintenance v7.2", tags: ["CNC", "Mazak", "Maintenance"], status: "indexed", chunks: 1842, size: "24.6 MB", indexed: "2026-03-04" },
  { id: "DOC-CNC-205",   name: "CNC-Mazak-INTEGREX-i400 — Operator Guide v3.1", tags: ["CNC", "Mazak", "Operations"], status: "indexed", chunks: 904, size: "12.1 MB", indexed: "2026-03-04" },
  { id: "DOC-HYD-018",   name: "Bosch Rexroth Hydraulic Systems Vol. III", tags: ["Hydraulic", "Rexroth"], status: "indexed", chunks: 2104, size: "31.8 MB", indexed: "2026-02-28" },
  { id: "DOC-ELEC-091",  name: "Siemens S7-1500 PLC Programming Reference", tags: ["PLC", "Siemens", "Electrical"], status: "indexed", chunks: 3216, size: "42.0 MB", indexed: "2026-02-12" },
  { id: "DOC-ELEC-092",  name: "ABB ACS580 Variable Frequency Drives", tags: ["VFD", "ABB", "Electrical"], status: "indexed", chunks: 1502, size: "19.4 MB", indexed: "2026-02-12" },
  { id: "DOC-SAFETY-018",name: "Plant Safety SOP — LOTO & Confined Spaces", tags: ["Safety", "SOP", "Critical"], status: "indexed", chunks: 412, size: "5.2 MB", indexed: "2026-01-30" },
  { id: "DOC-SAFETY-019",name: "ISO 13849-1 Compliance Reference Notes", tags: ["Safety", "ISO", "Compliance"], status: "needs-review", chunks: 188, size: "2.1 MB", indexed: "2025-12-10" },
  { id: "DOC-LUBE-007",  name: "Lubrication Standards 2025 — Master Reference", tags: ["Lubrication", "Maintenance"], status: "indexed", chunks: 326, size: "4.4 MB", indexed: "2026-01-15" },
  { id: "DOC-CAL-001",   name: "Calibration Master Log & Schedule", tags: ["QA", "Calibration"], status: "stale", chunks: 92, size: "1.0 MB", indexed: "2025-09-22" },
  { id: "DOC-PNEU-003",  name: "Pneumatic Systems — FRL Maintenance Manual", tags: ["Pneumatic", "Maintenance"], status: "indexed", chunks: 540, size: "7.2 MB", indexed: "2026-02-01" },
  { id: "DOC-REL-014",   name: "Reliability Engineering Handbook (Internal)", tags: ["Reliability", "Internal"], status: "indexed", chunks: 1980, size: "28.0 MB", indexed: "2026-01-18" },
  { id: "DOC-WELD-006",  name: "Welding SOP & Consumables Reference", tags: ["Welding", "Fabrication", "SOP"], status: "indexed", chunks: 218, size: "3.0 MB", indexed: "2026-02-19" },
];

function statusBadge(status) {
  switch (status) {
    case "indexed":      return <Badge kind="complete">Indexed</Badge>;
    case "needs-review": return <Badge kind="pending">Needs review</Badge>;
    case "stale":        return <Badge kind="failed">Stale &gt; 180 d</Badge>;
    default:             return <Badge kind="neutral">{status}</Badge>;
  }
}

function KnowledgeScreen({ onNavigate }) {
  const [selected, setSelected] = useState(new Set(["DOC-CAL-001", "DOC-SAFETY-019"]));

  const toggle = (id) => {
    setSelected(prev => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id); else next.add(id);
      return next;
    });
  };

  const allSelected = selected.size === MANUALS.length;
  const toggleAll = () => {
    setSelected(allSelected ? new Set() : new Set(MANUALS.map(m => m.id)));
  };

  return (
    <>
      <div className="page-header">
        <div>
          <h1 className="page-title">Knowledge Management</h1>
          <p className="page-subtitle">
            {MANUALS.length} documents · 13,324 chunks · 181 MB indexed corpus
          </p>
        </div>
        <div className="row">
          <button className="btn btn--ghost"><Icons.Filter size={14} /> Filter tags</button>
          <button className="btn btn--secondary" onClick={() => onNavigate("ingestion")}><Icons.Upload size={14} /> Upload Manuals</button>
        </div>
      </div>

      <Card bodyFlush>
        {/* Bulk action bar */}
        <div style={{
          padding: "10px 16px",
          background: selected.size > 0 ? "var(--orange-50)" : "var(--ink-50)",
          borderBottom: "1px solid var(--ink-200)",
          display: "flex",
          alignItems: "center",
          gap: 12,
          transition: "background 0.15s",
        }}>
          <span className="text-sm" style={{ fontWeight: 600, color: selected.size > 0 ? "var(--orange-700)" : "var(--ink-600)" }}>
            {selected.size > 0
              ? `${selected.size} document${selected.size > 1 ? "s" : ""} selected`
              : `${MANUALS.length} documents · Bulk actions available on selection`}
          </span>
          <span className="spacer" />
          {selected.size > 0 && (
            <>
              <button className="btn btn--ghost btn--sm" onClick={() => setSelected(new Set())}>Clear</button>
              <button className="btn btn--ghost btn--sm"><Icons.Tag size={13} /> Edit tags</button>
              <button className="btn btn--ghost btn--sm"><Icons.Download size={13} /> Export</button>
              <button className="btn btn--primary btn--sm"><Icons.Refresh size={13} /> Re-index ({selected.size})</button>
              <button className="btn btn--primary btn--sm"><Icons.Trash size={13} /> Delete ({selected.size})</button>
            </>
          )}
        </div>

        <table className="table">
          <thead>
            <tr>
              <th style={{ width: 36 }}><Checkbox checked={allSelected} onChange={toggleAll} /></th>
              <th style={{ width: 140 }}>Document ID</th>
              <th>Document Name</th>
              <th>Metadata Tags</th>
              <th style={{ width: 130 }}>Status</th>
              <th style={{ width: 100, textAlign: "right" }}>Chunks</th>
              <th style={{ width: 110 }}>Indexed</th>
              <th style={{ width: 110 }}>Inspect</th>
            </tr>
          </thead>
          <tbody>
            {MANUALS.map(m => {
              const isSel = selected.has(m.id);
              return (
                <tr key={m.id} style={isSel ? { background: "var(--orange-50)" } : null}>
                  <td><Checkbox checked={isSel} onChange={() => toggle(m.id)} /></td>
                  <td><span className="mono" style={{ color: "var(--navy-700)", fontWeight: 600 }}>{m.id}</span></td>
                  <td>
                    <div className="doc-name">{m.name}</div>
                    <div className="text-xs muted mono">{m.size}</div>
                  </td>
                  <td>
                    <div className="row gap-4" style={{ flexWrap: "wrap" }}>
                      {m.tags.map(t => (
                        <span key={t} className="badge badge--neutral" style={{ fontSize: 10.5 }}><Icons.Tag size={10} />{t}</span>
                      ))}
                    </div>
                  </td>
                  <td>{statusBadge(m.status)}</td>
                  <td className="mono" style={{ textAlign: "right", fontWeight: 600, color: "var(--ink-700)" }}>{m.chunks.toLocaleString()}</td>
                  <td className="mono text-xs muted">{m.indexed}</td>
                  <td>
                    <button className="btn btn--ghost btn--sm" onClick={() => onNavigate("inspector")}>
                      <Icons.Eye size={13} /> Inspect
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>

        {/* Footer pagination */}
        <div style={{ padding: "10px 16px", borderTop: "1px solid var(--ink-200)", display: "flex", alignItems: "center", gap: 12 }}>
          <span className="text-xs muted">Showing 1–{MANUALS.length} of {MANUALS.length}</span>
          <span className="spacer" />
          <button className="btn btn--ghost btn--sm" disabled>Prev</button>
          <span className="mono text-xs muted">page 1 / 1</span>
          <button className="btn btn--ghost btn--sm" disabled>Next</button>
        </div>
      </Card>
    </>
  );
}

window.KnowledgeScreen = KnowledgeScreen;
