import { useEffect, useState } from 'react'; import { useAuth } from '../context/AuthContext'; import { supabase } from '../lib/supabase'; import { getLeaderboard } from '../lib/api'; import type { LeaderboardRow } from '../lib/types'; import { Avatar, Spinner } from '../components/ui'; /** * Leaderboard display name: first name + the initial of the last name * ("Max Muster" → "Max M.") — surnames stay private on a public screen. */ function maskedName(fullName: string): string { const parts = fullName.trim().split(/\s+/).filter(Boolean); if (parts.length < 2) return parts[0] ?? fullName; return `${parts[0]} ${parts[parts.length - 1].charAt(0).toUpperCase()}.`; } export function Leaderboard() { const { contact } = useAuth(); const [rows, setRows] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { let active = true; (async () => { try { const data = await getLeaderboard(); if (active) setRows(data); } catch { /* non-fatal */ } finally { if (active) setLoading(false); } })(); // Live updates: re-fetch on any leaderboard change (points are synced // transactionally by the RPCs, so the table is always consistent). const channel = supabase .channel('leaderboard-live') .on('postgres_changes', { event: '*', schema: 'public', table: 'leaderboard' }, () => { getLeaderboard().then((d) => active && setRows(d)).catch(() => {}); }) .subscribe(); return () => { active = false; supabase.removeChannel(channel); }; }, []); if (loading) { return (
); } const me = contact?.email; const top3 = rows.slice(0, 3); const rest = rows.slice(3); const myRank = rows.findIndex((r) => r.contact_email === me) + 1; return (
Leaderboard
All attendees · by points
● Live
{top3.length > 0 && (
{[1, 0, 2].map((idx) => { const r = top3[idx]; if (!r) return
; const cls = idx === 0 ? 'b1' : idx === 1 ? 'b2' : 'b3'; return (
{r.points}
{maskedName(r.full_name)}
#{idx + 1}
); })}
)}
{rest.map((r, i) => { const rank = i + 4; const isMe = r.contact_email === me; return (
{rank}
{maskedName(r.full_name)} {isMe && (you)}
{r.points}
); })}
{myRank > 0 && (
You’re ranked #{myRank} of {rows.length}
)}
); }