/* ============================================================
   Dinasty Control — AI Risk Governor
   ============================================================ */

const GOV_TONE = {
  ALLOW: "var(--pos)",
  TEST_SMALL: "var(--warn)",
  PAUSE: "var(--neg)",
  BLOCK: "var(--neg)",
};

function GovStat({ label, value, color }) {
  return (
    <div style={{ background: "var(--panel)", border: "1px solid var(--border)", borderRadius: 6, padding: "8px 13px" }}>
      <div style={{ fontSize: 9.5, color: "var(--muted)", letterSpacing: ".08em", textTransform: "uppercase", fontWeight: 600 }}>{label}</div>
      <div className="mono" style={{ fontSize: 16, fontWeight: 700, color: color || "var(--text)" }}>{value}</div>
    </div>
  );
}

function GovPill({ value }) {
  const color = GOV_TONE[value] || "var(--muted)";
  return (
    <span className="mono" style={{
      display: "inline-block", minWidth: 76, textAlign: "center", fontSize: 10,
      fontWeight: 700, color, border: `1px solid ${color}66`,
      background: color + "18", borderRadius: 4, padding: "3px 7px",
    }}>{value}</span>
  );
}

function RiskGovernor() {
  const [data, setData] = React.useState(null);
  const [err, setErr] = React.useState("");
  const [loading, setLoading] = React.useState(true);
  const [running, setRunning] = React.useState(false);
  const [filter, setFilter] = React.useState("all");

  async function load() {
    setLoading(true); setErr("");
    try {
      const r = await fetch("/api/ai-risk-governor");
      const d = await r.json();
      if (!d.ok) setErr(d.message || "Report belum tersedia.");
      setData(d);
    } catch (e) {
      setErr(String(e));
    }
    setLoading(false);
  }

  async function run(apply) {
    setRunning(true); setErr("");
    try {
      const r = await fetch("/api/ai-risk-governor/run", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ apply }),
      });
      const d = await r.json();
      if (!d.ok) throw new Error(d.message || "Governor run failed.");
      setData(d.report);
    } catch (e) {
      setErr(String(e.message || e));
    }
    setRunning(false);
  }

  React.useEffect(() => { load(); }, []);

  if (loading) return <div className="placeholder"><p>Memuat Risk Governor...</p></div>;

  const s = data?.summary || {};
  const counts = s.decision_counts || {};
  const exposure = s.exposure || {};
  let rows = data?.decisions || [];
  if (filter !== "all") rows = rows.filter(r => r.decision === filter);

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%", overflow: "hidden" }}>
      <div style={{ padding: "14px 18px 0", flexShrink: 0 }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, marginBottom: 12 }}>
          <div>
            <span style={{ fontWeight: 700, fontSize: 15, letterSpacing: ".04em" }}>AI Risk Governor</span>
            <span style={{ color: "var(--dim)", fontSize: 11, marginLeft: 12, fontFamily: "var(--mono)" }}>
              {data?.generated_at ? data.generated_at.slice(0, 19).replace("T", " ") + " WIB" : "no report"}
            </span>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={() => run(false)} disabled={running} style={{ background: "none", border: "1px solid var(--border)", color: "var(--muted)", borderRadius: 5, padding: "5px 10px", cursor: "pointer", fontSize: 11 }}>
              {running ? "Running..." : "Run Shadow"}
            </button>
            <button onClick={() => run(true)} disabled={running} style={{ background: "rgba(236,186,90,.12)", border: "1px solid rgba(236,186,90,.45)", color: "var(--accent)", borderRadius: 5, padding: "5px 10px", cursor: "pointer", fontSize: 11, fontWeight: 700 }}>
              Apply Governor
            </button>
            <button onClick={load} disabled={running} style={{ background: "none", border: "1px solid var(--border)", color: "var(--muted)", borderRadius: 5, padding: "5px 10px", cursor: "pointer", fontSize: 11 }}>Refresh</button>
          </div>
        </div>

        {err && <div style={{ color: "var(--neg)", fontSize: 12, marginBottom: 10 }}>{err}</div>}

        <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginBottom: 12 }}>
          <GovStat label="Mode" value={data?.mode || "—"} color={data?.mode === "applied" ? "var(--accent)" : "var(--muted)"} />
          <GovStat label="ALLOW" value={counts.ALLOW || 0} color="var(--pos)" />
          <GovStat label="TEST SMALL" value={counts.TEST_SMALL || 0} color="var(--warn)" />
          <GovStat label="PAUSE" value={counts.PAUSE || 0} color="var(--neg)" />
          <GovStat label="Net Hist USC" value={s.overall ? ((s.overall.net >= 0 ? "+" : "") + s.overall.net) : "—"} color={s.overall?.net >= 0 ? "var(--pos)" : "var(--neg)"} />
          <GovStat label="PF" value={s.overall?.profit_factor || "—"} />
        </div>

        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 10 }}>
          {["all", "ALLOW", "TEST_SMALL", "PAUSE", "BLOCK"].map(x => (
            <button key={x} onClick={() => setFilter(x)} style={{
              background: filter === x ? "rgba(236,186,90,.12)" : "none",
              border: filter === x ? "1px solid rgba(236,186,90,.45)" : "1px solid var(--border)",
              color: filter === x ? "var(--accent)" : "var(--muted)",
              borderRadius: 4, padding: "3px 9px", cursor: "pointer", fontSize: 11,
            }}>{x === "all" ? "Semua" : x}</button>
          ))}
        </div>

        <div style={{ color: "var(--muted)", fontSize: 11.5, marginBottom: 10 }}>
          Session: <span className="mono" style={{ color: "var(--text)" }}>{s.session?.mode || "—"}</span>
          {" · "}
          Exposure: <span className="mono" style={{ color: exposure.blocks?.length ? "var(--warn)" : "var(--pos)" }}>{exposure.blocks?.length ? JSON.stringify(exposure.blocks) : "clear"}</span>
          {" · "}
          Safety: <span>{data?.safety || "—"}</span>
        </div>
      </div>

      <div style={{ flex: 1, overflowY: "auto", padding: "0 18px 18px" }}>
        <table className="mtable" style={{ width: "100%", borderCollapse: "collapse" }}>
          <thead>
            <tr>
              {["Set", "Account", "Slot", "Decision", "Risk x", "Flags", "Reason"].map(h => (
                <th key={h} style={{ fontSize: 9.5, letterSpacing: ".07em", color: "var(--muted)", fontWeight: 600,
                  textTransform: "uppercase", padding: "7px 8px", borderBottom: "1px solid var(--border)",
                  textAlign: "left", whiteSpace: "nowrap", position: "sticky", top: 0, background: "var(--bg)", zIndex: 2 }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map(row => (
              <tr key={row.set_id} className="mrow">
                <td className="mono" style={{ fontSize: 11.5 }}>{row.set_id}</td>
                <td className="mono" style={{ fontSize: 11.5 }}>{row.account_code}</td>
                <td style={{ fontSize: 11 }}>{row.slot_role || row.slot_no}</td>
                <td><GovPill value={row.decision} /></td>
                <td className="mono" style={{ color: row.risk_multiplier > 0 ? "var(--text)" : "var(--neg)", fontSize: 11.5 }}>{row.risk_multiplier}</td>
                <td style={{ color: "var(--muted)", fontSize: 11 }}>{(row.risk_flags || []).join(", ")}</td>
                <td style={{ color: "var(--muted)", fontSize: 11.5, maxWidth: 520 }}>{row.reason}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

window.RiskGovernor = RiskGovernor;
