/* ============================================================
   Dinasty Control — AI Daily Evaluation (SCREEN 4)
   End-of-session report: summary, risk warnings, best/worst
   slots, hedge effectiveness, and recommended action grid.
   All values derived deterministically from window.DINASTY.
   ============================================================ */

const REPORT_DATE = "2026-06-04";
const EVAL_WINDOW = "00:00 – 09:45 UTC";

/* ---------- circular gauge for hedge score ---------- */
function Gauge({ value }) {
  const r = 50, c = 2 * Math.PI * r;
  const pct = Math.max(0, Math.min(100, value)) / 100;
  const tone = value >= 70 ? "var(--pos)" : value >= 50 ? "var(--warn)" : "var(--neg)";
  return (
    <div className="gauge">
      <svg viewBox="0 0 120 120" width="118" height="118">
        <circle cx="60" cy="60" r={r} fill="none" stroke="rgba(255,255,255,.06)" strokeWidth="9" />
        <circle cx="60" cy="60" r={r} fill="none" stroke={tone} strokeWidth="9" strokeLinecap="round"
          strokeDasharray={c} strokeDashoffset={c * (1 - pct)} />
      </svg>
      <div className="gauge-mid">
        <span className="gauge-val" style={{ color: tone }}>{value}</span>
        <span className="gauge-cap">Score / 100</span>
      </div>
    </div>
  );
}

function DailyEval({ data, onOpenSet }) {
  const { rows, overview: o, monitor } = data;

  /* ---------- daily summary bullets ---------- */
  const summary = useMemo(() => {
    const buyShare = Math.round((o.buyLots / (o.buyLots + o.sellLots || 1)) * 100);
    const skewSide = buyShare >= 50 ? "BUY" : "SELL";
    const skewPct = buyShare >= 50 ? buyShare : 100 - buyShare;
    const worstDD = rows.reduce((m, r) => (r.drawdown > m.drawdown ? r : m), rows[0]);
    const best = [...rows].sort((a, b) => b.pl - a.pl)[0];
    const worst = [...rows].sort((a, b) => a.pl - b.pl)[0];
    const postureNote = { NORMAL: "edge intact across the book", WATCH: "elevated risk — heightened monitoring", REDUCE: "de-risking — exposure trimmed", PAUSE: "capital-protection halt engaged" }[o.aiStatus];
    return [
      { tone: o.dailyPL >= 0 ? "pos" : "neg", node: (<>Closed the session at <b className="mono">{fmtMoney(o.totalEquity)}</b> equity on net daily P/L of <span className="mono"><Num value={o.dailyPL} money showArrow={false} /></span>, with <span className="mono"><Num value={o.floatingPL} money showArrow={false} /></span> still floating across {o.counts.openSets} open sets.</>) },
      { tone: o.counts.pause ? "neg" : "warn", node: (<>AI issued <b>{o.counts.pause + o.counts.reduce} interventions</b> over {o.counts.total} scored sets — <b style={{ color: "var(--neg)" }}>{o.counts.pause} halted</b>, <b style={{ color: "var(--warn)" }}>{o.counts.reduce} throttled</b>, {o.counts.normal} left running normally.</>) },
      { tone: "accent", node: (<>Book leaned <b>{skewSide} {skewPct}%</b> by volume — <span className="mono">{o.buyLots.toFixed(1)}</span> buy vs <span className="mono">{o.sellLots.toFixed(1)}</span> sell lots; net exposure within mandate.</>) },
      { tone: o.ddPct > 8 ? "neg" : "warn", node: (<>Peak drawdown reached <b style={{ color: o.ddPct > 8 ? "var(--neg)" : "var(--warn)" }}>−{o.ddPct}%</b> (−{fmtMoney(o.ddAmount).slice(1)}); deepest single set <b className="mono">{worstDD.id}</b> at −{worstDD.drawdown}%.</>) },
      { tone: "dim", node: (<>Top contributor <b className="mono">{best.id}</b> <span className="mono"><Num value={best.pl} money showArrow={false} /></span>; weakest <b className="mono">{worst.id}</b> <span className="mono"><Num value={worst.pl} money showArrow={false} /></span>.</>) },
      { tone: o.aiStatus === "NORMAL" ? "pos" : o.aiStatus === "PAUSE" ? "neg" : "warn", node: (<>Posture closes the window at <b><AIBadge status={o.aiStatus} /></b> — {postureNote}.</>) },
    ];
  }, [rows, o]);

  /* ---------- risk warnings (P0 / P1 / P2) ---------- */
  const warnings = useMemo(() => {
    const w = [];
    const paused = rows.filter((r) => r.rec === "PAUSE").sort((a, b) => a.pf - b.pf);
    const reduced = rows.filter((r) => r.rec === "REDUCE");
    paused.slice(0, 2).forEach((r) => w.push({ sev: "P0", set: r.id, node: (<>PF <b>{r.pf.toFixed(2)}</b> below 0.85 floor — trading <b>halted</b>, edge lost.</>) }));
    if (o.ddPct >= 8) w.push({ sev: "P0", set: "PORTFOLIO", node: (<>Drawdown <b>−{o.ddPct}%</b> (−{fmtMoney(o.ddAmount).slice(1)}) breaching the 8% capital guard.</>) });
    const worstPL = [...rows].sort((a, b) => a.pl - b.pl)[0];
    if (worstPL.pl < -1200) w.push({ sev: "P1", set: worstPL.id, node: (<>Realised <b>−${Math.abs(worstPL.pl).toLocaleString()}</b> — largest single-set loss of the session.</>) });
    w.push({ sev: "P1", set: "VPS-2", node: (<>Latency <b>214ms</b> sustained — execution slippage risk on fills.</>) });
    const streak = [...rows].sort((a, b) => b.lossStreak - a.lossStreak)[0];
    if (streak.lossStreak >= 6) w.push({ sev: "P1", set: streak.id, node: (<>Loss streak <b>{streak.lossStreak}</b> consecutive — momentum breakdown.</>) });
    w.push({ sev: "P2", set: `${reduced.length} SETS`, node: (<>Throttled to <b>0.5× lots</b> on elevated drawdown — monitor for recovery.</>) });
    const grids = rows.filter((r) => r.role === "Grid" && r.openPos >= 5);
    if (grids.length) w.push({ sev: "P2", set: `${grids.length} GRIDS`, node: (<>Grid sets near max layers — basket exposure approaching cap.</>) });
    const order = { P0: 0, P1: 1, P2: 2 };
    return w.sort((a, b) => order[a.sev] - order[b.sev]);
  }, [rows, o]);

  const isSet = (s) => /^A\d{2}-\d{2}$/.test(s);

  /* ---------- best / worst slots ---------- */
  const best = useMemo(() => [...rows].sort((a, b) => b.pl - a.pl).slice(0, 5), [rows]);
  const worst = useMemo(() => [...rows].sort((a, b) => a.pl - b.pl).slice(0, 5), [rows]);

  /* ---------- hedge effectiveness ---------- */
  const hedge = useMemo(() => {
    const pairs = {};
    monitor.filter((m) => m.hedge).forEach((m) => { (pairs[m.hedge.id] = pairs[m.hedge.id] || []).push(m); });
    const arr = Object.values(pairs).filter((p) => p.length === 2);
    let offsetSum = 0, netR = 0, grossR = 0;
    arr.forEach(([a, b]) => {
      const net = a.r + b.r, gross = Math.abs(a.r) + Math.abs(b.r) + 1e-3;
      netR += net; grossR += gross;
      offsetSum += 1 - Math.abs(net) / gross;
    });
    const avgOffset = arr.length ? offsetSum / arr.length : 0;
    const score = Math.round(avgOffset * 100);
    const note = score >= 70
      ? <>Hedge legs are <b>absorbing directional risk effectively</b> — opposing positions cancel most adverse moves. No rebalance required this window.</>
      : score >= 50
      ? <>Partial offset — pairs <b>drifting slightly directional</b>. Net exposure is contained but worth monitoring into the next session.</>
      : <>Weak offset — legs have <b>decoupled directionally</b>. Review pair sizing; hedges are carrying unintended net exposure.</>;
    return { score, pairs: arr.length, avgOffset: Math.round(avgOffset * 100), netR: Math.round(netR * 10) / 10, note };
  }, [monitor]);

  /* ---------- recommended action per account × slot ---------- */
  const recMatrix = useMemo(() => {
    const accOrder = [];
    rows.forEach((r) => { if (!accOrder.find((a) => a.account === r.account)) accOrder.push({ account: r.account, vps: r.vps }); });
    const rank = { NORMAL: 0, REDUCE: 1, PAUSE: 2 }, names = ["NORMAL", "REDUCE", "PAUSE"];
    const slots = [1, 2, 3, 4, 5, 6, 7, 8];
    const grid = accOrder.map((a) => ({
      ...a,
      cells: slots.map((s) => {
        const rs = rows.filter((r) => r.account === a.account && r.slot === s);
        const mx = rs.reduce((m, r) => Math.max(m, rank[r.rec]), 0);
        return names[mx];
      }),
    }));
    return { grid, slots };
  }, [rows]);

  return (
    <div className="screen screen-daily">
      <div className="screen-head">
        <div className="screen-title">AI Daily Evaluation</div>
        <div className="screen-sub">Session report · <b>{REPORT_DATE}</b> · {EVAL_WINDOW} · {o.counts.total} sets evaluated</div>
      </div>

      {/* report summary strip */}
      <div className="blotter-sum">
        <div className="bs-item"><span className="bs-lbl">REPORT DATE</span><span className="bs-val mono">{REPORT_DATE}</span></div>
        <div className="bs-item"><span className="bs-lbl">EVAL WINDOW</span><span className="bs-val mono">{EVAL_WINDOW}</span></div>
        <div className="bs-item"><span className="bs-lbl">POSTURE</span><span className="bs-val bs-badge"><AIBadge status={o.aiStatus} /></span></div>
        <div className="bs-item"><span className="bs-lbl">NET DAILY P/L</span><span className="bs-val mono"><Num value={o.dailyPL} money showArrow={false} /></span></div>
        <div className="bs-item"><span className="bs-lbl">INTERVENTIONS</span><span className="bs-val mono">{o.counts.pause + o.counts.reduce} <i>of {o.counts.total}</i></span></div>
        <div className="filter-spacer"></div>
        <div className="bs-item"><span className="bs-lbl">HEDGE SCORE</span><span className={`bs-val mono ${hedge.score >= 70 ? "pos" : hedge.score >= 50 ? "warn" : "neg"}`}>{hedge.score}<i>/100</i></span></div>
      </div>

      <div className="de-scroll">
        {/* row 1 — summary + risk warnings */}
        <div className="de-row de-row-2">
          <section className="panel">
            <div className="panel-head"><span className="panel-title">Daily Summary</span><span className="panel-gen">auto-generated 09:45 UTC</span></div>
            <ul className="de-bullets">
              {summary.map((b, i) => (
                <li key={i} className="de-bul">
                  <span className={`de-bul-mk t-${b.tone}`}></span>
                  <span>{b.node}</span>
                </li>
              ))}
            </ul>
          </section>

          <section className="panel">
            <div className="panel-head"><span className="panel-title">Risk Warnings</span><span className="panel-meta mono">{warnings.length} active</span></div>
            <ul className="rw-list">
              {warnings.map((w, i) => (
                <li key={i} className={`rw-item ${isSet(w.set) ? "clickable" : ""}`} onClick={() => isSet(w.set) && onOpenSet(w.set)}>
                  <span className={`sev sev-${w.sev.toLowerCase()}`}>{w.sev}</span>
                  <span className="rw-set">{w.set}</span>
                  <span className="rw-text">{w.node}</span>
                </li>
              ))}
            </ul>
          </section>
        </div>

        {/* row 2 — best/worst slots + hedge effectiveness */}
        <div className="de-row de-row-bw">
          <section className="panel">
            <div className="panel-head"><span className="panel-title">Best / Worst Slots</span><span className="panel-meta">by realised P/L</span></div>
            <div className="bw-cols">
              <div>
                <div className="bw-col-title up"><span className="tri">▲</span>Top 5</div>
                <ul className="slot-list">
                  {best.map((r, i) => (
                    <li key={r.id} className="slot-item" onClick={() => onOpenSet(r.id)}>
                      <span className="slot-rank">{i + 1}</span>
                      <span className="slot-mid">
                        <span className="slot-id">{r.id}</span>
                        <span className="slot-meta">{r.role} · {r.symbol} · PF {r.pf.toFixed(2)}</span>
                      </span>
                      <span className="slot-pl"><Num value={r.pl} money showArrow={false} /></span>
                    </li>
                  ))}
                </ul>
              </div>
              <div>
                <div className="bw-col-title down"><span className="tri">▼</span>Bottom 5</div>
                <ul className="slot-list">
                  {worst.map((r, i) => (
                    <li key={r.id} className="slot-item" onClick={() => onOpenSet(r.id)}>
                      <span className="slot-rank">{i + 1}</span>
                      <span className="slot-mid">
                        <span className="slot-id">{r.id}</span>
                        <span className="slot-meta">{r.role} · {r.symbol} · PF {r.pf.toFixed(2)}</span>
                      </span>
                      <span className="slot-pl"><Num value={r.pl} money showArrow={false} /></span>
                    </li>
                  ))}
                </ul>
              </div>
            </div>
          </section>

          <section className="panel">
            <div className="panel-head"><span className="panel-title">Hedge Effectiveness</span><span className="panel-meta mono">{hedge.pairs} pairs</span></div>
            <div className="hedge-wrap">
              <Gauge value={hedge.score} />
              <div className="hedge-info">
                <div className="hedge-metrics">
                  <div className="hm-row"><span className="hm-lbl">Active pairs</span><span className="hm-val">{hedge.pairs}</span></div>
                  <div className="hm-row"><span className="hm-lbl">Avg offset</span><span className="hm-val">{hedge.avgOffset}%</span></div>
                  <div className="hm-row"><span className="hm-lbl">Net exposure</span><span className="hm-val" style={{ color: Math.abs(hedge.netR) <= 1.5 ? "var(--pos)" : "var(--warn)" }}>{hedge.netR >= 0 ? "+" : "−"}{Math.abs(hedge.netR)}R</span></div>
                </div>
                <div className="hedge-note">{hedge.note}</div>
              </div>
            </div>
          </section>
        </div>

        {/* row 3 — recommended action matrix */}
        <section className="panel">
          <div className="panel-head"><span className="panel-title">Recommended Action · Account × Slot</span><span className="panel-meta">worst-case per cell · next session</span></div>
          <div className="rm-wrap">
            <div className="rm-grid">
              <div className="rm-h rm-h-acct">Account</div>
              {recMatrix.slots.map((s) => <div key={s} className="rm-h">S{pad2s(s)}</div>)}
              {recMatrix.grid.map((acc) => (
                <React.Fragment key={acc.account}>
                  <div className="rm-acct"><span className="dot dot-ok" style={{ background: acc.vps === "VPS-2" ? "var(--warn)" : "var(--pos)", boxShadow: "none" }}></span>{acc.account}<span className="vps-mini">{acc.vps}</span></div>
                  {acc.cells.map((c, i) => (
                    <div key={i} className={`rm-cell rm-${c.toLowerCase()}`}>{c}</div>
                  ))}
                </React.Fragment>
              ))}
            </div>
          </div>
          <div className="rm-legend">
            <span className="rm-leg"><span className="sw rm-normal"></span>NORMAL — run as configured</span>
            <span className="rm-leg"><span className="sw rm-reduce"></span>REDUCE — scale lots 0.5×</span>
            <span className="rm-leg"><span className="sw rm-pause"></span>PAUSE — halt new entries</span>
            <span className="rm-leg-note">6 accounts · 8 slots · {o.counts.total} sets</span>
          </div>
        </section>
      </div>
    </div>
  );
}

const pad2s = (n) => String(n).padStart(2, "0");

window.DailyEval = DailyEval;
