/* DocTypes — Content Operations → Document types (attachments A2, 0145).
   The required "Document type" pick list on every Documents panel, one list per
   record type. Content Ops edits it here; the AI proposer reads the same list,
   including the "what counts" note. Retire, never delete: saved documents keep
   their type. Assigns window.LedgerDocTypes. */
(function () {
  const DS = window.LawCrimeDesignSystem_e18d68;
  const A = () => window.LedgerAPI.att;
  const icons = () => setTimeout(() => window.lucide && window.lucide.createIcons(), 30);

  // Order follows where people meet them: case side, then the desk, then crew.
  const KINDS = [
    ["matter", "Matters", "folder-open"],
    ["asset_request", "Asset requests", "clipboard-list"],
    ["asset_cost_event", "Request costs", "receipt"],   // 0160: invoice / quote / receipt per cost event
    ["agency", "Agencies", "landmark"],
    ["freelancer", "Freelancers", "contact"],
    ["booking", "Bookings", "calendar-check"],
    ["courthouse", "Courthouses", "building"],   // 0151, Content Ops only
  ];

  function Row({ t, onSaved, onError }) {
    const [f, setF] = React.useState({ label: t.label, hint: t.hint || "" });
    const [busy, setBusy] = React.useState(false);
    const dirty = f.label !== t.label || f.hint !== (t.hint || "");
    async function save(patch) {
      setBusy(true);
      try {
        const r = await A().saveDocType({ entity_type: t.entity_type, key: t.key, label: f.label, hint: f.hint || null,
          is_active: t.is_active, sort_order: t.sort_order, ...patch });
        if (r.ok) onSaved(); else onError(r.reason || "Couldn't save.");
      } catch (e) { onError(e.message || String(e)); }
      setBusy(false);
    }
    return (
      <tr className={t.is_active ? "" : "fl-cancelled"}>
        <td><input className="lc-input" value={f.label} onChange={(e) => setF({ ...f, label: e.target.value })} /></td>
        <td><input className="lc-input" value={f.hint} placeholder="What counts (helps people and the AI)" onChange={(e) => setF({ ...f, hint: e.target.value })} /></td>
        <td className="fl-badges">
          {dirty && <button type="button" className="link-btn" disabled={busy || !f.label.trim()} onClick={() => save({})}>Save</button>}
          {t.key !== "other" && (
            <button type="button" className="link-btn" disabled={busy} onClick={() => save({ is_active: !t.is_active })}>
              {t.is_active ? "Retire" : "Restore"}</button>
          )}
        </td>
      </tr>
    );
  }

  function DocTypes() {
    const [kind, setKind] = React.useState("matter");
    const [rows, setRows] = React.useState(null);
    const [err, setErr] = React.useState(null);
    const [nf, setNf] = React.useState({ label: "", hint: "" });
    const [busy, setBusy] = React.useState(false);
    const load = React.useCallback(() => {
      setErr(null);
      return A().allDocTypes(kind).then(setRows).catch((e) => { setRows([]); setErr(e.message || String(e)); });
    }, [kind]);
    React.useEffect(() => { setRows(null); load(); }, [load]);
    React.useEffect(() => { icons(); });

    async function add() {
      setBusy(true); setErr(null);
      try {
        const r = await A().saveDocType({ entity_type: kind, label: nf.label, hint: nf.hint || null });
        if (r.ok) { setNf({ label: "", hint: "" }); load(); } else setErr(r.reason || "Couldn't add.");
      } catch (e) { setErr(e.message || String(e)); }
      setBusy(false);
    }

    return (
      <div className="fl">
        <div className="page-head">
          <div>
            <div className="eyebrow">Content Operations</div>
            <h1 className="page-title">Document types<window.LedgerComment section="Document types" /></h1>
            <p className="page-sub">The "Document type" list people pick from when they add a document. Each kind of record has its own list.
              Retiring a type hides it from the picker; documents that already have it keep it. The AI reads these labels and the "what counts" note.</p>
          </div>
        </div>
        <div className="fl-tabs">
          {KINDS.map(([id, label, icon]) => (
            <button key={id} type="button" className={"fl-tab" + (kind === id ? " fl-tab--on" : "")} onClick={() => setKind(id)}>
              <span><i data-lucide={icon} /></span> {label}
            </button>
          ))}
        </div>
        {err && <div className="login__err" style={{ marginBottom: 12 }}>{err}</div>}
        <DS.Card style={{ marginBottom: 14 }}><DS.Card.Body style={{ padding: 0 }}>
          <div className="opsq-table-wrap">
            <table className="opsq-table fl-table">
              <thead><tr><th>Document type</th><th>What counts</th><th></th></tr></thead>
              <tbody>
                {rows === null ? <tr><td colSpan={3} className="fl-sub">Loading…</td></tr>
                  : rows.map((t) => (
                    <Row key={t.key + String(t.is_active) + t.label + (t.hint || "")} t={t} onSaved={load} onError={setErr} />
                  ))}
              </tbody>
            </table>
          </div>
        </DS.Card.Body></DS.Card>
        <DS.Card><DS.Card.Body>
          <div className="tr-label">Add a document type</div>
          <div className="fl-addtag dt-add">
            <input className="lc-input" value={nf.label} placeholder="Label, e.g. Search warrant" onChange={(e) => setNf({ ...nf, label: e.target.value })} />
            <input className="lc-input" value={nf.hint} placeholder="What counts (optional)" onChange={(e) => setNf({ ...nf, hint: e.target.value })} />
            <DS.Button size="sm" variant="primary" icon="plus" onClick={add} disabled={busy || !nf.label.trim()}>Add</DS.Button>
          </div>
        </DS.Card.Body></DS.Card>
      </div>
    );
  }

  window.LedgerDocTypes = DocTypes;
})();
