// ============================================================
// WC26 — Sports Lab · MLB + Tennis microstructure monitor (read-only)
// data จาก sports-recorder ({ns}_* collections) · ไว้ดูว่ามี edge ไหม
// ============================================================
function LabBook({ title, bids, asks, bid, ask }) {
  if (!bids || !asks || (!bids.length && !asks.length)) {
    return <div style={{ padding: 10, fontSize: 11.5, color: "var(--ink-3)" }}>{title}: รอ book…</div>;
  }
  const max = Math.max(...asks.slice(0, 5).map((l) => l.q), ...bids.slice(0, 5).map((l) => l.q), 1);
  return (
    <div>
      <div className="bc-label" style={{ fontSize: 10, padding: "4px 10px 2px" }}>{title}</div>
      {[...asks.slice(0, 5)].reverse().map((l, i) => (
        <div className="ob-row ask" key={"a" + i} style={{ padding: "2px 10px" }}>
          <span className="ob-depth" style={{ width: Math.min(100, (l.q / max) * 100) + "%" }}></span>
          <span className="down">{fmtCents(l.p)}</span><span style={{ color: "var(--ink-2)" }}>{l.q.toLocaleString()}</span>
        </div>
      ))}
      <div className="ob-row" style={{ borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)", padding: "4px 10px", margin: "1px 0" }}>
        <span className="bc-num" style={{ fontSize: 14, fontWeight: 600 }}>{fmtCents(bid != null && ask != null ? (bid + ask) / 2 : null)}</span>
        <span className="bc-label" style={{ fontSize: 9 }}>mid</span>
      </div>
      {bids.slice(0, 5).map((l, i) => (
        <div className="ob-row bid" key={"b" + i} style={{ padding: "2px 10px" }}>
          <span className="ob-depth" style={{ width: Math.min(100, (l.q / max) * 100) + "%" }}></span>
          <span className="up">{fmtCents(l.p)}</span><span style={{ color: "var(--ink-2)" }}>{l.q.toLocaleString()}</span>
        </div>
      ))}
    </div>
  );
}

function LabMatchDetail({ ns, m }) {
  const d = useSportMatch(ns, m.id, m.matchKey);
  const st = d.state || {};
  const ko = m.kickoffMs;
  const live = st.live === true;
  const series = (d.series || []).map((pt) => ({ m: (pt.t - ko) / 60000, p: pt.p }));
  return (
    <div style={{ padding: "10px 14px", background: "var(--panel-2)", borderTop: "1px solid var(--line)" }}>
      <div style={{ display: "flex", gap: 10, alignItems: "center", marginBottom: 8, flexWrap: "wrap" }}>
        {live ? <span className="bc-chip live"><span className="pulse-dot" style={{ background: "#fff" }}></span>Live</span>
              : <span className="bc-chip blue">{st.status || "pre"}</span>}
        {st.score ? <span className="bc-num" style={{ fontWeight: 600 }}>{st.score}</span> : null}
        {st.period ? <span className="bc-mono" style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{st.period}{st.elapsed ? " " + st.elapsed : ""}</span> : null}
        <span className="bc-mono" style={{ fontSize: 11, color: "var(--ink-3)", marginLeft: "auto" }}>liq ${Number(m.liq || 0).toLocaleString()}</span>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1.7fr) minmax(0,1fr) minmax(0,1fr)", gap: 10 }} className="lab-grid">
        <div className="panel" style={{ padding: "6px 4px" }}>
          <PriceChart series={series} height={150} accent="var(--sky)" liveDot
                      xLabel={(x) => (x < 0 ? "T" + Math.round(x) + "m" : Math.round(x) + "m")} />
          <div className="bc-label" style={{ fontSize: 9.5, padding: "0 10px 4px", color: "var(--ink-3)" }}>{m.yesName || "YES"}-win mid (จาก snaps + live)</div>
        </div>
        <div className="panel"><LabBook title={m.yesName || "YES"} bids={d.book && d.book.yesBids} asks={d.book && d.book.yesAsks} bid={d.book && d.book.yesBid} ask={d.book && d.book.yesAsk} /></div>
        <div className="panel"><LabBook title={m.noName || "NO"} bids={d.book && d.book.noBids} asks={d.book && d.book.noAsks} bid={d.book && d.book.noBid} ask={d.book && d.book.noAsk} /></div>
      </div>
    </div>
  );
}

function LabRow({ ns, m, open, onToggle }) {
  const d = useSportMatch(ns, open ? m.id : null, m.matchKey);  // book only when expanded for the row strip
  const now = Date.now();
  const mins = m.kickoffMs ? Math.round((m.kickoffMs - now) / 60000) : null;
  const when = mins == null ? "" : mins > 0 ? "in " + (mins >= 60 ? Math.round(mins / 60) + "h" : mins + "m") : "live/started";
  return (
    <div style={{ borderBottom: "1px solid var(--line)" }}>
      <div className="clickable" onClick={onToggle} style={{ display: "flex", alignItems: "center", gap: 10, padding: "11px 16px" }}>
        <span style={{ width: 14, color: "var(--ink-3)", fontSize: 11 }}>{open ? "▼" : "▶"}</span>
        <span className="bc-display" style={{ fontSize: 15, flex: 1, minWidth: 0, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{m.title || m.matchKey}</span>
        <span className="bc-mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>{when}</span>
        <span className="bc-mono" style={{ fontSize: 11.5 }}>${(Number(m.liq || 0) / 1000).toFixed(0)}k</span>
      </div>
      {open ? <LabMatchDetail ns={ns} m={m} /> : null}
    </div>
  );
}

function LabScreen() {
  useStore();
  const [ns, setNs] = React.useState("tn");
  const [openId, setOpenId] = React.useState(null);
  const list = useSportList(ns);
  const health = useSportsHealth();
  const sports = [["tn", "🎾 Tennis"], ["mlb", "⚾ MLB"]];

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <div className="panel" style={{ padding: "14px 18px", display: "flex", gap: 18, alignItems: "center", flexWrap: "wrap" }}>
        <span className="bc-display" style={{ fontSize: 19 }}>Sports Lab</span>
        <span style={{ display: "inline-flex", gap: 6 }}>
          {sports.map(([k, label]) => (
            <button key={k} onClick={() => { setNs(k); setOpenId(null); }}
              style={{ padding: "5px 14px", fontSize: 13, cursor: "pointer", fontFamily: "var(--display)", fontWeight: 700,
                background: ns === k ? "var(--pitch)" : "transparent", color: ns === k ? "#fff" : "var(--ink-2)",
                border: "1px solid " + (ns === k ? "var(--pitch)" : "var(--line-2)"), borderRadius: 6 }}>{label}</button>
          ))}
        </span>
        <div style={{ flex: 1 }}></div>
        <Stat label="Tracking now" value={list.length} sub={(health && health.obStats ? health.obStats.markets : "—") + " markets · recorder"} tone="up" />
        <ThaiHint>read-only · ดู microstructure 2-ขา ของกีฬาที่ swing เยอะ — ไว้ประเมินว่า scalp/fade มี edge ไหม (ยังไม่มี bot เทรด)</ThaiHint>
      </div>

      <div className="panel" style={{ overflow: "hidden" }}>
        <div className="panel-head">
          <span className="panel-title">{ns === "tn" ? "Tennis" : "MLB"} · live & upcoming</span>
          <span className="panel-sub">sports-recorder · {ns}_* collections</span>
        </div>
        {list.length ? list.map((m) => (
          <LabRow key={m.id} ns={ns} m={m} open={openId === m.id} onToggle={() => setOpenId(openId === m.id ? null : m.id)} />
        )) : (
          <div style={{ padding: 18 }}>
            <ThaiHint>{ns === "mlb"
              ? "ยังไม่มีเกม MLB ใน window (เกมเตะดึก BKK — จะขึ้นเองคืนนี้)"
              : "รอ recorder ดึงแมตช์… (เทนนิสมีทั้งวัน ปกติมี 5-10 แมตช์)"}</ThaiHint>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { LabScreen });
