/* Stratum Leads — Operations Console. Gate Review (Governance): the platform-admin
   control point for the three gates from docs/ADMIN_CRAWL_CONTROL_PLAN.md —
   runtime_gate (crawler/enrichment execution), data_mutation_gate (verify/reject),
   crawl_publish_gate (publish to marketplace). Hold/open a gate, and approve/hold
   the gated actions queued against it. Every decision is written to the Audit Log
   (which lives beside this surface in the Governance family). 100% mock; all
   privileged actions gate on is_platform_admin() in Phase 2.
   UNIQUE top-level names only (shared global scope — see the fmtUSD trap). */

const { Button, Card, Metric, StatusChip, Switch, EmptyState } = window.StratumLeadsDesignSystem_6367ed;
const { I } = window.OpsShared;

const GR_KIND_ICON = { run: "play", enrichment: "contact", publish: "upload-cloud", credential: "key-round", review: "list-checks" };
const GR_GATE_LABEL = { runtime_gate: "runtime_gate", data_mutation_gate: "data_mutation_gate", crawl_publish_gate: "crawl_publish_gate" };

function GrGateCard({ g, open, onToggle }) {
  return (
    <Card style={{ borderLeft: `3px solid ${open ? "var(--success)" : "var(--danger)"}` }}>
      <div style={{ display: "grid", gap: 12 }}>
        <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 12 }}>
          <div style={{ minWidth: 0 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <strong style={{ fontSize: 15, fontWeight: 800 }}>{g.name}</strong>
              {g.autoApprove && <StatusChip tone="neutral">auto-approve</StatusChip>}
            </div>
            <code style={{ fontSize: 11.5, color: "var(--text-muted)", fontFamily: "var(--font-mono)" }}>{g.action}</code>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <StatusChip tone={open ? "success" : "danger"} dot>{open ? "Open" : "Held"}</StatusChip>
            <Switch checked={open} onChange={() => onToggle(g)} />
          </div>
        </div>
        <p style={{ margin: 0, fontSize: 12.5, color: "var(--text-muted)" }}>{g.description}</p>
        <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12, color: "var(--text-subtle)", paddingTop: 6, borderTop: "1px solid var(--border-subtle)" }}>
          {I("shield", { width: 13 })} Gates: {g.gates}
        </div>
      </div>
    </Card>);

}

function GrApproval({ a, gateOpen, onDecide }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 14, alignItems: "center", padding: "14px 4px", borderTop: "1px solid var(--border-subtle)" }}>
      <span style={{ width: 34, height: 34, flexShrink: 0, display: "grid", placeItems: "center", borderRadius: "50%", background: "var(--accent-soft)", color: "var(--accent)" }}>{I(GR_KIND_ICON[a.kind] || "circle-dot", { width: 16 })}</span>
      <span style={{ minWidth: 0 }}>
        <strong style={{ fontSize: 13.5, display: "block" }}>{a.title}</strong>
        <span style={{ fontSize: 11.5, color: "var(--text-muted)" }}>
          {a.target} · requested by {a.requestedBy} · {a.requestedAt}
        </span>
        <span style={{ display: "inline-flex", marginTop: 5 }}>
          <StatusChip tone={gateOpen ? "neutral" : "warning"}>{GR_GATE_LABEL[a.gate] || a.gate}{gateOpen ? "" : " · held"}</StatusChip>
        </span>
      </span>
      <span style={{ display: "flex", gap: 8 }}>
        <Button size="sm" variant="secondary" icon={I("pause", { width: 14 })} onClick={() => onDecide(a, "hold")}>Hold</Button>
        <Button size="sm" variant="primary" disabled={!gateOpen} title={gateOpen ? undefined : "Gate is held — open it first"} icon={I("check", { width: 14 })} onClick={() => onDecide(a, "approve")}>Approve</Button>
      </span>
    </div>);

}

function GateReviewPage({ governance, onGateToggle, onDecide, onNavigate }) {
  const [held, setHeld] = React.useState(() => {
    const h = {};governance.gates.forEach((g) => h[g.id] = g.state === "held");return h;
  });
  const [approvals, setApprovals] = React.useState(() => governance.approvals.slice());
  React.useEffect(refresh, [held, approvals.length]);

  const isOpen = (gateId) => !held[gateId];
  const toggleGate = (g) => {
    const nowHeld = !held[g.id];
    setHeld((h) => ({ ...h, [g.id]: nowHeld }));
    onGateToggle && onGateToggle(g, nowHeld ? "held" : "open");
  };
  const decide = (a, decision) => {
    setApprovals((prev) => prev.filter((x) => x.id !== a.id));
    onDecide && onDecide(a, decision);
  };

  const heldCount = governance.gates.filter((g) => held[g.id]).length;
  const openCount = governance.gates.length - heldCount;

  return (
    <div style={{ padding: 24, width: "100%", maxWidth: "var(--page-max)" }}>
      <PageHeader eyebrow="Governance" title="Gate Review"
        description="Hold or open the platform gates, and approve the actions queued against them. Every decision is written to the Audit Log. Privileged actions require is_platform_admin()."
        actions={<Button variant="secondary" icon={I("history", { width: 15 })} onClick={() => onNavigate("auditlog")}>Audit Log</Button>} />

      <Reveal style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px,1fr))", gap: 14, marginBottom: 22 }}>
        <Metric icon={I("inbox")} value={approvals.length} label="Pending approvals" accent="amber" />
        <Metric icon={I("lock")} value={heldCount} label="Gates held" accent={heldCount ? "amber" : "green"} />
        <Metric icon={I("lock-open")} value={openCount} label="Gates open" accent="green" />
        <Metric icon={I("shield-check")} value={governance.admins.length} label="Platform admins" accent="violet" />
      </Reveal>

      <Reveal delay={60} style={{ marginBottom: 22 }}>
        <div style={{ marginBottom: 12, fontSize: 13, fontWeight: 800, color: "var(--text-muted)", textTransform: "uppercase", letterSpacing: "0.04em" }}>Governance gates</div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(300px,1fr))", gap: 16 }}>
          {governance.gates.map((g) => <GrGateCard key={g.id} g={g} open={isOpen(g.id)} onToggle={toggleGate} />)}
        </div>
      </Reveal>

      <Reveal delay={100} style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 20, alignItems: "start" }}>
        <Card title="Pending approvals" note="Gated actions awaiting a platform-admin decision">
          {approvals.length === 0 ?
          <EmptyState icon="check-circle-2" title="All clear" message="No gated actions are waiting on review." /> :
          <div>{approvals.map((a) => <GrApproval key={a.id} a={a} gateOpen={isOpen(a.gate)} onDecide={decide} />)}</div>}
        </Card>

        <Card title="Platform admins" note="is_platform_admin() — separate principal from tenants">
          <div style={{ display: "grid", gap: 2 }}>
            {governance.admins.map((ad, i) =>
            <div key={ad.email} style={{ display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 12, alignItems: "center", padding: "12px 4px", borderTop: i === 0 ? "none" : "1px solid var(--border-subtle)" }}>
                <span style={{ width: 34, height: 34, display: "grid", placeItems: "center", borderRadius: "50%", background: "var(--accent-soft)", color: "var(--accent)", fontWeight: 800, fontSize: 12 }}>{ad.name.split(" ").map((w) => w[0]).slice(0, 2).join("")}</span>
                <span style={{ minWidth: 0 }}>
                  <strong style={{ fontSize: 13, display: "block" }}>{ad.name}</strong>
                  <span style={{ fontSize: 11.5, color: "var(--text-muted)" }}>{ad.email}</span>
                </span>
                <StatusChip tone="violet">{ad.role}</StatusChip>
              </div>
            )}
          </div>
          <div style={{ marginTop: 12, paddingTop: 12, borderTop: "1px solid var(--border-subtle)", fontSize: 11.5, color: "var(--text-subtle)", display: "flex", alignItems: "center", gap: 8 }}>
            {I("info", { width: 13 })} Role management arrives with the Phase-2 admin panel.
          </div>
        </Card>
      </Reveal>
    </div>);

}

Object.assign(window, { OpsGovernance: { GateReviewPage } });
