// ============================================================
// WC26 — Dashboard (live recorder data · trading panels await Phase 1)
// ============================================================
function EquitySpark({ points, height = 120 }) {
  const ref = React.useRef(null);
  const [w, setW] = React.useState(500);
  React.useEffect(() => {
    const el = ref.current; if (!el) return;
    const ro = new ResizeObserver(() => setW(el.clientWidth));
    ro.observe(el); setW(el.clientWidth);
    return () => ro.disconnect();
  }, []);
  const min = Math.min(0, ...points), max = Math.max(...points, 1);
  const PAD = 8;
  const X = (i) => PAD + (i / (points.length - 1)) * (w - PAD * 2);
  const Y = (v) => PAD + (1 - (v - min) / (max - min)) * (height - PAD * 2);
  const line = points.map((v, i) => (i ? "L" : "M") + X(i).toFixed(1) + " " + Y(v).toFixed(1)).join(" ");
  const area = line + ` L ${X(points.length - 1)} ${Y(min)} L ${X(0)} ${Y(min)} Z`;
  return (
    <div ref={ref}>
      <svg width={w} height={height} style={{ display: "block" }}>
        <defs>
          <linearGradient id="eqFill" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="var(--pitch)" stopOpacity="0.22" />
            <stop offset="100%" stopColor="var(--pitch)" stopOpacity="0.02" />
          </linearGradient>
        </defs>
        <line x1={PAD} x2={w - PAD} y1={Y(0)} y2={Y(0)} stroke="var(--line-2)" strokeDasharray="3 4" />
        <path d={area} fill="url(#eqFill)" />
        <path d={line} fill="none" stroke="var(--pitch)" strokeWidth="2.5" strokeLinejoin="round" />
        <circle cx={X(points.length - 1)} cy={Y(points[points.length - 1])} r="4" fill="var(--pitch)" stroke="#fff" strokeWidth="1.5" />
      </svg>
    </div>
  );
}

function SystemBanner({ botMode }) {
  const h = WC.HEALTH || {};
  const killed = botMode === "killed";
  const paused = botMode === "paused";
  const counters = h.counters || {};
  const owner = Auth.isOwner;
  const [confirmKill, setConfirmKill] = React.useState(false);
  return (
    <div className="panel" style={{
      display: "flex", alignItems: "center", gap: 14, padding: "14px 18px", flexWrap: "wrap",
      borderLeft: `4px solid ${killed ? "var(--hot)" : paused ? "var(--gold)" : "var(--sky)"}`,
    }}>
      <span><span className="pulse-dot" style={{ animationPlayState: killed || paused ? "paused" : "running" }}></span></span>
      <div style={{ flex: 1, minWidth: 220 }}>
        <div className="bc-display" style={{ fontSize: 19 }}>
          {killed ? "Kill switch ON" : paused ? "Paused" : "System LIVE"}
          <span style={{ color: "var(--ink-3)", fontWeight: 600, marginLeft: 10, fontSize: 14, letterSpacing: ".06em" }}>SC1 + LA1 · PAPER · TVH-FOOTBALL</span>
        </div>
        <ThaiHint>
          {killed ? "ปิดทุก position เก็งกำไรแล้ว (lock sets ถือต่อ — riskless) · กด Re-arm เพื่อกลับมาเทรด"
            : paused ? "หยุดเปิดไม้ใหม่ — position เดิมยังบริหารตาม stop rule"
            : "recorder อัด data + bot เทรด paper อัตโนมัติ · ปุ่มควบคุมใช้ได้เมื่อ login Telegram (allowlist)"}
        </ThaiHint>
      </div>
      <Stat label="WS conns" value={h.connCount ?? "—"} sub="matches in window" />
      <Stat label="Book snaps" value={(counters.snapsWritten ?? 0).toLocaleString()} sub="since boot" />
      <Stat label="Score events" value={(counters.scoreEventsWritten ?? 0).toLocaleString()} sub="sports ws" />
      {killed ? (
        <button className="btn btn-green" disabled={!owner} title={owner ? "" : "ต้อง login Telegram"}
                onClick={() => saveControls({ killSwitch: false, mode: "recording-only" })}>▶ Re-arm Bot</button>
      ) : (
        <div style={{ display: "flex", gap: 8 }}>
          <button className="btn btn-ghost" disabled={!owner} title={owner ? "" : "ต้อง login Telegram"}
                  onClick={() => saveControls({ mode: paused ? "recording-only" : "paused" })}>
            {paused ? "▶ Resume" : "❚❚ Pause"}
          </button>
          {confirmKill ? (
            <span style={{ display: "inline-flex", gap: 8, alignItems: "center" }}>
              <span style={{ fontSize: 12, color: "var(--hot)", fontWeight: 600 }}>ปิดทุก position?</span>
              <button className="btn btn-danger btn-sm" onClick={() => { saveControls({ killSwitch: true }); setConfirmKill(false); }}>Confirm</button>
              <button className="btn btn-ghost btn-sm" onClick={() => setConfirmKill(false)}>No</button>
            </span>
          ) : (
            <button className="btn btn-danger" disabled={!owner} title={owner ? "" : "ต้อง login Telegram"}
                    onClick={() => setConfirmKill(true)}>Kill Switch</button>
          )}
        </div>
      )}
    </div>
  );
}

function TodayMatchCard({ f, nav }) {
  const live = f.status === "live";
  return (
    <div className={"panel card-hover clickable"} style={{ padding: 14, display: "flex", flexDirection: "column", gap: 10 }}
         onClick={() => nav(live ? "live" : f.status === "settled" ? "summary" : "prematch", f.id)}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <StatusPill status={f.status} />
        <span className="bc-mono" style={{ fontSize: 11.5, color: "var(--ink-3)" }}>
          {live ? (f.elapsed || f.period || "LIVE") + (f.score ? " · " + f.score[0] + "–" + f.score[1] : "") : f.time}
        </span>
      </div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
        <TeamSide code={f.home} size={26} />
        <span className="bc-label">vs</span>
        <TeamSide code={f.away} size={26} reverse />
      </div>
      <div style={{ display: "flex", gap: 6 }}>
        {[["1", f.odds.home], ["X", f.odds.draw], ["2", f.odds.away]].map(([k, p]) => (
          <span key={k} className="bc-mono" style={{
            flex: 1, textAlign: "center", fontSize: 12.5, padding: "5px 0",
            background: "var(--panel-2)", border: "1px solid var(--line)", borderRadius: 5,
          }}>
            <span style={{ color: "var(--ink-3)", marginRight: 5, fontFamily: "var(--display)", fontWeight: 700 }}>{k}</span>{fmtCents0(p)}
          </span>
        ))}
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", borderTop: "1px solid var(--line)", paddingTop: 9 }}>
        <span className="bc-label" style={{ color: "var(--sky)" }}>● Recording</span>
        <span className="bc-mono" style={{ fontSize: 12, color: "var(--ink-3)" }}>
          {f.liq ? "liq " + fmtMoney(f.liq) : ""}
        </span>
      </div>
    </div>
  );
}

function DashboardScreen({ nav, botMode }) {
  useStore();
  const FX = WC.FIXTURES || [];
  const now = Date.now();
  const settled = FX.filter((f) => f.status === "settled");
  const today = FX.filter((f) => f.kickoffMs > now - 4 * 3600e3 && f.kickoffMs < now + 48 * 3600e3).slice(0, 8);
  const reports = settled.map((f) => f.report).filter(Boolean);
  const eq = reports.reduce((arr, r) => (arr.push(arr[arr.length - 1] + (r.netPnl || 0)), arr), [0]);

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <SystemBanner botMode={botMode} />

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))", gap: 12 }}>
        {[
          ["Bankroll (paper)", fmtMoneyFull(WC.ACCOUNT.bankroll), "wc_controls/global", null],
          ["Tournament P&L", reports.length ? fmtMoneyFull(WC.ACCOUNT.realized, true) : "—", reports.length + " matches traded", reports.length ? pnlClass(WC.ACCOUNT.realized) : null],
          ["Per-match cap", fmtMoneyFull(WC.ACCOUNT.perMatchCap), "daily stop " + fmtMoneyFull(WC.ACCOUNT.dailyStop), null],
          ["Next 48h", today.length, today.map((f) => f.home + "-" + f.away).slice(0, 3).join(" · ") || "—", null],
        ].map(([l, v, sub, tone]) => (
          <div key={l} className="panel" style={{ padding: "14px 16px" }}>
            <Stat label={l} value={v} sub={sub} tone={tone} big />
          </div>
        ))}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.4fr) minmax(0, 1fr)", gap: 16 }} className="dash-cols">
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div className="panel">
            <div className="panel-head">
              <span className="panel-title">Today &amp; next 48h</span>
              <span className="panel-sub">{new Date().toLocaleDateString("en-GB", { weekday: "short", day: "numeric", month: "short", year: "numeric" })}</span>
            </div>
            <div style={{ padding: 14, display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(230px, 1fr))", gap: 12 }}>
              {today.length ? today.map((f) => <TodayMatchCard key={f.id} f={f} nav={nav} />)
                : <ThaiHint>ยังไม่มีนัดใน 24 ชม. ข้างหน้า</ThaiHint>}
            </div>
          </div>

          <div className="panel">
            <div className="panel-head">
              <span className="panel-title">Settled matches</span>
              <button className="btn btn-ghost btn-sm" onClick={() => nav("fixtures")}>All fixtures →</button>
            </div>
            {settled.length ? (
              <table className="tbl">
                <thead><tr><th>Match</th><th>Score</th><th style={{ textAlign: "right" }}>Rounds</th><th style={{ textAlign: "right" }}>P&L</th><th></th></tr></thead>
                <tbody>
                  {settled.map((f) => (
                    <tr key={f.id} className="clickable" onClick={() => nav("summary", f.id)} style={{ opacity: f.report ? 1 : 0.55 }}>
                      <td>
                        <span style={{ display: "inline-flex", alignItems: "center", gap: 7 }}>
                          <TeamBadge code={f.home} size={22} /><TeamBadge code={f.away} size={22} />
                          <span className="bc-display" style={{ fontSize: 15 }}>{f.home} – {f.away}</span>
                        </span>
                      </td>
                      <td className="bc-mono">{f.score ? f.score[0] + "–" + f.score[1] : "—"}</td>
                      <td className="bc-mono" style={{ textAlign: "right" }}>{f.report ? f.report.rounds : "—"}</td>
                      <td className={"bc-num " + (f.report ? pnlClass(f.report.netPnl) : "")} style={{ textAlign: "right", fontWeight: 600 }}>
                        {f.report ? fmtMoneyFull(f.report.netPnl, true) : "not traded"}
                      </td>
                      <td style={{ textAlign: "right", color: "var(--ink-3)", fontSize: 12 }}>{f.report ? "report →" : ""}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            ) : <Phase1Note>ยังไม่มีนัดที่จบ — นัดแรก Mexico vs South Africa จะ settle คืนนี้</Phase1Note>}
          </div>
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div className="panel">
            <div className="panel-head">
              <span className="panel-title">Equity curve</span>
              {reports.length ? <span className={"bc-num " + pnlClass(eq[eq.length - 1])} style={{ fontWeight: 600 }}>{fmtMoneyFull(eq[eq.length - 1], true)}</span> : null}
            </div>
            {reports.length ? (
              <div style={{ padding: "10px 12px 4px" }}>
                <EquitySpark points={eq} />
                <ThaiHint>กำไรสะสมหลังจบแต่ละ match ที่เทรด</ThaiHint>
              </div>
            ) : <Phase1Note>equity curve จะเริ่มวาดเมื่อ wc-trader ปิด match แรก</Phase1Note>}
          </div>

          <div className="panel">
            <div className="panel-head">
              <span className="panel-title">Budget</span>
              {Auth.isOwner ? <span className="bc-chip green">editable</span> : <span className="bc-chip ghost">read-only</span>}
            </div>
            <div style={{ padding: 16, display: "flex", flexDirection: "column", gap: 12 }}>
              {[["Bankroll (paper)", "bankrollUsd", WC.ACCOUNT.bankroll],
                ["Per-match cap", "defaultPerMatchCapUsd", WC.ACCOUNT.perMatchCap],
                ["Daily loss stop", "dailyLossStopUsd", WC.ACCOUNT.dailyStop]].map(([l, field, v]) => (
                <div key={field} style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                  <span className="bc-label">{l}</span>
                  {Auth.isOwner ? (
                    <input className="num-input" type="number" step={field === "bankrollUsd" ? 100 : 10}
                           key={field + "_" + v} defaultValue={v}
                           onBlur={(e) => { const n = +e.target.value; if (n > 0 && n !== v) saveControls({ [field]: n }); }} />
                  ) : (
                    <span className="bc-num" style={{ fontWeight: 600 }}>{fmtMoneyFull(v)}</span>
                  )}
                </div>
              ))}
              <ThaiHint>{Auth.isOwner
                ? "แก้แล้วกดออกจากช่อง — bot รับค่าใหม่ทันที (onSnapshot) ไม่ต้อง deploy"
                : "login Telegram (allowlist) เพื่อแก้ budget และใช้ปุ่มควบคุม"}</ThaiHint>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { DashboardScreen });
