// ============================================================
// WC26 — Pre-match (countdown จริง · 48h drift จาก hourly sweeps · book จริง)
// ============================================================
function useCountdownTo(targetMs) {
  const [now, setNow] = React.useState(Date.now());
  React.useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, []);
  const t = Math.max(0, Math.floor((targetMs - now) / 1000));
  const h = Math.floor(t / 3600), m = Math.floor((t % 3600) / 60), s = t % 60;
  return `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;
}

const TONE_CHIP = { var: "live", lineup: "blue", goal: "gold", info: "green", card: "gold" };

function PrematchScreen({ nav, fixtureId }) {
  useStore();
  const FX = WC.FIXTURES || [];
  const f = FX.find((x) => x.id === fixtureId && x.status !== "settled")
    || FX.filter((x) => x.status === "upcoming").sort((a, b) => a.kickoffMs - b.kickoffMs)[0];
  const [sel, setSel] = React.useState(null);
  const [tf, setTf] = React.useState("24h");
  const codes = f ? [f.home.toLowerCase(), "draw", f.away.toLowerCase()] : [];
  const selCode = (sel && codes.includes(sel)) ? sel : (f ? f.home.toLowerCase() : null);
  const live = useLiveMatch(f ? f.id : null, selCode);
  const series = usePrematchSeries(f ? f.id : null, selCode);
  const snapTfMin = tf === "1h" ? 60 : tf === "6h" ? 360 : null;
  const snapSeries = useSnapSeries(f ? f.id : null, selCode, snapTfMin);
  const countdown = useCountdownTo(f ? f.kickoffMs : Date.now());

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

  const selBook = live.books[selCode];
  const selLabel = selCode === "draw" ? "Draw" : (WC.TEAMS[selCode === codes[0] ? f.home : f.away] || { name: selCode }).name;
  const oddsOf = (code) => code === codes[0] ? f.odds.home : code === "draw" ? f.odds.draw : f.odds.away;
  const midOf = (code) => {
    const b = live.books[code];
    return (b && b.bid != null && b.ask != null) ? (b.bid + b.ask) / 2 : oddsOf(code);
  };
  const priceNow = live.price ?? oddsOf(selCode);
  // timeframe → display series (snaps = 1s data for short TF, hourly sweeps for long)
  const ko = f.kickoffMs;
  let displaySeries;
  if (snapTfMin) {
    displaySeries = snapSeries.map((pt) => ({ m: (pt.t - ko) / 3600e3, p: pt.p }));
  } else if (tf === "24h") {
    displaySeries = series.filter((pt) => pt.m >= -24);
  } else {
    displaySeries = series;
  }
  const priceOpen = displaySeries.length ? displaySeries[0].p : priceNow;
  const chg = priceNow != null && priceOpen != null ? priceNow - priceOpen : 0;
  const base = priceNow ?? 0.5;
  const yDom = [Math.max(0, Math.round((base - 0.16) * 20) / 20), Math.min(1, Math.round((base + 0.16) * 20) / 20)];
  const market = selLabel + (selCode === "draw" ? "" : " to win") + " (" + selCode.toUpperCase() + "-YES)";
  const catalysts = live.events.filter((e) => e.type === "lineup" || e.type === "var" || e.type === "card" || e.type === "info").slice(0, 8);
  const inWindow = !!((WC.HEALTH || {}).conns || {})[f.id];

  const chartSeries = displaySeries.length >= 2 ? displaySeries : null;
  const xLab = snapTfMin
    ? (h) => new Date(ko + h * 3600e3).toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" })
    : (h) => (h >= -0.5 ? "KO" : "T" + Math.round(h) + "h");

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <div>
        <button className="btn btn-ghost btn-sm" onClick={() => nav("fixtures")}>← Fixtures</button>
      </div>
      <div className="panel" style={{ overflow: "hidden" }}>
        <div style={{ display: "flex", alignItems: "stretch", flexWrap: "wrap" }}>
          <div style={{ flex: "none", background: "var(--sky)", color: "#fff", display: "flex", alignItems: "center", padding: "10px 18px", gap: 12 }}>
            <span className="bc-label" style={{ color: "rgba(255,255,255,.75)" }}>Kick-off in</span>
            <span className="bc-num" style={{ fontSize: 24, fontWeight: 600 }}>{countdown}</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-label" style={{ fontSize: 14 }}>vs</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} (local)</span>
            <span>{f.liq ? "liquidity " + fmtMoney(f.liq) : ""}{inWindow ? " · recording" : ""}</span>
          </div>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8 }}>
        {[
          { code: codes[0], k: f.home + " win" },
          { code: "draw", k: "Draw" },
          { code: codes[2], k: f.away + " win" },
        ].map((c) => {
          const active = selCode === c.code;
          return (
            <div key={c.code} className="panel clickable" onClick={() => setSel(c.code)}
                 style={{ padding: "9px 12px", textAlign: "center", borderColor: active ? "var(--sky)" : "var(--line)", boxShadow: active ? "0 0 0 1px var(--sky), var(--shadow)" : "var(--shadow)" }}>
              <div className="bc-label" style={{ fontSize: 10.5, marginBottom: 2, color: active ? "var(--sky)" : undefined }}>{c.k}{active ? " · watching" : ""}</div>
              <div className="bc-num" style={{ fontSize: 19, fontWeight: 600 }}>{fmtCents(midOf(c.code))}</div>
            </div>
          );
        })}
      </div>

      <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">{market} · drift</span>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
                <TfTabs value={tf} onChange={setTf}
                        options={[["1h", "1h"], ["6h", "6h"], ["24h", "24h"], ["all", "All"]]} />
                <span className={"bc-num " + pnlClass(chg)} style={{ fontSize: 18, fontWeight: 600 }}>
                  {fmtCents(priceNow)} <span style={{ fontSize: 12 }}>({chg >= 0 ? "+" : "−"}{Math.abs(chg * 100).toFixed(1)}¢ / {tf})</span>
                </span>
              </span>
            </div>
            <div style={{ padding: "8px 8px 2px" }}>
              {chartSeries ? (
                <PriceChart series={chartSeries} height={230} liveDot accent="var(--sky)"
                            yDomain={yDom}
                            xLabel={xLab} />
              ) : (
                <div style={{ height: 160, display: "flex", alignItems: "center", justifyContent: "center", color: "var(--ink-3)", fontSize: 12 }}>
                  {snapTfMin ? "ยังไม่มี book snaps ในช่วงเวลานี้ (ตลาดเพิ่งเข้า tracking window)" : "hourly sweeps กำลังสะสม — เส้น drift จะยาวขึ้นเรื่อย ๆ (จุดละ 1 ชม.)"}
                </div>
              )}
            </div>
            <div style={{ padding: "4px 16px 12px" }}>
              <ThaiHint>ราคาเฉลี่ย bid/ask ของตลาด {selLabel} จาก hourly sweep (กดการ์ดด้านบนเพื่อสลับขา) — ช่วงที่ต้องจับตาคือ T−2h ถึง T−1h ตอนประกาศตัวจริง</ThaiHint>
            </div>
          </div>

          <div className="panel">
            <div className="panel-head"><span className="panel-title">Catalysts · ตัวแปรก่อนเตะ</span><span className="panel-sub">lineups · VAR · news</span></div>
            {catalysts.length ? (
              <div>
                {catalysts.map((c, i) => (
                  <div key={i} style={{ display: "flex", gap: 12, padding: "11px 16px", borderBottom: i < catalysts.length - 1 ? "1px solid var(--line)" : "none", alignItems: "flex-start" }}>
                    <span className={"bc-chip " + (TONE_CHIP[c.type] || "blue")} style={{ flex: "none" }}>{c.type.toUpperCase()}</span>
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontWeight: 700, fontSize: 13.5 }}>{c.label}</div>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div style={{ padding: "18px 16px", display: "flex", gap: 10, alignItems: "center" }}>
                <span className="bc-chip ghost">Quiet</span>
                <ThaiHint>ยังไม่มี event — ฟีด lineup/VAR จะตื่นเมื่อใส่ APIFOOTBALL_KEY (lineups ~T−75min) · score events เริ่มตอนบอลเตะ</ThaiHint>
              </div>
            )}
          </div>
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 14, minWidth: 0 }}>
          <div className="panel">
            <div className="panel-head"><span className="panel-title">Order book</span><span className="bc-chip blue">{selCode.toUpperCase()}-YES</span></div>
            <div style={{ padding: "6px 6px 10px" }}>
              <OrderBook book={selBook} last={priceNow} lastDir={live.dir} />
            </div>
          </div>

          <div className="panel">
            <div className="panel-head">
              <span className="panel-title">Bot plan</span>
              <span className="bc-chip gold">Phase 1</span>
            </div>
            <Phase1Note>แผนเข้าเทรด (entry zone / max exposure / stop rule) จะมาจาก wc_plans เมื่อ wc-trader deploy — budget cap ปัจจุบัน {fmtMoneyFull(WC.ACCOUNT.perMatchCap)}/นัด</Phase1Note>
          </div>

          <div className="panel" style={{ background: "var(--panel-2)" }}>
            <div style={{ padding: 14 }}>
              <div className="bc-display" style={{ fontSize: 15, marginBottom: 5 }}>No position yet</div>
              <ThaiHint>ระบบอยู่โหมด recording — เก็บ book ทุก 1 วิ + trades + score ตั้งแต่ T−36h เพื่อ calibrate engine</ThaiHint>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { PrematchScreen, useCountdownTo });
