/* Courthouses (G4, spec agencies-by-location-v1 D2, D9, D12). The building a court sits in and
   what a crew needs there: audio, XLR patch, power, signal, camera rules, load-in.

   Content Ops only (D12): the table's RLS returns nothing to anyone else, and every entry point
   here checks LedgerCaps first so nobody else sees an empty section. Reached from a county panel,
   a court's profile and Search (no page of its own in the nav, D8). Documents (patch-panel photos,
   floor plans) use the attachments mount in the restricted drive (D22).

   Assigns window.LedgerCourthouses = { canUse, Section, Page, chips }. */
(function () {
  const DS = window.LawCrimeDesignSystem_e18d68;
  const icons = () => setTimeout(() => window.lucide && window.lucide.createIcons(), 30);
  const Ic = ({ n }) => <span className="ic-wrap" key={n}><i data-lucide={n} /></span>;
  const canUse = () => !!(window.LedgerCaps && (window.LedgerCaps.isContentOps || window.LedgerCaps.isAdmin));
  const stateName = (s) => (window.LEDGER_STATE_NAME && window.LEDGER_STATE_NAME[s]) || s;
  const place = (c) => [c.city, c.county && c.county + " County", c.state].filter(Boolean).join(", ");

  // Vocabularies mirror the courthouses CHECKs (0151).
  const SIGNAL = { good: "Good signal", weak: "Weak signal", none: "No signal" };
  const triOpts = [{ value: "", label: "Not known" }, { value: "true", label: "Yes" }, { value: "false", label: "No" }];
  const sigOpts = [{ value: "", label: "Not known" }].concat(Object.keys(SIGNAL).map((k) => ({ value: k, label: SIGNAL[k] })));

  /** Short chips for a card: what a crew asks first. */
  function chips(c) {
    const out = [];
    if (c.xlr_patch === true) out.push({ k: "xlr", text: "XLR patch" });
    if (c.xlr_patch === false) out.push({ k: "xlr", text: "No XLR patch", warn: true });
    if (c.signal) out.push({ k: "sig", text: SIGNAL[c.signal], warn: c.signal !== "good" });
    if (c.camera_rules) out.push({ k: "cam", text: "Camera rules" });
    if (c.parking_load_in) out.push({ k: "load", text: "Load-in noted" });
    return out;
  }

  // ---- Create / edit --------------------------------------------------------
  const FIELDS = ["name", "state", "county", "city", "address", "court_entity_id", "audio", "power_notes", "signal_notes",
                  "camera_rules", "parking_load_in", "contact_on_site", "courtroom_notes", "notes", "last_visited"];
  function CourthouseForm({ initial, onSaved, onCancel }) {
    const { Button, Input, Select } = DS;
    const [f, setF] = React.useState(() => {
      const base = {};
      FIELDS.forEach((k) => { base[k] = (initial && initial[k]) || ""; });
      base.xlr_patch = initial && initial.xlr_patch != null ? String(initial.xlr_patch) : "";
      base.signal = (initial && initial.signal) || "";
      return base;
    });
    const [courts, setCourts] = React.useState([]);
    const [busy, setBusy] = React.useState(false);
    const [err, setErr] = React.useState(null);
    const st = (f.state || "").trim().toUpperCase();
    React.useEffect(() => {
      if (!/^[A-Z]{2}$/.test(st)) { setCourts([]); return; }
      window.LedgerAPI.listCourts(st).then(setCourts).catch(() => setCourts([]));
    }, [st]);
    React.useEffect(() => { icons(); }, []);
    const set = (k) => (e) => setF((s) => ({ ...s, [k]: e.target.value }));
    const lc = (s) => String(s || "").toLowerCase();
    // Courts in the same county first: that is almost always the one.
    const courtOpts = [{ value: "", label: "— not linked —" }].concat(
      courts.slice().sort((a, b) => (lc(b.county) === lc(f.county)) - (lc(a.county) === lc(f.county)) || a.entity_name.localeCompare(b.entity_name))
        .map((c) => ({ value: c.entity_id, label: c.entity_name + (c.county ? ` · ${c.county}` : "") })));
    async function save() {
      if (!f.name.trim()) { setErr("Give the courthouse a name."); return; }
      if (!/^[A-Z]{2}$/.test(st)) { setErr("State is a two-letter code, e.g. FL."); return; }
      setBusy(true); setErr(null);
      try {
        const p = { courthouse_id: (initial && initial.courthouse_id) || null };
        FIELDS.forEach((k) => { p[k] = String(f[k] || "").trim() || null; });
        p.state = st;
        p.xlr_patch = f.xlr_patch === "" ? null : f.xlr_patch === "true";
        p.signal = f.signal || null;
        const id = await window.LedgerAPI.saveCourthouse(p);
        onSaved(id);
      } catch (e) { setErr(e.message || String(e)); setBusy(false); }
    }
    const area = (k, label, ph) => (
      <div className="full">
        <label className="field-label">{label}</label>
        <textarea className="lc-input ledger-textarea ch-area" value={f[k]} onChange={set(k)} placeholder={ph} />
      </div>
    );
    return (
      <div className="pl-form">
        {err && <div className="login__err" style={{ marginBottom: 10 }}>{err}</div>}
        <div className="form-grid">
          <Input label="Name *" value={f.name} onChange={set("name")} placeholder="e.g. Bartow Courthouse" />
          <Input label="State *" value={f.state} onChange={set("state")} placeholder="FL" />
          <Input label="County" value={f.county} onChange={set("county")} placeholder="e.g. Polk" />
          <Input label="City" value={f.city} onChange={set("city")} />
          <div className="full"><Input label="Address" value={f.address} onChange={set("address")} /></div>
          <div className="full"><Select label="Court" value={f.court_entity_id} onChange={set("court_entity_id")} options={courtOpts} /></div>
        </div>
        <div className="form-subhead" style={{ marginTop: 14 }}>Production notes</div>
        <div className="form-grid">
          <Select label="XLR patch for press" value={f.xlr_patch} onChange={set("xlr_patch")} options={triOpts} />
          <Select label="Signal inside" value={f.signal} onChange={set("signal")} options={sigOpts} />
          {area("audio", "Audio", "Mult box in the gallery, bring a 25 ft XLR…")}
          <div className="full"><Input label="Signal notes" value={f.signal_notes} onChange={set("signal_notes")} placeholder="Weak on floor 4; bonded cell works from the hallway" /></div>
          {area("power_notes", "Power", "Outlets by the rail; no extension cords across the aisle")}
          {area("camera_rules", "Camera rules", "Pool camera only; no shots of jurors; order needed 48 h ahead")}
          {area("parking_load_in", "Parking and load-in", "Loading dock on Main St, check in with security first")}
          <Input label="On-site contact" value={f.contact_on_site} onChange={set("contact_on_site")} placeholder="Name, role, phone" />
          <Input type="date" label="Last visited" value={f.last_visited} onChange={set("last_visited")} />
          {area("courtroom_notes", "Courtrooms", "3B: camera position behind the jury box…")}
          {area("notes", "Other notes", "")}
        </div>
        <div className="form-actions">
          <Button variant="ghost" onClick={onCancel} disabled={busy}>Cancel</Button>
          <Button variant="primary" icon="check" onClick={save} disabled={busy}>{busy ? "Saving…" : "Save courthouse"}</Button>
        </div>
      </div>
    );
  }

  // ---- Cards (county panel, court profile) ---------------------------------
  function Card({ c, onOpen, showPlace }) {
    React.useEffect(() => { icons(); }, []);
    return (
      <div className="ag-card pl-card ch-card">
        <div className="ag-name"><button type="button" className="ag-namelink" onClick={() => onOpen(c.courthouse_id)}><Ic n="building" /> {c.name}</button></div>
        <div className="ag-meta">
          <span className="ag-loc">{showPlace ? place(c) : (c.court_name || "No court linked")}</span>
          {chips(c).map((q) => <span key={q.k} className={"chip" + (q.warn ? " pl-chip--warn" : "")}>{q.text}</span>)}
        </div>
        {!chips(c).length && <div className="pl-counts">No production notes yet</div>}
      </div>
    );
  }

  /** Courthouses for a county (state + county) or for one court (courtId). Renders nothing outside Content Ops. */
  function Section({ state, county, courtId, onOpen, title = "Courthouses" }) {
    const [rows, setRows] = React.useState(null);
    const [adding, setAdding] = React.useState(false);
    const [err, setErr] = React.useState(null);
    const ok = canUse();
    const load = React.useCallback(() => {
      if (!ok) return;
      window.LedgerAPI.listCourthouses().then(setRows).catch((e) => setErr(e.message || String(e)));
    }, [ok]);
    React.useEffect(() => { load(); }, [load]);
    React.useEffect(() => { icons(); }, [rows, adding]);
    if (!ok) return null;
    const lc = (s) => String(s || "").toLowerCase();
    const mine = (rows || []).filter((c) => courtId ? c.court_entity_id === courtId
      : c.state === state && lc(c.county) === lc(county));
    return (
      <div className="pl-sec">
        <div className="form-subhead">{title} ({rows ? mine.length : "…"}) <span className="ch-only">Content Ops</span></div>
        {err && <div className="login__err" style={{ marginBottom: 10 }}>{err}</div>}
        {mine.length > 0 && <div className="ag-grid">{mine.map((c) => <Card key={c.courthouse_id} c={c} onOpen={onOpen} />)}</div>}
        {rows && mine.length === 0 && !adding && <div className="pl-empty">No courthouses recorded here yet.</div>}
        {adding
          ? <DS.Card><DS.Card.Body>
              <CourthouseForm initial={{ state, county, court_entity_id: courtId || "" }}
                onCancel={() => setAdding(false)} onSaved={(id) => { setAdding(false); load(); onOpen(id); }} />
            </DS.Card.Body></DS.Card>
          : <button type="button" className="link-btn pl-add" onClick={() => setAdding(true)}><Ic n="plus" /> Add a courthouse</button>}
      </div>
    );
  }

  // ---- The courthouse page --------------------------------------------------
  function Row({ label, value, icon }) {
    if (value == null || value === "") return null;
    return (
      <div className="ch-row">
        <span className="ch-rowlabel"><Ic n={icon} /> {label}</span>
        <span className="ch-rowval">{value}</span>
      </div>
    );
  }

  function Page({ id, onBack, onOpenAgency, onOpenMatter, onOpenPlace }) {
    const { Button } = DS;
    const [data, setData] = React.useState(null);
    const [err, setErr] = React.useState(null);
    const [editing, setEditing] = React.useState(false);
    const [busy, setBusy] = React.useState(false);
    const reload = React.useCallback(() => {
      window.LedgerAPI.getCourthouse(id).then(setData).catch((e) => setErr(e.message || String(e)));
    }, [id]);
    React.useEffect(() => { setData(null); setErr(null); setEditing(false); if (canUse()) reload(); }, [id, reload]);
    React.useEffect(() => { icons(); }, [data, editing]);

    const back = <div className="crumb" onClick={onBack}><i data-lucide="arrow-left" /> Back</div>;
    if (!canUse()) return <div>{back}<div className="ledger-empty"><i data-lucide="lock" /><b>Courthouses are for Content Ops</b></div></div>;
    if (err) return <div>{back}<div className="login__err">{err}</div></div>;
    if (!data) return <div>{back}<div style={{ color: "var(--text-muted)", fontSize: 13 }}>Loading…</div></div>;

    const c = data.courthouse;
    const today = window.LedgerTime.todayEastern();
    const upcoming = data.events.filter((e) => (e.event_date || "") >= today).reverse();
    const past = data.events.filter((e) => (e.event_date || "") < today);
    const yn = (v) => (v === true ? "Yes" : v === false ? "No" : null);
    const who = (e) => (e ? String(e).split("@")[0] : null);
    async function remove() {
      if (!window.confirm(`Remove “${c.name}”? Its court dates lose the link; the notes are kept in history.`)) return;
      setBusy(true);
      try { await window.LedgerAPI.removeCourthouse(c.courthouse_id); onBack(); }
      catch (e) { setErr(e.message || String(e)); setBusy(false); }
    }
    const evRow = (e) => {
      const m = e.matters || {};
      return (
        <li key={e.event_id} style={{ cursor: onOpenMatter ? "pointer" : null }} onClick={() => onOpenMatter && onOpenMatter(e.matter_id)}>
          <div className="li-main">
            <b>{e.event_date ? window.LedgerTime.fmtDate(e.event_date) : "No date"}{e.event_time ? " · " + e.event_time.slice(0, 5) : ""} · {window.titleize(e.event_type || "court date")}</b>
            <span>{[m.display_id, m.display_alias || m.working_title].filter(Boolean).join(" · ")}{e.courtroom ? " · " + e.courtroom : ""}{e.judge_name ? " · " + e.judge_name : ""}</span>
          </div>
          <i data-lucide="chevron-right" style={{ width: 16, height: 16, color: "var(--lc-slate-300)" }} />
        </li>
      );
    };

    return (
      <div>
        {back}
        <div className="page-head">
          <div>
            <div className="eyebrow">Courthouse{place(c) ? " · " + place(c) : ""}</div>
            <h1 className="page-title">{c.name}<window.LedgerComment section="Courthouse page" /></h1>
            <div className="ch-sub">
              {c.court
                ? <span>Court: <button type="button" className="link-btn" onClick={() => onOpenAgency && onOpenAgency(c.court.entity_id)}>{c.court.entity_name}</button></span>
                : <span>No court linked yet</span>}
              {c.county && onOpenPlace && <span> · <button type="button" className="link-btn" onClick={() => onOpenPlace({ state: c.state, county: c.county })}>{c.county} County, {c.state}</button></span>}
              {c.address && <span> · {c.address}</span>}
            </div>
          </div>
          {!editing && (
            <div style={{ display: "flex", gap: 8 }}>
              <Button variant="secondary" icon="pencil" onClick={() => setEditing(true)}>Edit</Button>
              <Button variant="ghost" icon="trash-2" onClick={remove} disabled={busy}>Remove</Button>
            </div>
          )}
        </div>

        <div className="ch-owner">
          {data.owner && <span><Ic n="user-check" /> Notes owner: <b>{data.owner}</b></span>}
          <span>Last edited by {who(c.updated_email) || who(c.created_email) || "—"} on {window.LedgerTime.fmtDate(String(c.updated_at).slice(0, 10))}</span>
          {c.last_visited && <span>Crew last there {window.LedgerTime.fmtDate(c.last_visited)}</span>}
        </div>

        {editing ? (
          <DS.Card style={{ marginBottom: 22 }}><DS.Card.Body>
            <CourthouseForm initial={c} onCancel={() => setEditing(false)} onSaved={() => { setEditing(false); reload(); }} />
          </DS.Card.Body></DS.Card>
        ) : (
          <div className="ag-detail-two">
            <div>
              <div className="form-subhead">Production checklist</div>
              <DS.Card style={{ marginBottom: 20 }}><DS.Card.Body>
                <Row label="Audio" icon="mic" value={c.audio} />
                <Row label="XLR patch" icon="cable" value={yn(c.xlr_patch)} />
                <Row label="Signal" icon="signal" value={[c.signal && SIGNAL[c.signal], c.signal_notes].filter(Boolean).join(" · ") || null} />
                <Row label="Power" icon="plug" value={c.power_notes} />
                <Row label="Camera rules" icon="video" value={c.camera_rules} />
                <Row label="Load-in" icon="truck" value={c.parking_load_in} />
                <Row label="On site" icon="user" value={c.contact_on_site} />
                {![c.audio, c.xlr_patch, c.signal, c.signal_notes, c.power_notes, c.camera_rules, c.parking_load_in, c.contact_on_site].some((v) => v != null && v !== "") && (
                  <div className="pl-empty">Nothing recorded yet. <button type="button" className="link-btn" onClick={() => setEditing(true)}>Add production notes</button></div>
                )}
              </DS.Card.Body></DS.Card>
            </div>
            <div>
              <div className="form-subhead">Courtrooms and notes</div>
              <DS.Card style={{ marginBottom: 20 }}><DS.Card.Body>
                {c.courtroom_notes && <div className="ag-notes">{c.courtroom_notes}</div>}
                {c.notes && <div className="ag-notes">{c.notes}</div>}
                {!c.courtroom_notes && !c.notes && <div className="pl-empty">No notes yet.</div>}
              </DS.Card.Body></DS.Card>
            </div>
          </div>
        )}

        {window.LedgerAttachments && (
          <DS.Card style={{ marginBottom: 20 }}><DS.Card.Body>
            <window.LedgerAttachments entityType="courthouse" entityId={c.courthouse_id} />
          </DS.Card.Body></DS.Card>
        )}

        <div className="form-subhead">Upcoming court dates here ({upcoming.length})</div>
        {upcoming.length === 0
          ? <div className="pl-empty" style={{ marginBottom: 18 }}>None on the calendar.</div>
          : <DS.Card style={{ marginBottom: 18 }}><DS.Card.Body style={{ padding: 0 }}><ul className="linklist">{upcoming.map(evRow)}</ul></DS.Card.Body></DS.Card>}
        {past.length > 0 && (
          <details className="ch-past">
            <summary>Past court dates ({past.length})</summary>
            <DS.Card><DS.Card.Body style={{ padding: 0 }}><ul className="linklist">{past.map(evRow)}</ul></DS.Card.Body></DS.Card>
          </details>
        )}
      </div>
    );
  }

  window.LedgerCourthouses = { canUse, Section, Page, chips, SIGNAL, stateName };
})();
