// ——— Global XP leaderboard (top players by total experience points) ———
function XpLeaderboard({ limit = 20 }) {
  const [state, setState] = React.useState({ players: [], self: null, loading: true, ok: false, demo: false });
  const myName = getStoredName();

  React.useEffect(() => {
    let alive = true;
    setState(s => ({ ...s, loading: true }));
    fetchXpTop(limit, getStoredEmail()).then(r => {
      if (alive) setState({ players: r.players, self: r.self, loading: false, ok: r.ok, demo: !!r.demo });
    });
    return () => { alive = false; };
  }, [limit]);

  if (state.loading) {
    return <p style={{ textAlign: 'center', color: 'var(--ink-soft)', padding: 24 }}>Loading champions…</p>;
  }

  if (!state.players.length) {
    return (
      <p style={{ textAlign: 'center', color: 'var(--ink-soft)', padding: 24 }}>
        No points yet — play a game to be the first champion!
      </p>
    );
  }

  const medals = ['🥇', '🥈', '🥉'];
  // Is the current player already shown in the top list?
  const selfRank = state.self ? state.self.rank : null;
  const selfInList = selfRank !== null && selfRank <= state.players.length;

  const Row = ({ rank, p, isMe }) => {
    const lvl = xpLevel(p.xp);
    return (
      <li className="xp-row" style={{
        display: 'grid',
        gridTemplateColumns: '46px 1fr 68px 68px 92px',
        alignItems: 'center', gap: 10, padding: '12px 14px', marginBottom: 8,
        background: isMe ? 'var(--c-sun)' : rank <= 3 ? 'var(--bg-warm)' : 'var(--paper)',
        border: 'var(--border)', borderRadius: 16, fontWeight: 700,
      }}>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 20, textAlign: 'center' }}>
          {rank <= 3 ? medals[rank - 1] : rank}
        </div>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontSize: 16, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {p.name}{isMe ? ' (you)' : ''}
          </div>
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 5, marginTop: 4,
            padding: '2px 9px', borderRadius: 999, background: lvl.color,
            color: lvl.text || 'var(--ink)',
            border: '2px solid var(--ink)', fontSize: 11, fontWeight: 800,
            fontFamily: 'var(--font-display)',
          }}>
            <span style={{ fontSize: 12, lineHeight: 1 }}>{lvl.icon}</span>{lvl.name}
          </span>
        </div>
        <div style={{ fontSize: 14, color: 'var(--ink-soft)', textAlign: 'right', fontWeight: 700 }}>
          {p.games}
        </div>
        <div style={{ fontSize: 14, color: 'var(--ink-soft)', textAlign: 'right', fontWeight: 700 }}>
          {(p.plays != null ? p.plays : 0).toLocaleString()}
        </div>
        <div style={{
          fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 19,
          textAlign: 'right', display: 'flex', alignItems: 'center',
          justifyContent: 'flex-end', gap: 4,
        }}>
          <span style={{ fontSize: 15 }}>⭐</span>{p.xp.toLocaleString()}
        </div>
      </li>
    );
  };

  return (
    <div>
      {state.demo && (
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8, justifyContent: 'center',
          padding: '8px 14px', marginBottom: 14, borderRadius: 12,
          background: 'var(--bg-warm)', border: '2px dashed var(--ink)',
          fontSize: 12.5, fontWeight: 700, color: 'var(--ink-soft)', textAlign: 'center',
        }}>
          <span>👀</span> Example data — the live points board switches on once the server is updated.
        </div>
      )}
      {/* Column headers */}
      <div style={{
        display: 'grid', gridTemplateColumns: '46px 1fr 68px 68px 92px', gap: 10,
        padding: '4px 14px', marginBottom: 4, fontSize: 11, fontWeight: 800,
        color: 'var(--ink-soft)', textTransform: 'uppercase', letterSpacing: '.06em',
        whiteSpace: 'nowrap',
      }}>
        <div style={{ textAlign: 'center' }}>Rank</div>
        <div>Player</div>
        <div style={{ textAlign: 'right' }}>Games</div>
        <div style={{ textAlign: 'right' }}>Plays</div>
        <div style={{ textAlign: 'right' }}>Points</div>
      </div>

      <ol style={{ listStyle: 'none', padding: 0, margin: 0 }}>
        {state.players.map((p, i) => {
          const isMe = myName && p.name
            && p.name.trim().toLowerCase() === myName.trim().toLowerCase();
          return <Row key={i} rank={i + 1} p={p} isMe={isMe} />;
        })}
      </ol>

      {/* Pin the current player's own row if they're outside the top list */}
      {state.self && !selfInList && (
        <React.Fragment>
          <div style={{ textAlign: 'center', color: 'var(--ink-soft)', fontWeight: 800, margin: '6px 0', letterSpacing: '.2em' }}>···</div>
          <ol style={{ listStyle: 'none', padding: 0, margin: 0 }}>
            <Row rank={state.self.rank} p={state.self} isMe={true} />
          </ol>
        </React.Fragment>
      )}
    </div>
  );
}

// ——— Per-game leaderboards (browse top players for each game) ———
function GameLeaderboards({ go }) {
  const [selected, setSelected] = React.useState(GAMES[0].id);
  const game = GAMES.find(g => g.id === selected);

  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'minmax(220px, 280px) 1fr', gap: 24 }} className="lb-layout">
      {/* Game list */}
      <div className="lb-game-list" style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {GAMES.map(g => (
          <button key={g.id} onClick={() => setSelected(g.id)} style={{
            display: 'flex', alignItems: 'center', gap: 12,
            padding: '10px 14px',
            border: selected === g.id ? 'var(--border)' : '2px solid transparent',
            borderRadius: 14,
            background: selected === g.id ? 'var(--paper)' : 'transparent',
            boxShadow: selected === g.id ? '3px 3px 0 var(--ink)' : 'none',
            cursor: 'pointer', textAlign: 'left', fontWeight: 700,
            fontFamily: 'var(--font-body)', fontSize: 15,
          }}>
            <span style={{
              width: 26, height: 26, borderRadius: 8, background: g.color,
              border: '2px solid var(--ink)', flexShrink: 0,
            }}></span>
            <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {g.title}
            </span>
          </button>
        ))}
      </div>

      {/* Selected leaderboard */}
      <div style={{
        padding: 24, background: 'var(--paper)',
        border: 'var(--border-thick)', borderRadius: 22,
        boxShadow: 'var(--shadow-lg)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 18 }}>
          <span style={{
            width: 44, height: 44, borderRadius: 12, background: game.color,
            border: 'var(--border)', flexShrink: 0,
          }}></span>
          <div>
            <div style={{ fontSize: 12, textTransform: 'uppercase',
              letterSpacing: '.08em', color: 'var(--ink-soft)', fontWeight: 800 }}>
              {game.cat}
            </div>
            <h2 style={{ fontSize: 26 }}>{game.title}</h2>
          </div>
          <button className="btn" style={{ marginLeft: 'auto', padding: '8px 16px', fontSize: 14 }}
            onClick={() => go('game:' + game.id)}>Play →</button>
        </div>
        <LeaderboardList gameId={game.id} highlightName={getStoredName()}
          lowerIsBetter={game.lowerIsBetter} metric={game.metric} />
      </div>
    </div>
  );
}

// ——— Leaderboards page — toggle between global points and per-game ———
function LeaderboardsPage({ go }) {
  const [view, setView] = React.useState('points'); // 'points' | 'games'

  const tabs = [
    { id: 'points', icon: '⭐', label: 'Top Points' },
    { id: 'games',  icon: '🏆', label: 'By game' },
  ];

  return (
    <div className="section" style={{ maxWidth: 1100 }}>
      <span className="eyebrow">Leaderboards</span>
      <h1 style={{ marginTop: 14 }}>Top players</h1>
      <p style={{ color: 'var(--ink-soft)', maxWidth: 620, marginTop: 12, marginBottom: 22 }}>
        {view === 'points'
          ? 'Every game you play earns experience points. Here are the all-time points champions across the whole Game Lab.'
          : 'Tap any game to see who\'s at the top. Names are saved when players finish a game.'}
      </p>

      {/* View toggle */}
      <div style={{ display: 'flex', gap: 10, marginBottom: 24, flexWrap: 'wrap' }}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => setView(t.id)} style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            padding: '10px 20px', borderRadius: 999,
            border: 'var(--border)', cursor: 'pointer',
            fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 15,
            background: view === t.id ? 'var(--ink)' : 'var(--paper)',
            color: view === t.id ? 'var(--bg)' : 'var(--ink)',
            boxShadow: view === t.id ? 'none' : '3px 3px 0 var(--ink)',
          }}>
            <span style={{ fontSize: 17, lineHeight: 1 }}>{t.icon}</span>{t.label}
          </button>
        ))}
      </div>

      {view === 'points' ? (
        <div style={{
          padding: 24, background: 'var(--paper)',
          border: 'var(--border-thick)', borderRadius: 22,
          boxShadow: 'var(--shadow-lg)', maxWidth: 720,
        }}>
          <XpLeaderboard limit={20} />
        </div>
      ) : (
        <GameLeaderboards go={go} />
      )}
    </div>
  );
}

Object.assign(window, { LeaderboardsPage, XpLeaderboard });
