import React from 'react'; import { api } from './api.js'; export default function Leaderboard({ username, lastResult, onPlayAgain, onChangeUser }) { const [data, setData] = React.useState(null); const [loading, setLoading] = React.useState(true); const [err, setErr] = React.useState(''); React.useEffect(() => { let alive = true; (async () => { try { const r = await fetch(api(`/api/leaderboard?limit=25&username=${encodeURIComponent(username)}`)) .then((r) => r.json()); if (!alive) return; if (!r.ok) throw new Error(r.error || 'failed'); setData(r); } catch (e) { if (alive) setErr(e.message || 'Could not load leaderboard.'); } finally { if (alive) setLoading(false); } })(); return () => { alive = false; }; }, [username, lastResult]); const myRow = data?.me; const inTop = !!myRow && data?.top?.some((t) => t.username.toLowerCase() === username.toLowerCase()); return (
▸ GLOBAL LEADERBOARD

{lastResult ? ( <>NICE ROUND, {username}! ) : ( <>HALL OF EGGS )}

{lastResult && (
THIS ROUND {lastResult.score}
YOUR BEST {lastResult.best ?? '—'}
RANK {lastResult.rank ? `#${lastResult.rank}` : '—'} {lastResult.total ? of {lastResult.total} : null}
)} {loading &&
loading scores…
} {err &&
✕ {err}
} {data && ( <>
# PLAYER GAMES BEST
    {data.top.length === 0 && (
  1. No scores yet — yours will be the first!
  2. )} {data.top.map((row, i) => { const isMe = row.username.toLowerCase() === username.toLowerCase(); return (
  3. {i + 1} {row.username}{isMe ? YOU : null} {row.games} {row.best}
  4. ); })}
{myRow && !inTop && ( <>
· · ·
  1. {myRow.rank} {myRow.username}YOU {myRow.games} {myRow.best}
)} )}
); }