// ============================================================
// WC26 — Match summary + TRADE REPLAY (The-Eye-style review)
// กราฟ bid/ask จาก snaps ที่อัดไว้ + จุดซื้อขาย ▲▼ ของ bot + events จาก API
// ============================================================
function RemainingMatches({ nav, excludeId }) {
  const upcoming = (WC.FIXTURES || [])
    .filter((f) => f.status === "upcoming" && f.id !== excludeId)
    .sort((a, b) => a.kickoffMs - b.kickoffMs)
    .slice(0, 6);
  return (
    <div className="panel">
      <div className="panel-head"><span className="panel-title">Remaining matches</span><span className="panel-sub">{upcoming.length} next</span></div>
      {upcoming.map((f) => (
        <div key={f.id} className="clickable" onClick={() => nav("prematch", f.id)}
             style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 16px", borderBottom: "1px solid var(--line)" }}>
          <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 className="bc-mono" style={{ fontSize: 11, color: "var(--ink-3)", marginLeft: "auto" }}>{f.date} {f.time}</span>
          <span className="bc-mono" style={{ fontSize: 11.5 }}>{fmtCents0(f.odds.home)}/{fmtCents0(f.odds.draw)}/{fmtCents0(f.odds.away)}</span>
        </div>
      ))}
      {!upcoming.length ? <div style={{ padding: 14, fontSize: 12, color: "var(--ink-3)" }}>—</div> : null}
    </div>
  );
}

function teamAbbrOf(f, name) {
  const n = String(name || "").toLowerCase();
  if ((WC.TEAMS[f.home] || {}).name && WC.TEAMS[f.home].name.toLowerCase() === n) return f.home;
  if ((WC.TEAMS[f.away] || {}).name && WC.TEAMS[f.away].name.toLowerCase() === n) return f.away;
  return name || "";
}

function SummaryScreen({ nav, fixtureId }) {
  useStore();
  const FX = WC.FIXTURES || [];
  const f = FX.find((x) => x.id === fixtureId)
    || FX.filter((x) => x.status === "settled").sort((a, b) => b.kickoffMs - a.kickoffMs)[0];
  const r = f ? f.report : null;
  const [sel, setSel] = React.useState(null);
  const codes = f ? [f.home.toLowerCase(), "draw", f.away.toLowerCase()] : [];
  const selCode = (sel && codes.includes(sel)) ? sel : (r && r.winner && codes.includes(r.winner) ? r.winner : codes[0]);
  const replay = useReplaySeries(f ? f.id : null, selCode, f ? f.kickoffMs : null);
  const hist = useMatchHistory(f ? f.id : null);

  if (!f) {
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <div className="panel"><Phase1Note>ยังไม่มีนัดที่จบ — match report แรกจะถูกสร้างหลังนัดเปิดสนาม settle</Phase1Note></div>
        <RemainingMatches nav={nav} />
      </div>
    );
  }

  const ko = f.kickoffMs;
  // ▲▼ markers เฉพาะ fills ของขาที่เลือก (ราคาอยู่บนสเกลเดียวกับกราฟ)
  const markers = hist.fills.filter((x) => x.code === selCode)
    .map((x) => ({ m: (x.ts - ko) / 60000, p: x.px, kind: x.side === "buy" ? "buy" : "sell" }));
  // events จาก API (ประตู/VAR/lineups + score changes)
  const chartEvents = [];
  let prevScore = null;
  for (const e of hist.events) {
    if (e.src === "api-football" && e.type) {
      const t = String(e.type).toLowerCase();
      const m = e.minute != null ? e.minute : Math.round((e.ts - ko) / 60000);
      if (t === "goal") chartEvents.push({ m, type: "goal", team: teamAbbrOf(f, e.team) });
      else if (t === "var") chartEvents.push({ m, type: "var" });
    } else if (e.score && e.score !== prevScore) {
      if (prevScore != null) chartEvents.push({ m: Math.round((e.tsMs || e.ts) - ko) / 60000, type: "goal" });
      prevScore = e.score;
    }
  }
  const totalBudget = hist.plans.reduce((s, p) => s + (p.budgetUsd || 0), 0);
  const lastM = replay.mid.length ? replay.mid[replay.mid.length - 1].m : 100;

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <div><button className="btn btn-ghost btn-sm" onClick={() => nav("fixtures")}>← Fixtures</button></div>

      {/* lower-third header */}
      <div className="panel" style={{ overflow: "hidden" }}>
        <div style={{ display: "flex", alignItems: "stretch", flexWrap: "wrap" }}>
          <div style={{ flex: "none", background: "var(--chrome)", color: "#fff", display: "flex", flexDirection: "column", justifyContent: "center", padding: "10px 18px" }}>
            <span className="bc-display" style={{ fontSize: 17 }}>{f.status === "settled" ? "Full-time" : "In progress"}</span>
            <span style={{ fontSize: 11, color: "rgba(255,255,255,.6)" }}>{f.date}</span>
          </div>
          <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", gap: 18, padding: "12px 16px", minWidth: 280 }}>
            <TeamSide code={f.home} size={34} />
            <span className="bc-display" style={{ fontSize: 34, background: "var(--chrome)", color: "#fff", padding: "2px 14px", borderRadius: 6 }}>
              {f.score ? f.score[0] + "–" + f.score[1] : "–"}
            </span>
            <TeamSide code={f.away} size={34} reverse />
          </div>
          <div style={{ flex: "none", display: "flex", flexDirection: "column", justifyContent: "center", padding: "8px 18px", borderLeft: "1px solid var(--line)" }}>
            <span className="bc-label">Match P&L (paper)</span>
            <span className={"bc-num " + (r ? pnlClass(r.netPnl) : "")} style={{ fontSize: 26, fontWeight: 600 }}>
              {r ? fmtMoneyFull(r.netPnl, true) : "—"}
            </span>
            <span style={{ fontSize: 11, color: "var(--ink-3)" }}>
              {r ? (totalBudget ? "on " + fmtMoneyFull(totalBudget) + " budget" : (r.rounds || 0) + " rounds") : "not traded"}
            </span>
          </div>
        </div>
      </div>

      {/* per-plan reports */}
      {hist.plans.length ? (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))", gap: 12 }}>
          {hist.plans.map((p) => (
            <div key={p.id} className="panel" style={{ padding: "12px 16px" }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 8 }}>
                <span className="bc-display" style={{ fontSize: 16 }}>{p.id} <span style={{ color: "var(--ink-3)", fontSize: 11 }}>{p.kind}</span></span>
                <span className={"bc-num " + pnlClass(p.netPnl || 0)} style={{ fontSize: 20, fontWeight: 600 }}>{fmtMoneyFull(p.netPnl || 0, true)}</span>
              </div>
              <div className="bc-mono" style={{ fontSize: 11.5, color: "var(--ink-2)", display: "flex", flexWrap: "wrap", gap: "4px 14px" }}>
                <span>rounds {p.rounds ?? 0}{p.winRate != null ? " · WR " + Math.round(p.winRate * 100) + "%" : ""}</span>
                <span>vol {fmtMoney(p.volumeUsd || 0)}</span>
                {p.roi != null ? <span>ROI {(p.roi * 100).toFixed(1)}%</span> : null}
                {p.makerShare != null ? <span>maker {Math.round(p.makerShare * 100)}%</span> : null}
                {p.blocked && Object.keys(p.blocked).length ? <span>gate {Object.entries(p.blocked).map(([k, v]) => k + "×" + v).join(" ")}</span> : null}
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="panel"><Phase1Note>นัดนี้ไม่มี session เทรด (ก่อน wc-trader deploy) — data ตลาดยังอัดครบ</Phase1Note></div>
      )}

      {/* ─── TRADE REPLAY ─── */}
      <div className="panel">
        <div className="panel-head" style={{ flexWrap: "wrap", gap: 8 }}>
          <span className="panel-title">Trade replay · bid/ask + จุดซื้อขายของ bot</span>
          <span style={{ display: "inline-flex", gap: 6 }}>
            {[{ c: codes[0], k: f.home }, { c: "draw", k: "DRAW" }, { c: codes[2], k: f.away }].map((o) => (
              <button key={o.c} onClick={() => setSel(o.c)}
                style={{ padding: "3px 10px", fontSize: 11, cursor: "pointer", fontFamily: "var(--display)", fontWeight: 700,
                  letterSpacing: ".05em", textTransform: "uppercase",
                  background: selCode === o.c ? "var(--pitch)" : "transparent",
                  color: selCode === o.c ? "#fff" : "var(--ink-2)",
                  border: "1px solid " + (selCode === o.c ? "var(--pitch)" : "var(--line-2)"), borderRadius: 5 }}>
                {o.k}{r && r.winner === o.c ? " 🏆" : ""}
              </button>
            ))}
          </span>
        </div>
        <div style={{ padding: "8px 8px 2px" }}>
          <PriceChart series={replay.mid} height={260}
                      markers={markers}
                      events={chartEvents}
                      extras={[
                        { series: replay.bid, color: "var(--pitch)", width: 1, opacity: 0.5 },
                        { series: replay.ask, color: "var(--hot)", width: 1, opacity: 0.5 },
                      ]}
                      accent="var(--sky)"
                      domain={[-15, Math.max(100, lastM + 2)]}
                      xLabel={(m) => (m < 0 ? "T" + Math.round(m) + "m" : Math.round(m) + "'")} />
        </div>
        <div style={{ padding: "4px 16px 12px" }}>
          <ThaiHint>เส้นหลัก = mid ของ {selCode ? selCode.toUpperCase() : ""}-YES · เส้นเขียว/แดงบาง = best bid/ask ที่อัดไว้จริงทุกวินาที · ▲ = bot ซื้อ · ▼ = bot ขาย · เส้นทอง = ประตู (จาก API-Football) — กดปุ่มบนเพื่อดูขาอื่น (lock-arb ซื้อพร้อมกัน 3 ขา ลองสลับดูครบ)</ThaiHint>
        </div>
      </div>

      <div className="live-grid" style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.4fr) minmax(0, 1fr)", gap: 14 }}>
        {/* tx tape */}
        <div className="panel">
          <div className="panel-head"><span className="panel-title">Bot transactions</span><span className="panel-sub">{hist.fills.length} fills</span></div>
          {hist.fills.length ? (
            <div style={{ maxHeight: 300, overflowY: "auto" }}>
              <table className="tbl">
                <thead><tr><th>เวลา</th><th>นาที</th><th>plan</th><th>side</th><th>market</th><th style={{ textAlign: "right" }}>qty @ px</th><th>tag</th></tr></thead>
                <tbody>
                  {hist.fills.map((x, i) => (
                    <tr key={i}>
                      <td className="bc-mono" style={{ fontSize: 11.5 }}>{new Date(x.ts).toLocaleTimeString("en-GB")}</td>
                      <td className="bc-mono" style={{ fontSize: 11.5 }}>{Math.round((x.ts - ko) / 60000)}'</td>
                      <td className="bc-mono" style={{ fontSize: 11.5 }}>{x.planId}</td>
                      <td><span className={"bc-display " + (x.side === "buy" ? "up" : "down")} style={{ fontSize: 12.5 }}>{x.side.toUpperCase()}</span></td>
                      <td className="bc-mono" style={{ fontSize: 11.5 }}>{(x.code || "").toUpperCase()}</td>
                      <td className="bc-mono" style={{ fontSize: 11.5, textAlign: "right" }}>{x.qty} @ {fmtCents(x.px)}</td>
                      <td className="bc-mono" style={{ fontSize: 10.5, color: "var(--ink-3)" }}>{x.liquidity === "maker" ? "M" : "T"} · {x.tag}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : <div style={{ padding: 14, fontSize: 12, color: "var(--ink-3)" }}>ไม่มี fill ในนัดนี้</div>}
        </div>

        {/* API signals */}
        <div className="panel">
          <div className="panel-head"><span className="panel-title">Signals · API events</span><span className="panel-sub">score ws · API-Football</span></div>
          {hist.events.length ? (
            <div style={{ maxHeight: 300, overflowY: "auto" }}>
              {hist.events.map((e, i) => {
                const mm = e.minute != null ? e.minute + "'" : new Date(e.tsMs || e.ts).toLocaleTimeString("en-GB").slice(0, 5);
                const label = e.src === "api-football"
                  ? (e.type || "") + (e.detail ? " — " + e.detail : "") + (e.player ? " · " + e.player : "") + (e.team ? " (" + teamAbbrOf(f, e.team) + ")" : "")
                  : "score " + (e.score || "") + " · " + (e.period || e.status || "");
                const icon = String(e.type || "").toLowerCase() === "goal" || (e.score && i > 0) ? "⚽" : String(e.type || "").toLowerCase() === "var" ? "🖥" : "•";
                return (
                  <div key={i} style={{ display: "flex", gap: 10, padding: "7px 14px", borderBottom: "1px solid var(--line)", alignItems: "baseline" }}>
                    <span className="bc-mono" style={{ fontSize: 11, color: "var(--ink-3)", width: 40, flex: "none" }}>{mm}</span>
                    <span style={{ flex: "none" }}>{icon}</span>
                    <span style={{ fontSize: 12.5 }}>{label}</span>
                  </div>
                );
              })}
            </div>
          ) : <div style={{ padding: 14, fontSize: 12, color: "var(--ink-3)" }}>ไม่มี event บันทึกไว้ (นัดนี้อยู่ช่วง score-ws ยังบอด — นัดถัดไปครบ)</div>}
        </div>
      </div>

      <div className="live-grid" style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.5fr) minmax(0, 1fr)", gap: 14 }}>
        <div className="panel">
          <div className="panel-head"><span className="panel-title">Recorded data · {f.id}</span></div>
          <div style={{ padding: "6px 0" }}>
            {[
              ["Order books", "wc_book_history/" + f.id + "-*/snaps"],
              ["Trades", "wc_trades/" + f.id + "-*/ticks"],
              ["Score & events", "wc_match_state/" + f.id],
              ["Hourly lines", "wc_line_sweeps/" + f.id + "/sweeps"],
              ["Sharp anchor", "wc_sharp_lines/" + f.id],
            ].map(([k, v]) => (
              <div key={k} style={{ display: "flex", justifyContent: "space-between", gap: 12, padding: "8px 16px", borderBottom: "1px solid var(--line)", fontSize: 12.5 }}>
                <span className="bc-label" style={{ fontSize: 10.5, paddingTop: 2, flex: "none" }}>{k}</span>
                <span className="bc-mono" style={{ textAlign: "right", fontSize: 11.5, color: "var(--ink-2)" }}>{v}</span>
              </div>
            ))}
          </div>
        </div>
        <RemainingMatches nav={nav} excludeId={f.id} />
      </div>
    </div>
  );
}

Object.assign(window, { SummaryScreen });
