/* ============================================================================
   DIVONCI WORLD — SETTINGS  (screens_settings.jsx)
   ----------------------------------------------------------------------------
   Identity, roles & the data map. This is the human-readable view of the API
   seam: which resources exist, the role→area write matrix, and the live
   row count for every backend table (all read through DW.get).
   ========================================================================== */
const { useState: useStateSt, useEffect: useEffectSt } = React;

const ROLE_AREAS = ["clients", "projects", "foundry", "warroom", "council", "deployments", "evidence", "workrate", "risk"];
const ROLE_GRID = {
  sovereign: ["*"],
  commander: ["clients", "projects", "foundry", "warroom", "council", "deployments", "evidence"],
  operator:  ["projects", "foundry", "workrate", "deployments"],
  analyst:   ["evidence", "risk"],
  viewer:    [],
};

function ResourceMap() {
  const [counts, setCounts] = useStateSt({});
  const [loading, setLoading] = useStateSt(true);
  useEffectSt(() => {
    let alive = true;
    Promise.all((DW.RESOURCES || []).map((r) => DW.get(r, {}).then((rows) => [r, Array.isArray(rows) ? rows.length : 0]).catch(() => [r, -1])))
      .then((pairs) => { if (!alive) return; const o = {}; pairs.forEach(([k, v]) => (o[k] = v)); setCounts(o); setLoading(false); });
    const unsub = DW.subscribe("*", () => {
      DW.get("audit_events", {}).then((rows) => alive && setCounts((c) => ({ ...c, audit_events: rows.length })));
    });
    return () => { alive = false; unsub(); };
  }, []);
  if (loading) return <div style={{ padding: 18 }}><LoadingState lines={6} label="Querying resources" /></div>;
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(190px, 1fr))", gap: 8 }}>
      {(DW.RESOURCES || []).map((r) => (
        <div key={r} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "9px 12px", border: "1px solid var(--hairline)", borderRadius: "var(--r-sm)", background: "var(--panel)" }}>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-2)" }}>{r}</span>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 600, color: counts[r] < 0 ? "var(--state-crisis)" : "var(--violet-ink)" }}>{counts[r] < 0 ? "err" : counts[r]}</span>
        </div>
      ))}
    </div>
  );
}

function SettingsScreen() {
  const auth = useAuth();
  return (
    <div className="screen">
      <div className="screen-head">
        <div>
          <div className="title"><span className="sub">System</span>Settings</div>
          <div className="meta">Identity, roles and the data map. This is the operator’s view of the API seam — the contract every screen reads and writes through.</div>
        </div>
      </div>

      <div className="cols c-8-4" style={{ alignItems: "start" }}>
        <div style={{ display: "grid", gap: "var(--s-6)" }}>
          {/* roles matrix */}
          <Panel className="tight">
            <PHead icon="users" eyebrow="Roles · write matrix" right={<span className="client-mono">DW.can(role, area)</span>} />
            <div style={{ overflowX: "auto" }}>
              <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
                <thead>
                  <tr>
                    <th style={{ textAlign: "left", padding: "10px 14px", fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--ink-4)" }}>Role</th>
                    {ROLE_AREAS.map((a) => <th key={a} style={{ padding: "10px 6px", fontFamily: "var(--font-mono)", fontSize: 9, color: "var(--ink-4)", textTransform: "uppercase" }}>{a.slice(0, 4)}</th>)}
                  </tr>
                </thead>
                <tbody>
                  {Object.keys(ROLE_GRID).map((role) => (
                    <tr key={role} style={{ borderTop: "1px solid var(--hairline)", background: role === auth.user.role ? "var(--active-dim)" : "transparent" }}>
                      <td style={{ padding: "9px 14px", fontWeight: 600 }}>{role}{role === auth.user.role ? " ←" : ""}</td>
                      {ROLE_AREAS.map((a) => {
                        const ok = ROLE_GRID[role].includes("*") || ROLE_GRID[role].includes(a);
                        return <td key={a} style={{ textAlign: "center", padding: "9px 6px" }}>{ok ? <Icon name="check" style={{ width: 13, height: 13, color: "var(--state-clear)" }} /> : <span style={{ color: "var(--ink-4)" }}>·</span>}</td>;
                      })}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </Panel>

          {/* data map */}
          <Panel className="tight">
            <PHead icon="database" eyebrow="Data map · resources" right={<span className="client-mono">{(DW.RESOURCES || []).length} tables · DW.get(resource)</span>} />
            <div style={{ padding: "var(--s-6)" }}><ResourceMap /></div>
          </Panel>
        </div>

        {/* identity rail */}
        <div style={{ display: "grid", gap: "var(--s-6)" }}>
          <Panel style={{ padding: "var(--s-7)" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 13, marginBottom: 16 }}>
              <div className="d-avatar" style={{ width: 42, height: 42, fontSize: 17 }}>D</div>
              <div><div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 16 }}>{auth.user.name}</div><div className="client-mono">{auth.user.title}</div></div>
            </div>
            <div className="loop-k" style={{ marginBottom: 8 }}>Active role</div>
            <div style={{ display: "flex", gap: 7, flexWrap: "wrap" }}>
              {Object.keys(ROLE_GRID).map((r) => (
                <button key={r} className={"role-pill"} style={{ borderColor: r === auth.user.role ? "var(--violet-bright)" : undefined, color: r === auth.user.role ? "var(--violet-ink)" : undefined }} onClick={() => auth.signInAs(r)}>{r}</button>
              ))}
            </div>
            <div className="client-mono" style={{ marginTop: 12, lineHeight: 1.6, color: "var(--ink-4)" }}>Switching role re-renders every gated control across the OS via DW.subscribe('auth').</div>
          </Panel>

          <Panel style={{ padding: "var(--s-7)" }}>
            <div className="loop-k" style={{ marginBottom: 10 }}>Seam status</div>
            <div style={{ display: "grid", gap: 9 }}>
              {[["API seam", "dw-api.js · online", "clear"], ["Realtime", "DW.subscribe · in-memory pulse", "clear"], ["Supabase", "not connected · // ⇄ markers ready", "caution"], ["Audit log", "writing on every mutate", "clear"]].map(([k, v, s], i) => (
                <div key={i} style={{ display: "flex", alignItems: "center", gap: 9, fontSize: 12.5 }}>
                  <Led state={s} size={7} /><span style={{ color: "var(--ink-2)" }}>{k}</span>
                  <span style={{ marginLeft: "auto", fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--ink-4)" }}>{v}</span>
                </div>
              ))}
            </div>
          </Panel>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { SettingsScreen });
