/* Leaderboard screen — the hero standings view across all three leagues. */

function LeaderboardScreen({ onOpenModel }) {
  const { StandingsTable, Stat, Card, Eyebrow, Badge, Sparkline, RankBadge } = window.TheOracleLeagueDesignSystem_92fa71;
  const { STANDINGS, MODELS } = window;
  const [league, setLeague] = React.useState("accuracy"); // accuracy | consensus | book
  const byId = Object.fromEntries(MODELS.map((m) => [m.id, m]));
  const SuspendedStamp = window.SuspendedStamp;
  const SM = window.SUSPENDED_MODELS || new Set();

  const leader = STANDINGS[0];
  const leaderModel = byId[leader.id];

  const stampCol = SM.size > 0 ? [{
    key: "_stamp", label: "", align: "left",
    render: (r) => SM.has(r.id) ? <SuspendedStamp size="xs" /> : null,
  }] : [];

  const columns = league === "accuracy"
    ? [
        ...stampCol,
        { key: "points", label: "Pts", align: "right", mono: true, color: "var(--accent)" },
        { key: "brier", label: "Brier", align: "right", mono: true },
        { key: "called", label: "Called", align: "right", mono: true },
        { key: "exact", label: "Exact", align: "right", mono: true },
      ]
    : [
        ...stampCol,
        { key: "bal", label: "Bankroll", align: "right", mono: true,
          render: (r) => { const v = league === "consensus" ? r.consensus : r.book;
            return <span style={{ color: v >= 100 ? "var(--positive)" : "var(--negative)" }}>${v.toFixed(2)}</span>; } },
        { key: "pnl", label: "P&L", align: "right", mono: true,
          render: (r) => { const v = (league === "consensus" ? r.consensus : r.book) - 100;
            return <span style={{ color: v >= 0 ? "var(--positive)" : "var(--negative)" }}>{v >= 0 ? "+" : "−"}${Math.abs(v).toFixed(2)}</span>; } },
        { key: "spark", label: "Trend", align: "right",
          render: (r) => {
            const base = league === "consensus" ? r.consensus : r.book;
            const sparkMap = league === "consensus" ? window.SPARKLINES_CON : window.SPARKLINES_BOOK;
            const real = sparkMap && sparkMap[r.id];
            const seed = r.rank * 7;
            const series = (real && real.length > 1) ? real : [100, 100 + (seed%9) - 4, 100 + (seed%13) - 7, (base+100)/2, base];
            return <span style={{ display: "inline-flex", justifyContent: "flex-end", width: "100%" }}><Sparkline data={series} baseline={100} width={88} height={26} /></span>;
          }},
      ];

  const rows = [...STANDINGS]
    .sort((a, b) => league === "accuracy" ? a.rank - b.rank
      : (league === "consensus" ? b.consensus - a.consensus : b.book - a.book))
    .map((r, i) => ({
      ...r, rank: league === "accuracy" ? r.rank : i + 1,
      highlight: r.id === "claude",
      model: { name: byId[r.id].name, sublabel: byId[r.id].vendor, color: byId[r.id].color },
    }));

  const tabs = [
    { id: "accuracy", label: "Accuracy", sub: "fun points + Brier" },
    { id: "consensus", label: "Vs. Consensus", sub: "bankroll league" },
    { id: "book", label: "Vs. Bookmaker", sub: "bankroll league" },
  ];

  return (
    <div style={{ padding: "28px 32px", maxWidth: 980 }}>
      {/* Hero */}
      <div style={{ display: "flex", flexDirection: "column", gap: 14, marginBottom: 24 }}>
        <Eyebrow tone="gold">{window.MATCHDAY.label} · standings</Eyebrow>
        <h1 style={{ fontFamily: "var(--font-display)", fontSize: 44, fontWeight: 400, letterSpacing: "-0.02em", color: "var(--text-primary)", lineHeight: 1.12, margin: 0, maxWidth: 700 }}>
          Which machine sees the game clearest?
        </h1>
        <p style={{ fontFamily: "var(--font-sans)", fontSize: 15, color: "var(--text-secondary)", maxWidth: 620, lineHeight: 1.55, margin: 0 }}>
          Eight frontier models predict every World Cup fixture. They are scored on accuracy and made to bet — once against each other, once against the bookmakers.
        </p>
      </div>

      {/* Leader spotlight + season stats */}
      <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 16, marginBottom: 24 }}>
        <Card glow padding={18} style={{ cursor: "pointer" }} onClick={() => onOpenModel(leader.id)}>
          <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
            <RankBadge rank={1} size={44} />
            <div style={{ minWidth: 0 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
                <span style={{ fontFamily: "var(--font-sans)", fontSize: 19, fontWeight: 700, color: "var(--text-primary)" }}>{leaderModel.name}</span>
                <Badge tone="gold" variant="solid">LEADER</Badge>
                {SM.has(leader.id) && <SuspendedStamp size="sm" />}
              </div>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-muted)" }}>{leaderModel.vendor} · {leader.called} called · {leader.exact} exact scores</span>
            </div>
          </div>
          <div style={{ display: "flex", gap: 28, marginTop: 18 }}>
            <Stat label="Fun points" value={leader.points} size="md" />
            <Stat label="Mean Brier" value={leader.brier.toFixed(3)} size="md" />
            <Stat label="Consensus $" value={`$${leader.consensus.toFixed(0)}`} delta={`+${(leader.consensus-100).toFixed(0)}`} size="md" />
          </div>
        </Card>
        <Card padding={18}>
          <Eyebrow rule>Season so far</Eyebrow>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginTop: 14 }}>
            <Stat label="Matches" value="14" size="sm" />
            <Stat label="Models" value="8" size="sm" />
            <Stat label="Predictions" value="112" size="sm" />
            <Stat label="Exact scores" value="18" size="sm" />
          </div>
        </Card>
      </div>

      {/* League switch */}
      <div style={{ display: "flex", gap: 8, marginBottom: 14, borderBottom: "1px solid var(--border)", paddingBottom: 14 }}>
        {tabs.map((t) => {
          const on = league === t.id;
          return (
            <button key={t.id} onClick={() => setLeague(t.id)}
              style={{
                display: "flex", flexDirection: "column", gap: 2, alignItems: "flex-start",
                padding: "8px 14px", borderRadius: "var(--radius-md)", cursor: "pointer",
                border: `1px solid ${on ? "transparent" : "var(--border)"}`,
                background: on ? "var(--accent-soft)" : "transparent",
                transition: "background var(--dur)",
              }}>
              <span style={{ fontFamily: "var(--font-sans)", fontSize: 14, fontWeight: 600, color: on ? "var(--gold-200)" : "var(--text-secondary)" }}>{t.label}</span>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--text-muted)" }}>{t.sub}</span>
            </button>
          );
        })}
      </div>

      <Card padding={6}>
        <StandingsTable rows={rows} columns={columns} onRowClick={(r) => onOpenModel(r.id)} />
      </Card>
    </div>
  );
}

window.LeaderboardScreen = LeaderboardScreen;
