import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; type Score = { fullTime?: { home?: number | null; away?: number | null }; halfTime?: { home?: number | null; away?: number | null }; winner?: string | null; }; type Match = { id: number; utcDate: string; status: string; stage?: string; group?: string; matchday?: number; homeTeam: string; awayTeam: string; score: Score; competition?: string; venue?: string; referees?: string[]; }; type ApiResponse = { count: number; matches: Match[]; fetchedAt: string; }; function useFetchOnce(fn: () => Promise) { const [data, setData] = useState(null); const [error, setError] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { let mounted = true; (async () => { try { const result = await fn(); if (mounted) { setData(result); setError(null); } } catch (e: any) { if (mounted) setError(e?.message || 'Failed to fetch'); } finally { if (mounted) setLoading(false); } })(); return () => { mounted = false; }; }, [fn]); return { data, error, loading } as const; } async function fetchJson(url: string, init?: RequestInit): Promise { const res = await fetch(url, { cache: 'no-store', ...init }); if (!res.ok) { const text = await res.text(); let body: any = null; try { body = text ? JSON.parse(text) : null; } catch { /* noop */ } const err: any = new Error(`HTTP ${res.status}`); err.status = res.status; err.body = body; // Try to derive wait seconds for 429 from body.details.message like: "You reached your request limit. Wait 56 seconds." if (res.status === 429) { const msg: string | undefined = body?.details?.message || body?.message || body?.error; const m = msg ? msg.match(/(\d+)\s*seconds?/) : null; if (m) err.waitSec = Number(m[1]); } throw err; } return res.json(); } function MatchCard({ m }: { m: Match }) { const kickoff = useMemo(() => new Date(m.utcDate), [m.utcDate]); const time = kickoff.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); const date = kickoff.toLocaleDateString(); const ftHome = m.score.fullTime?.home ?? '-'; const ftAway = m.score.fullTime?.away ?? '-'; const statusNice = m.status.replace('_', ' '); return (
{m.homeTeam} {ftHome} : {ftAway} {m.awayTeam}
{statusNice} {date} {time} {m.group && {m.group}} {m.stage && {m.stage}}
); } function useBackoffUntilSuccess(fn: () => Promise, opts?: { baseDelaySec?: number; maxDelaySec?: number; factor?: number }) { const base = Math.max(1, opts?.baseDelaySec ?? 30); const max = Math.max(base, opts?.maxDelaySec ?? 300); const factor = Math.max(1.1, opts?.factor ?? 2); const [data, setData] = useState(null); const [error, setError] = useState(null); const [loading, setLoading] = useState(true); const [retryInSec, setRetryInSec] = useState(null); const delayRef = useRef(base); const tRetryRef = useRef(null); const tTickRef = useRef(null); const inFlightRef = useRef(false); useEffect(() => { let mounted = true; const clearTimers = () => { if (tRetryRef.current) { window.clearTimeout(tRetryRef.current); tRetryRef.current = null; } if (tTickRef.current) { window.clearInterval(tTickRef.current); tTickRef.current = null; } }; const scheduleRetry = (sec: number) => { clearTimers(); const clamped = Math.min(Math.max(1, Math.floor(sec)), max); setRetryInSec(clamped); // countdown ticker tTickRef.current = window.setInterval(() => { setRetryInSec(v => (v && v > 0 ? v - 1 : 0)); }, 1000); tRetryRef.current = window.setTimeout(() => { if (!mounted) return; clearTimers(); run(); }, clamped * 1000); }; const run = async () => { if (inFlightRef.current) return; // avoid overlapping calls try { inFlightRef.current = true; setLoading(true); const result = await fn(); if (!mounted) return; clearTimers(); setData(result); setError(null); } catch (e: any) { if (!mounted) return; // 429: backoff and retry if (e?.status === 429) { const suggested = Number(e?.waitSec) || delayRef.current || base; const next = Math.min(max, Math.max(base, suggested)); delayRef.current = Math.min(max, Math.ceil(next * factor)); setError(`Rate limited. Retrying in ${next}s...`); scheduleRetry(next); return; } setError(e?.message || 'Failed to fetch'); } finally { inFlightRef.current = false; if (mounted) setLoading(false); } }; run(); return () => { mounted = false; clearTimers(); }; }, [fn, base, max, factor]); return { data, error, loading, retryInSec } as const; } export default function App() { const fetchLive = useCallback(() => fetchJson('http://localhost:8787/api/live', { headers: { 'cache-control': 'no-cache' } }), []); const fetchToday = useCallback(() => fetchJson('http://localhost:8787/api/matches', { headers: { 'cache-control': 'no-cache' } }), []); const live = useBackoffUntilSuccess(fetchLive); const today = useBackoffUntilSuccess(fetchToday); return (

UEFA Champions League — Live Scores

Live right now

{live.loading &&

Loading…

} {live.error &&

{live.error}{typeof live.retryInSec === 'number' ? ` (${live.retryInSec}s)` : ''}

} {!live.loading && !live.error && live.data?.matches?.length === 0 &&

No live matches.

}
{live.data?.matches?.map(m => )}

Today

{today.loading &&

Loading…

} {today.error &&

{today.error}{typeof today.retryInSec === 'number' ? ` (${today.retryInSec}s)` : ''}

}
{today.data?.matches?.map(m => )}
); }