// ============================================================
// WC26 — Live match (REAL order book + score · bot panels await Phase 1)
// ============================================================
const QB_GREEN = "oklch(0.8 0.15 152)";
const QB_RED = "oklch(0.74 0.16 25)";
const QB_GOLD = "oklch(0.85 0.13 90)";

function LiveScoreboard({ f }) {
  const live = f.status === "live";
  const clock = f.status === "settled" ? "FT" : (f.elapsed || f.period || (live ? "LIVE" : f.time));
  return (
    <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", alignItems: "center", padding: "0 18px", gap: 10 }}>
          {f.status === "settled"
            ? <span className="bc-chip ghost" style={{ background: "rgba(255,255,255,.12)", color: "#fff", border: "none" }}>Full-time</span>
            : live
              ? <span className="bc-chip live"><span className="pulse-dot" style={{ background: "#fff" }}></span>Live</span>
              : <span className="bc-chip blue">Pre-match</span>}
          <span className="bc-num" style={{ fontSize: 22, fontWeight: 600 }}>{clock}</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)", fontSize: 11.5, color: "var(--ink-3)" }}>
          <span style={{ fontFamily: "var(--display)", fontWeight: 600, textTransform: "uppercase", letterSpacing: ".08em", color: "var(--ink-2)" }}>{f.date} · {f.time}</span>
          <span>{f.period ? "period " + f.period : (f.liq ? "liq " + fmtMoney(f.liq) : "")}</span>
        </div>
      </div>
    </div>
  );
}

function MarketStrip({ f, books, sel, setSel }) {
  const mid = (b) => (b && b.bid != null && b.ask != null) ? (b.bid + b.ask) / 2 : null;
  const cells = [
    { code: f.home.toLowerCase(), k: f.home + " win", p: mid(books[f.home.toLowerCase()]) ?? f.odds.home },
    { code: "draw", k: "Draw", p: mid(books["draw"]) ?? f.odds.draw },
    { code: f.away.toLowerCase(), k: f.away + " win", p: mid(books[f.away.toLowerCase()]) ?? f.odds.away },
  ];
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8 }}>
      {cells.map((c) => {
        const active = sel === c.code;
        return (
          <div key={c.k} className="panel clickable" onClick={() => setSel(c.code)} style={{
            padding: "9px 12px", textAlign: "center",
            borderColor: active ? "var(--pitch)" : "var(--line)",
            boxShadow: active ? "0 0 0 1px var(--pitch), var(--shadow)" : "var(--shadow)",
          }}>
            <div className="bc-label" style={{ fontSize: 10.5, marginBottom: 2, color: active ? "var(--pitch-deep)" : undefined }}>
              {c.k}{active ? " · watching" : ""}
            </div>
            <div className="bc-num" style={{ fontSize: 19, fontWeight: 600 }}>{fmtCents(c.p)}</div>
          </div>
        );
      })}
    </div>
  );
}

function QuoteBar({ live, code }) {
  const b = live.books[code] || {};
  const bids = b.bids || [], asks = b.asks || [];
  const bid = bids[0], ask = asks[0], bid2 = bids[1], ask2 = asks[1];
  if (!bid || !ask) return null;
  const spread = Math.max(0, ask.p - bid.p);
  const delta = live.delta || 0;
  const cells = [
    { label: code.toUpperCase() + "-YES · NOW", big: fmtCents(live.price), color: QB_GOLD, bigSize: 30,
      sub: <span style={{ color: delta >= 0 ? QB_GREEN : QB_RED }}>{(delta >= 0 ? "+" : "−") + Math.abs(delta * 100).toFixed(1) + "¢ last tick"}</span> },
    { label: "BID · BUY", big: fmtCents(bid.p), color: QB_GREEN,
      sub: <span><span className="pulse-dot" style={{ background: QB_GREEN, width: 5, height: 5, marginRight: 6 }}></span>{bid2 ? fmtCents(bid2.p) + "/" : ""}{fmtCents(bid.p)} · {bid.q.toLocaleString()}</span> },
    { label: "ASK · SELL", big: fmtCents(ask.p), color: QB_RED,
      sub: <span><span className="pulse-dot" style={{ background: QB_RED, width: 5, height: 5, marginRight: 6 }}></span>{fmtCents(ask.p)}{ask2 ? "/" + fmtCents(ask2.p) : ""} · {ask.q.toLocaleString()}</span> },
    { label: "SPREAD", big: (spread * 100).toFixed(1) + "¢", color: "#fff",
      sub: <span>mid {fmtCents((bid.p + ask.p) / 2)} · top10 lvls</span> },
  ];
  return (
    <div className="panel quote-grid" style={{ background: "var(--chrome)", borderColor: "var(--chrome)", color: "#fff", display: "grid", gridTemplateColumns: "1.25fr 1fr 1fr 1fr", gap: 14, padding: "12px 20px" }}>
      {cells.map((c, i) => (
        <div key={i} style={{ minWidth: 0, borderLeft: i ? "1px solid rgba(255,255,255,.12)" : "none", paddingLeft: i ? 16 : 0 }}>
          <div className="bc-label" style={{ color: "rgba(255,255,255,.5)", marginBottom: 3 }}>{c.label}</div>
          <div className="bc-num" style={{ fontSize: c.bigSize || 26, fontWeight: 600, color: c.color, lineHeight: 1 }}>{c.big}</div>
          <div className="bc-mono" style={{ fontSize: 11, color: "rgba(255,255,255,.55)", marginTop: 4, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.sub}</div>
        </div>
      ))}
    </div>
  );
}

function EventFeed({ events }) {
  if (!events.length) return <div style={{ padding: 14, fontSize: 12, color: "var(--ink-3)" }}>ยังไม่มี event — score/period changes จาก Polymarket sports ws + VAR/lineups จาก API-Football จะโผล่ที่นี่</div>;
  const icon = (e) => e.type === "goal" ? "⚽" : e.type === "var" ? "🖥" : e.type === "card" ? "▮" : e.type === "lineup" ? "📋" : "•";
  const color = (e) => e.type === "goal" || e.type === "var" ? "var(--gold)" : e.type === "card" ? "var(--gold)" : "var(--ink-3)";
  return (
    <div style={{ display: "flex", flexDirection: "column" }}>
      {events.map((e, i) => (
        <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.5, color: "var(--ink-3)", width: 32, flex: "none" }}>{e.m != null && e.m >= 0 ? e.m + "'" : ""}</span>
          <span style={{ color: color(e), flex: "none" }}>{icon(e)}</span>
          <span style={{ fontSize: 12.5, fontWeight: e.type === "goal" ? 700 : 400 }}>{e.label}</span>
        </div>
      ))}
    </div>
  );
}

function LiveScreen({ nav, fixtureId }) {
  useStore();
  const FX = WC.FIXTURES || [];
  // explicit fid only when not settled · otherwise prefer the CURRENT live match
  const f = FX.find((x) => x.id === fixtureId && x.status !== "settled")
    || FX.find((x) => x.status === "live")
    || FX.filter((x) => x.status === "upcoming").sort((a, b) => a.kickoffMs - b.kickoffMs)[0]
    || FX.find((x) => x.id === fixtureId);
  const [sel, setSel] = React.useState(null);
  const [tf, setTf] = React.useState("all");
  const selCode = sel || (f ? f.home.toLowerCase() : null);
  const live = useLiveMatch(f ? f.id : null, selCode);
  const bot = useBotPanel(f ? f.id : null);
  const ko = f ? f.kickoffMs : 0;
  // 'Match' = full window from snaps (T−15m → now) so the line is complete even
  // when the page opens mid-game · short TFs unchanged
  const matchMin = f && f.status !== "upcoming"
    ? Math.max(20, Math.min(150, Math.ceil((Date.now() - (ko - 15 * 60e3)) / 60000))) : null;
  const snapTfMin = tf === "10m" ? 10 : tf === "30m" ? 30 : tf === "1h" ? 60 : matchMin;
  const snapSeries = useSnapSeries(f ? f.id : null, selCode, snapTfMin);

  if (!f) return <div className="panel"><Phase1Note>รอ fixtures จาก recorder…</Phase1Note></div>;

  const goalEvents = live.events.filter((e) => e.type === "goal" || e.type === "ht").map((e) => ({ m: e.m, type: e.type }));
  // timeframe → merge snap history (1s data) with the live-accumulated series
  let chartHist = live.hist, chartBid = live.bidHist, chartAsk = live.askHist;
  if (snapTfMin) {
    const cutMin = tf === "all" ? -15 : (Date.now() - snapTfMin * 60e3 - ko) / 60000;
    const snapMin = snapSeries.map((pt) => ({ m: (pt.t - ko) / 60000, p: pt.p }));
    chartHist = [...snapMin, ...live.hist.filter((p) => p.m >= cutMin)].sort((a, b) => a.m - b.m);
    chartBid = live.bidHist.filter((p) => p.m >= cutMin);
    chartAsk = live.askHist.filter((p) => p.m >= cutMin);
  }
  const lastM = chartHist.length ? chartHist[chartHist.length - 1].m : 0;
  const domain = tf === "all" && (f.status === "live" || f.status === "settled")
    ? [-15, Math.max(96, lastM + 2)] : undefined;
  const liveXLab = tf !== "all"
    ? (m) => new Date(ko + m * 60000).toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" })
    : (f.status === "upcoming" ? ((m) => Math.round(m / 60) + "h") : ((m) => (m < 0 ? "T" + Math.round(m) + "m" : Math.round(m) + "'")));
  // bot fills as ▲▼ on the chart (selected outcome only — same price scale)
  const fillMarkers = bot.fills.filter((x) => x.code === selCode)
    .map((x) => ({ m: (x.ts - ko) / 60000, p: x.px, kind: x.side === "buy" ? "buy" : "sell" }));
  const marketName = (WC.TEAMS[f.home] || { name: f.home }).name + " to win (" + f.home + "-YES)";

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <LiveScoreboard f={f} />
      {f.status === "settled" ? (
        <div className="panel" style={{ padding: "14px 18px", display: "flex", gap: 16, alignItems: "center", flexWrap: "wrap", borderLeft: "4px solid var(--pitch)" }}>
          <div style={{ flex: 1, minWidth: 240 }}>
            <div className="bc-display" style={{ fontSize: 20 }}>Match settled{f.score ? " — " + f.score[0] + "–" + f.score[1] : ""}</div>
            <ThaiHint>order book + trades + score ของนัดนี้ถูกอัดครบใน Firestore สำหรับวิเคราะห์</ThaiHint>
          </div>
          <button className="btn btn-primary" onClick={() => nav("summary", f.id)}>View match report →</button>
        </div>
      ) : null}
      <MarketStrip f={f} books={live.books} sel={selCode} setSel={setSel} />
      <QuoteBar live={live} code={selCode} />

      <div className="live-grid" style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.9fr) minmax(0, 1fr)", gap: 14 }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 14, minWidth: 0 }}>
          <div className="panel">
            <div className="panel-head" style={{ flexWrap: "wrap", gap: 8 }}>
              <span className="panel-title">{marketName}</span>
              <span style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
                <TfTabs value={tf} onChange={setTf}
                        options={[["10m", "10m"], ["30m", "30m"], ["1h", "1h"], ["all", "Match"]]} />
                <span className={"bc-num " + (live.dir >= 0 ? "up" : "down")} style={{ fontSize: 22, fontWeight: 600 }}>
                  {fmtCents(live.price)} {live.dir > 0 ? "▲" : live.dir < 0 ? "▼" : ""}
                </span>
              </span>
            </div>
            <div style={{ padding: "8px 8px 2px" }}>
              <PriceChart series={chartHist} height={250} liveDot
                          markers={fillMarkers}
                          events={goalEvents}
                          extras={[
                            { series: chartBid, color: "var(--pitch)", width: 1, opacity: 0.55 },
                            { series: chartAsk, color: "var(--hot)", width: 1, opacity: 0.55 },
                          ]}
                          accent="var(--sky)" domain={domain}
                          xLabel={liveXLab} />
            </div>
            <div style={{ padding: "4px 16px 12px" }}>
              <ThaiHint>เส้นหลัก = mid ของ {selCode ? selCode.toUpperCase() : ""}-YES · เส้นบางเขียว/แดง = best bid/ask · เส้นทอง = ประตู · ▲ = bot ซื้อ / ▼ = bot ขาย (ขาที่เลือกอยู่ — สลับขาดูไม้อื่น)</ThaiHint>
            </div>
          </div>
          <div className="panel">
            <div className="panel-head"><span className="panel-title">Match events</span><span className="panel-sub">sports ws + API-Football</span></div>
            <div style={{ maxHeight: 220, overflowY: "auto" }}><EventFeed events={live.events} /></div>
          </div>
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 14, minWidth: 0 }}>
          <div className="panel">
            <div className="panel-head">
              <span className="panel-title">Bot sessions</span>
              {bot.sessions.length
                ? <span className="bc-chip green">Paper · live</span>
                : <span className="bc-chip gold">standby</span>}
            </div>
            {bot.sessions.length ? bot.sessions.map((s) => (
              <div key={s.id} style={{ padding: "10px 14px", borderBottom: "1px solid var(--line)" }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 6 }}>
                  <span className="bc-display" style={{ fontSize: 15 }}>{s.planId} <span style={{ color: "var(--ink-3)", fontSize: 11 }}>{s.kind}</span></span>
                  <span className="bc-chip ghost" style={{ fontSize: 10 }}>{s.status === "settled" ? "settled" : s.phase}</span>
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                  <Stat label="Realized" value={fmtMoneyFull(s.realized || 0, true)} tone={pnlClass(s.realized || 0)} />
                  <Stat label="Unreal / Locked" value={fmtMoneyFull(s.unrealized || 0, true)} tone={pnlClass(s.unrealized || 0)} />
                  <Stat label="Rounds" value={(s.rounds || 0) + (s.wins != null ? " (" + s.wins + "W)" : "")} />
                  <Stat label="Deployed" value={fmtMoneyFull(s.deployedUsd || 0)} sub={"max " + fmtMoneyFull(s.maxDeployUsd || 0)} />
                </div>
                {(s.lotsOpen || []).length ? (
                  <div style={{ marginTop: 8, display: "flex", flexDirection: "column", gap: 4 }}>
                    {s.lotsOpen.map((l, i) => l.kind === "lockset" ? (
                      <div key={i} className="bc-mono" style={{ fontSize: 11.5, padding: "5px 8px", background: "var(--pitch-tint)", borderRadius: 5 }}>
                        🔒 LOCK {l.qty} ชุด @ Σ{((l.cost / l.qty) * 100).toFixed(1)}¢ → ล็อก <b className="up">+{fmtMoneyFull(l.qty - l.cost)}</b> (รับตอน settle)
                      </div>
                    ) : (
                      <div key={i} className="bc-mono" style={{ fontSize: 11.5, padding: "5px 8px", background: "var(--panel-2)", borderRadius: 5 }}>
                        📈 {(l.code || "").toUpperCase()} {l.qty} @ {fmtCents(l.avgPx)} <span style={{ color: "var(--ink-3)" }}>· เข้า {new Date(l.openedMs).toLocaleTimeString("en-GB").slice(0, 5)}</span>
                      </div>
                    ))}
                  </div>
                ) : null}
                {s.blocked && Object.keys(s.blocked).length ? (
                  <div className="bc-mono" style={{ fontSize: 10.5, color: "var(--ink-3)", marginTop: 6 }}>
                    gate: {Object.entries(s.blocked).map(([k, v]) => k + "×" + v).join(" · ")}
                  </div>
                ) : null}
              </div>
            )) : <Phase1Note>sessions เปิดอัตโนมัติที่ T−2.5h ก่อนเตะ — SC1 scalper + LA1 lock-arb</Phase1Note>}
          </div>

          <div className="panel">
            <div className="panel-head"><span className="panel-title">Bot tape</span><span className="panel-sub">ซื้อต่ำ → ขายสูง วนเป็นรอบ</span></div>
            {bot.fills.length ? (
              <div style={{ display: "flex", flexDirection: "column", maxHeight: 260, overflowY: "auto" }}>
                {bot.fills.map((t, i) => (
                  <div key={t.ts + "_" + i} style={{ display: "grid", gridTemplateColumns: "42px 1fr auto", gap: 8, padding: "6px 14px", borderBottom: "1px solid var(--line)", alignItems: "baseline", fontSize: 12 }}>
                    <span className={"bc-display " + (t.side === "buy" ? "up" : "down")} style={{ fontSize: 13 }}>{(t.side || "").toUpperCase()}</span>
                    <span className="bc-mono">{(t.code || "").toUpperCase()} {t.qty} @ {fmtCents(t.px)} <span style={{ color: "var(--ink-3)" }}>· {t.liquidity === "maker" ? "M" : "T"} · {t.tag}{t.planId ? " · " + t.planId : ""}</span></span>
                    <span className="bc-mono" style={{ color: "var(--ink-3)", fontSize: 10.5 }}>{new Date(t.ts).toLocaleTimeString("en-GB")}</span>
                  </div>
                ))}
              </div>
            ) : <div style={{ padding: 14, fontSize: 12, color: "var(--ink-3)" }}>รอ fill แรกจาก bot…</div>}
          </div>

          <div className="panel">
            <div className="panel-head">
              <span className="panel-title">Order book</span>
              <span className="bc-chip green">{(selCode || "").toUpperCase()}-YES</span>
            </div>
            <div style={{ padding: "6px 6px 10px" }}>
              <OrderBook book={live.books[selCode]} last={live.price} lastDir={live.dir} />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LiveScreen });
