// ============================================
// Live Meet Results — real-time engine
// ============================================
// Simulates live splits arriving for an in-progress meet.
// Single source of truth in window.LIVE_MEET so all portals reference the same data.

const LIVE_EVENTS = [
  {
    id: "evt-100fr-w",
    name: "100m Freestyle — Women 13-14",
    status: "running",
    distance: 100,
    poolLength: 50,
    lanes: [
      { lane: 1, swimmer: "Hannah Lim", club: "Eastside SC", seed: "1:04.20", color: "#7C3AED" },
      { lane: 2, swimmer: "Sophie Chen",  club: "Marina Bay AC", seed: "1:03.80", color: "#0099CC", featured: true },
      { lane: 3, swimmer: "Ava Robinson", club: "Marina Bay AC", seed: "1:02.94", color: "#D4A017", featured: true },
      { lane: 4, swimmer: "Mei Tanaka",   club: "Sentosa Swim",  seed: "1:01.10", color: "#00C9A7" },
      { lane: 5, swimmer: "Olivia Park",  club: "Eastside SC", seed: "1:02.20", color: "#F97316" },
      { lane: 6, swimmer: "Zoe Khan",     club: "Marina Bay AC", seed: "1:04.50", color: "#1A7C6E", featured: true },
    ],
  },
  {
    id: "evt-200im-m",
    name: "200m IM — Men 15-16",
    status: "upcoming",
    distance: 200,
    poolLength: 50,
    lanes: [],
  },
  {
    id: "evt-50fly-w",
    name: "50m Butterfly — Women 11-12",
    status: "complete",
    distance: 50,
    poolLength: 50,
    lanes: [
      { lane: 4, swimmer: "Mia Tanaka", club: "Marina Bay AC", finish: "0:32.41", place: 1, pb: true, color: "#0099CC", featured: true },
      { lane: 5, swimmer: "Ruby Adams", club: "Eastside SC", finish: "0:32.88", place: 2, color: "#F97316" },
      { lane: 3, swimmer: "Lin Chen", club: "Sentosa Swim", finish: "0:33.04", place: 3, color: "#00C9A7" },
      { lane: 6, swimmer: "Emily Park", club: "Marina Bay AC", finish: "0:33.62", place: 4, color: "#D4A017" },
    ],
  },
];

// Engine: keeps a single piece of state in window.__liveMeet
function useLiveMeet() {
  const [tick, setTick] = useState(0);
  useEffect(() => {
    if (!window.__liveMeet) {
      window.__liveMeet = {
        eventId: "evt-100fr-w",
        currentLength: 0,   // 0 = pre-start, 1 = first 50m done, 2 = finished
        splits: {},          // swimmerLane -> [splits]
        running: true,
        startedAt: Date.now(),
        listeners: new Set(),
        broadcast() { this.listeners.forEach(fn => fn()); },
      };
      // start the tick
      const id = setInterval(() => {
        const lm = window.__liveMeet;
        if (!lm.running) return;
        const elapsed = (Date.now() - lm.startedAt) / 1000;
        const ev = LIVE_EVENTS.find(e => e.id === lm.eventId);
        if (!ev) return;
        // Each swimmer hits 50m around their seed-50 + some variation
        ev.lanes.forEach(l => {
          const k = `${ev.id}-${l.lane}`;
          if (!lm.splits[k]) lm.splits[k] = [];
          const splits = lm.splits[k];
          const seed = parseFloat(l.seed.split(":")[1]) + (parseInt(l.seed.split(":")[0]) * 60);
          const half = seed / 2 + (Math.random() - 0.5) * 0.8;
          if (splits.length === 0 && elapsed >= half) splits.push(Number(half.toFixed(2)));
          if (splits.length === 1 && elapsed >= (splits[0] + half + 0.3)) splits.push(Number((splits[0] + half + 0.3).toFixed(2)));
        });
        if (Date.now() - lm.startedAt > 80 * 1000) {
          // event done — mark complete
          ev.status = "complete";
          lm.running = false;
        }
        lm.broadcast();
      }, 250);
      window.__liveMeet.intervalId = id;
    }
    const fn = () => setTick(t => t + 1);
    window.__liveMeet.listeners.add(fn);
    return () => window.__liveMeet?.listeners.delete(fn);
  }, []);
  return window.__liveMeet;
}

// Helpers
function fmtTime(s) {
  if (s == null || isNaN(s)) return "—";
  const m = Math.floor(s / 60);
  const sec = (s % 60).toFixed(2);
  return m ? `${m}:${sec.padStart(5, "0")}` : `0:${sec.padStart(5, "0")}`;
}

function eventState(ev, splits) {
  if (ev.status === "upcoming") return { state: "upcoming" };
  if (ev.status === "complete") return { state: "complete" };
  const arr = ev.lanes.map(l => {
    const s = splits[`${ev.id}-${l.lane}`] || [];
    return { ...l, splits: s, total: s.length === 2 ? s[1] : s.length === 1 ? null : null };
  });
  return { state: "running", arr };
}

// Compact widget: shows in headers/dashboards
function LiveMeetTicker({ onClick }) {
  const lm = useLiveMeet();
  if (!lm) return null;
  const ev = LIVE_EVENTS.find(e => e.id === lm.eventId);
  const arr = ev.lanes.map(l => ({ ...l, splits: lm.splits[`${ev.id}-${l.lane}`] || [] }))
    .sort((a, b) => (b.splits[b.splits.length - 1] || 999) - (a.splits[a.splits.length - 1] || 999));
  return (
    <button onClick={onClick} className="row" style={{
      gap: 10, padding: "8px 14px", borderRadius: 999,
      background: "linear-gradient(90deg, var(--red), #b91c1c)", color: "white", boxShadow: "var(--sh-4)",
      animation: "pulse-ring 2s infinite", border: "0",
    }}>
      <span style={{ width: 8, height: 8, borderRadius: "50%", background: "white", animation: "pulse-ring 1.2s infinite" }}/>
      <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: 1.5, textTransform: "uppercase" }}>LIVE</span>
      <span style={{ fontSize: 13, fontWeight: 600, whiteSpace: "nowrap" }}>{ev.name.split(" — ")[0]}</span>
      <Icon name="chev-right" size={14}/>
    </button>
  );
}

// Live leaderboard — used inside detail pages
function LiveLeaderboard({ eventId, highlight, compact }) {
  const lm = useLiveMeet();
  const ev = LIVE_EVENTS.find(e => e.id === eventId) || LIVE_EVENTS[0];
  const splits = lm?.splits || {};
  const ranked = ev.lanes.map(l => {
    const s = splits[`${ev.id}-${l.lane}`] || [];
    return { ...l, splits: s, finishS: s.length === 2 ? s[1] : null, fiftyS: s[0] || null };
  });

  // Sort by who's furthest along, then time
  const sorted = [...ranked].sort((a, b) => {
    if (a.finishS && b.finishS) return a.finishS - b.finishS;
    if (a.finishS) return -1;
    if (b.finishS) return 1;
    if (a.fiftyS && b.fiftyS) return a.fiftyS - b.fiftyS;
    if (a.fiftyS) return -1;
    if (b.fiftyS) return 1;
    return parseFloat(a.seed.split(":")[1]) - parseFloat(b.seed.split(":")[1]);
  });

  const fastest50 = Math.min(...ranked.map(r => r.fiftyS).filter(Boolean), Infinity);
  const fastestFinish = Math.min(...ranked.map(r => r.finishS).filter(Boolean), Infinity);

  return (
    <div className="col" style={{ gap: 6 }}>
      {sorted.map((l, i) => {
        const place = i + 1;
        const isHighlight = highlight === l.swimmer || l.featured;
        const finished = !!l.finishS;
        const gap = l.finishS && place > 1 ? l.finishS - sorted[0].finishS : null;
        return (
          <div key={l.lane} style={{
            display: "grid",
            gridTemplateColumns: compact ? "32px 1fr 64px 64px" : "44px 1fr 90px 100px 70px",
            gap: 12, alignItems: "center",
            padding: "12px 14px",
            background: isHighlight ? "var(--aqua-50)" : finished && place === 1 ? "var(--amber-50)" : "var(--gray-50)",
            borderRadius: 10,
            borderLeft: `4px solid ${place === 1 ? "var(--gold)" : place === 2 ? "var(--gray-400)" : place === 3 ? "#cd7f32" : "transparent"}`,
          }}>
            <div style={{
              width: 28, height: 28, borderRadius: "50%",
              background: place === 1 ? "var(--gold)" : place === 2 ? "var(--gray-400)" : place === 3 ? "#cd7f32" : "var(--gray-200)",
              color: place <= 3 ? "white" : "var(--gray-700)",
              fontWeight: 700, fontSize: 12, display: "flex", alignItems: "center", justifyContent: "center",
            }}>{place}</div>
            <div style={{ minWidth: 0 }}>
              <div className="row" style={{ gap: 8 }}>
                <Avatar name={l.swimmer} color={l.color} size="sm"/>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontWeight: 700, fontSize: 13, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{l.swimmer}</div>
                  {!compact && <div className="t-caption">Lane {l.lane} · {l.club}</div>}
                </div>
                {isHighlight && <Pill tone="aqua">You</Pill>}
              </div>
            </div>
            {!compact && (
              <div style={{ textAlign: "right" }}>
                <div className="t-caption" style={{ fontSize: 10 }}>50m</div>
                <div className="t-mono-sm" style={{ fontWeight: 700, color: l.fiftyS === fastest50 ? "var(--mint)" : "var(--gray-700)" }}>
                  {l.fiftyS ? fmtTime(l.fiftyS) : <span style={{ color: "var(--gray-400)" }}>—</span>}
                </div>
              </div>
            )}
            <div style={{ textAlign: "right" }}>
              <div className="t-caption" style={{ fontSize: 10 }}>{compact ? "Time" : "Finish"}</div>
              <div className="t-mono-sm" style={{ fontWeight: 700, fontSize: compact ? 13 : 16, color: l.finishS === fastestFinish ? "var(--gold)" : finished ? "var(--gray-900)" : l.fiftyS ? "var(--aqua)" : "var(--gray-400)" }}>
                {l.finishS ? fmtTime(l.finishS) : l.fiftyS ? <span style={{ fontSize: 11, color: "var(--aqua)", fontWeight: 600 }}>● Swimming</span> : <span style={{ color: "var(--gray-400)" }}>Pre-race</span>}
              </div>
            </div>
            {!compact && (
              <div style={{ textAlign: "right" }}>
                {gap != null && <Pill tone={gap < 0.5 ? "mint" : "default"}>+{gap.toFixed(2)}</Pill>}
                {finished && place === 1 && <Pill tone="amber" icon="trophy">1st</Pill>}
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

// Full Live Meet detail page
function LiveMeetPage({ setSubroute, highlight }) {
  const lm = useLiveMeet();
  const [evId, setEvId] = useState("evt-100fr-w");
  const ev = LIVE_EVENTS.find(e => e.id === evId);

  return (
    <div className="col" style={{ gap: 16 }}>
      <div className="row" style={{ gap: 8 }}>
        <button className="btn-icon" onClick={() => setSubroute("home")}><Icon name="chev-left" size={18}/></button>
        <div className="t-caption">Meets</div><div className="t-caption">/</div><div className="t-caption" style={{ color: "var(--gray-900)", fontWeight: 600 }}>Regional Champs · Live</div>
      </div>

      <Card style={{ background: "linear-gradient(135deg, var(--navy-900), var(--c-competitive))", color: "white", position: "relative", overflow: "hidden" }}>
        <div style={{ position: "absolute", top: 14, right: 14 }}>
          <div className="row" style={{ gap: 6, background: "rgba(220, 38, 38, 0.95)", padding: "6px 12px", borderRadius: 999 }}>
            <span style={{ width: 8, height: 8, borderRadius: "50%", background: "white", animation: "pulse-ring 1.2s infinite" }}/>
            <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: 1.5 }}>LIVE</span>
          </div>
        </div>
        <Pill tone="navy" style={{ background: "rgba(255,255,255,0.2)", color: "white" }}>Day 1 of 3</Pill>
        <div className="t-h1" style={{ color: "white", marginTop: 10 }}>Regional Championships</div>
        <div style={{ color: "rgba(255,255,255,0.7)" }}>National Stadium · Jul 22, 2026 · 2:14 PM</div>
        <div className="row" style={{ gap: 24, marginTop: 20, flexWrap: "wrap" }}>
          <div><div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", letterSpacing: 1, textTransform: "uppercase", fontWeight: 700 }}>Events done</div><div className="t-mono-stat" style={{ color: "white" }}>14 / 26</div></div>
          <div><div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", letterSpacing: 1, textTransform: "uppercase", fontWeight: 700 }}>Swimmers</div><div className="t-mono-stat" style={{ color: "white" }}>284</div></div>
          <div><div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", letterSpacing: 1, textTransform: "uppercase", fontWeight: 700 }}>Club PBs</div><div className="t-mono-stat" style={{ color: "var(--mint)" }}>+12</div></div>
          <div><div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", letterSpacing: 1, textTransform: "uppercase", fontWeight: 700 }}>Next heat in</div><div className="t-mono-stat" style={{ color: "var(--gold)" }}>2:48</div></div>
        </div>
      </Card>

      {/* Event tabs */}
      <div className="row" style={{ gap: 8, overflowX: "auto", paddingBottom: 4 }}>
        {LIVE_EVENTS.map(e => {
          const active = evId === e.id;
          return (
            <button key={e.id} onClick={() => setEvId(e.id)} style={{
              padding: "10px 16px", borderRadius: 12, whiteSpace: "nowrap",
              background: active ? "white" : "var(--gray-50)",
              boxShadow: active ? "var(--sh-4)" : "none",
              borderLeft: active ? `3px solid ${e.status === "running" ? "var(--red)" : e.status === "complete" ? "var(--mint)" : "var(--gray-400)"}` : "3px solid transparent",
              textAlign: "left",
            }}>
              <div className="row" style={{ gap: 6 }}>
                {e.status === "running" && <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--red)", animation: "pulse-ring 1.2s infinite" }}/>}
                {e.status === "complete" && <Icon name="check" size={11} color="var(--mint)"/>}
                {e.status === "upcoming" && <Icon name="clock" size={11} color="var(--gray-500)"/>}
                <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: 1, textTransform: "uppercase", color: e.status === "running" ? "var(--red)" : e.status === "complete" ? "var(--mint)" : "var(--gray-500)" }}>
                  {e.status === "running" ? "Racing" : e.status === "complete" ? "Final" : "Up next"}
                </span>
              </div>
              <div style={{ fontWeight: 700, fontSize: 13, marginTop: 2 }}>{ev.name === e.name ? e.name : e.name}</div>
            </button>
          );
        })}
      </div>

      <Card>
        <div className="between" style={{ marginBottom: 14 }}>
          <div>
            <div className="t-h2">{ev.name}</div>
            <div className="muted" style={{ fontSize: 12 }}>{ev.distance}m · {ev.poolLength}m pool</div>
          </div>
          {ev.status === "running" && (
            <Pill tone="red">● At {Math.round((Date.now() - (lm?.startedAt || 0)) / 1000)}s</Pill>
          )}
          {ev.status === "complete" && <Pill tone="mint">Final results</Pill>}
        </div>

        {ev.lanes.length > 0 ? (
          <LiveLeaderboard eventId={ev.id} highlight={highlight}/>
        ) : (
          <EmptyState icon="clock" title="Event starts soon" sub="Heat assignments will appear here when warm-up begins."/>
        )}
      </Card>

      {ev.status === "running" && (
        <Card>
          <div className="t-h2" style={{ marginBottom: 14 }}>Race progression</div>
          <RaceTrack ev={ev} splits={lm?.splits || {}} highlight={highlight}/>
        </Card>
      )}
    </div>
  );
}

// Visual lane track for an in-progress event
function RaceTrack({ ev, splits, highlight }) {
  const lanes = ev.lanes;
  // estimate progress per swimmer
  const positions = lanes.map(l => {
    const s = splits[`${ev.id}-${l.lane}`] || [];
    if (s.length === 2) return 1;
    if (s.length === 1) return 0.5 + (Math.random() * 0.4); // somewhere mid-second-50
    return Math.min(0.48, ((Date.now() - (window.__liveMeet?.startedAt || 0)) / 1000) / 32);
  });
  return (
    <div className="col" style={{ gap: 6 }}>
      {lanes.map((l, i) => {
        const pct = positions[i] * 100;
        const isHi = highlight === l.swimmer || l.featured;
        return (
          <div key={l.lane} style={{ position: "relative", height: 36, background: "linear-gradient(180deg, var(--sky), var(--aqua-100))", borderRadius: 8, overflow: "hidden", border: isHi ? "1.5px solid var(--aqua)" : "1px solid var(--gray-200)" }}>
            <div style={{ position: "absolute", inset: 0, background: "repeating-linear-gradient(90deg, transparent 0, transparent 38px, rgba(255,255,255,0.5) 38px, rgba(255,255,255,0.5) 40px)" }}/>
            <div style={{ position: "absolute", left: 8, top: 8, fontSize: 10, color: "var(--gray-600)", fontWeight: 700 }}>L{l.lane}</div>
            <div style={{ position: "absolute", left: `calc(${pct}% - 14px)`, top: 4, transition: "left 300ms ease-out" }}>
              <div style={{ width: 28, height: 28, borderRadius: "50%", background: l.color, border: "2px solid white", boxShadow: "var(--sh-2)", display: "flex", alignItems: "center", justifyContent: "center", color: "white", fontWeight: 700, fontSize: 10 }}>
                {l.swimmer.split(" ").map(n => n[0]).slice(0, 2).join("")}
              </div>
            </div>
            <div style={{ position: "absolute", right: 8, top: 10, fontSize: 11, fontFamily: "var(--f-mono)", fontWeight: 700, color: "var(--gray-700)" }}>{l.swimmer}</div>
          </div>
        );
      })}
      <div className="row" style={{ marginTop: 6, justifyContent: "space-between", fontSize: 10, color: "var(--gray-500)", padding: "0 4px" }}>
        <span>Start</span><span>50m turn</span><span>Finish</span>
      </div>
    </div>
  );
}

// Inline "Live now" card for portal dashboards
function LiveNowCard({ swimmerName, onView }) {
  const lm = useLiveMeet();
  const ev = LIVE_EVENTS.find(e => e.id === lm?.eventId);
  if (!ev) return null;
  const lane = ev.lanes.find(l => l.swimmer === swimmerName);
  const splits = lm?.splits?.[`${ev.id}-${lane?.lane}`] || [];

  return (
    <Card style={{ background: "linear-gradient(135deg, #7b1212, var(--navy-900))", color: "white", position: "relative", overflow: "hidden" }}>
      <div style={{ position: "absolute", top: 14, right: 14 }}>
        <div className="row" style={{ gap: 6, background: "rgba(255,255,255,0.18)", padding: "6px 12px", borderRadius: 999 }}>
          <span style={{ width: 8, height: 8, borderRadius: "50%", background: "white", animation: "pulse-ring 1.2s infinite" }}/>
          <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: 1.5 }}>LIVE</span>
        </div>
      </div>
      <Pill tone="navy" style={{ background: "rgba(255,255,255,0.18)", color: "white" }}>Regional Champs</Pill>
      <div className="t-h2" style={{ color: "white", marginTop: 10 }}>{swimmerName || "Sophie Chen"} is racing now</div>
      <div style={{ color: "rgba(255,255,255,0.7)", fontSize: 13 }}>{ev.name} · Lane {lane?.lane || "—"}</div>

      <div className="row" style={{ gap: 28, marginTop: 18, flexWrap: "wrap" }}>
        <div>
          <div style={{ fontSize: 10, color: "rgba(255,255,255,0.5)", letterSpacing: 1, textTransform: "uppercase", fontWeight: 700 }}>50m split</div>
          <div className="t-mono-timer" style={{ fontSize: 28, color: splits[0] ? "var(--mint)" : "rgba(255,255,255,0.4)" }}>{splits[0] ? fmtTime(splits[0]) : "—:—"}</div>
        </div>
        <div>
          <div style={{ fontSize: 10, color: "rgba(255,255,255,0.5)", letterSpacing: 1, textTransform: "uppercase", fontWeight: 700 }}>Finish</div>
          <div className="t-mono-timer" style={{ fontSize: 28, color: splits[1] ? "var(--gold)" : "rgba(255,255,255,0.4)" }}>{splits[1] ? fmtTime(splits[1]) : "—:—"}</div>
        </div>
        <div>
          <div style={{ fontSize: 10, color: "rgba(255,255,255,0.5)", letterSpacing: 1, textTransform: "uppercase", fontWeight: 700 }}>Seed</div>
          <div className="t-mono-timer" style={{ fontSize: 28, color: "white" }}>{lane?.seed || "—"}</div>
        </div>
      </div>

      <Button variant="mint" style={{ marginTop: 18 }} onClick={onView} iconRight="chev-right">Watch live</Button>
    </Card>
  );
}

Object.assign(window, { LiveMeetPage, LiveLeaderboard, LiveMeetTicker, LiveNowCard, useLiveMeet, LIVE_EVENTS, fmtTime });
