// app.jsx — routing + API integration // The Go backend serves Bracket.html for both / and /champion/:id. // We detect which page we're on from the URL. const { useState: useAppState, useEffect: useAppEffect } = React; // ── URL detection ───────────────────────────────────────────────── const _path = window.location.pathname; const IS_CHAMP = _path.startsWith('/champion/'); const IS_BATTLE = _path.startsWith('/battle/'); const IS_RULES = _path.startsWith('/rules/'); const IS_INSCRICAO = _path.startsWith('/inscricao/'); const IS_VIEW = _path.startsWith('/view/'); const IS_ADMIN_LOGIN = _path === '/admin/login'; const IS_ADMIN_HOME = _path === '/admin' || _path === '/admin/'; const IS_ADMIN_SETTINGS = _path.startsWith('/admin/settings/'); const IS_ADMIN_REGISTRATIONS = _path.startsWith('/admin/inscricoes/'); const IS_ADMIN_ADMINS = _path === '/admin/admins'; const IS_ADMIN = IS_ADMIN_HOME || IS_ADMIN_SETTINGS || IS_ADMIN_REGISTRATIONS || IS_ADMIN_ADMINS; const TOURNAMENT_ID = IS_CHAMP ? _path.replace('/champion/', '').split('/')[0] : IS_BATTLE ? _path.replace(/^\/battle\//, '').split('/')[0] : IS_ADMIN_SETTINGS ? _path.replace('/admin/settings/', '').split('/')[0] : IS_ADMIN_REGISTRATIONS ? _path.replace('/admin/inscricoes/', '').split('/')[0] : IS_RULES ? _path.replace('/rules/', '').split('/')[0] : IS_INSCRICAO ? _path.replace('/inscricao/', '').split('/')[0] : IS_VIEW ? _path.replace('/view/', '').split('/')[0] : null; let BATTLE_ROUND = 0, BATTLE_MATCH = 0; if (IS_BATTLE) { const parts = _path.replace(/^\/battle\//, '').split('/'); BATTLE_ROUND = parseInt(parts[1]) || 0; BATTLE_MATCH = parseInt(parts[2]) || 0; } // ── Convert backend format → React bracket format ───────────────── function backendToReact(data) { const rounds = (data.rounds || []).map(round => ({ name: round.name, matches: round.matches.map(m => ({ a: m.a ? { ...m.a, seed: m.a.id } : null, b: m.b ? { ...m.b, seed: m.b.id } : null, winner: m.winner ? { ...m.winner, seed: m.winner.id } : null, // both-bye → 'bye', otherwise use backend status as-is status: (m.a?.bye && m.b?.bye) ? 'bye' : m.status, })) })); // Reconstruct fighters list from round-0 matches (excludes Passe Livre) const fighters = []; const seen = new Set(); if (rounds.length) { rounds[0].matches.forEach(m => { [m.a, m.b].forEach(f => { if (f && !f.bye && !seen.has(f.id)) { seen.add(f.id); fighters.push(f); } }); }); } // Sort by original ID so players appear in registration order (seed #01, #02, …) fighters.sort((a, b) => a.id - b.id); return { id: data.id, name: data.name, title: data.title, rules: data.rules || '', bgColor: data.bgColor || '#05080e', winsNeeded: data.winsNeeded || 2, fighters, // [{ id, name, seed, ... }] totalFighters: data.totalFighters || fighters.length, bracket: { rounds, totalRounds: rounds.length }, status: data.status, registering: data.status === 'registering', finished: data.status === 'finished', champion: data.champion ? { ...data.champion, seed: data.champion.id } : null, hideNames: !!data.hideNames, }; } function formatRelDate(iso) { if (!iso) return ''; const days = Math.floor((Date.now() - new Date(iso).getTime()) / 86400000); if (days === 0) return 'hoje'; if (days === 1) return 'ontem'; if (days < 7) return `há ${days} dias`; if (days < 30) return `há ${Math.floor(days / 7)} sem`; return `há ${Math.floor(days / 30)} meses`; } // ── Tweaks defaults ──────────────────────────────────────────────── const TWEAK_DEFAULTS = { anims: true, cardStyle: 'default' }; // ── Theme ───────────────────────────────────────────────────────── function initTheme() { const saved = localStorage.getItem('theme') || 'dark'; document.documentElement.setAttribute('data-theme', saved); return saved; } // ── App ─────────────────────────────────────────────────────────── function App() { const [t, setTweak] = useTweaks(TWEAK_DEFAULTS); const [theme, setTheme] = useAppState(initTheme); function toggleTheme() { const next = theme === 'dark' ? 'light' : 'dark'; setTheme(next); document.documentElement.setAttribute('data-theme', next); localStorage.setItem('theme', next); } // Screen: determined by URL, not changeable in-app (full navigation) const screen = IS_ADMIN_LOGIN ? 'login' : IS_ADMIN_HOME ? 'admin-home' : IS_ADMIN_SETTINGS ? 'admin-settings' : IS_ADMIN_REGISTRATIONS ? 'admin-registrations' : IS_ADMIN_ADMINS ? 'admin-admins' : IS_INSCRICAO ? 'inscricao' : IS_RULES ? 'rules' : IS_BATTLE ? 'battle' : IS_VIEW ? 'view' : IS_CHAMP ? 'bracket' : 'home'; const [tournament, setTournament] = useAppState(null); const [loading, setLoading] = useAppState(IS_CHAMP || IS_BATTLE || IS_VIEW); const [notFound, setNotFound] = useAppState(false); const [recent, setRecent] = useAppState([]); const [showPlayers, setShowPlayers] = useAppState(false); const [showChamp, setShowChamp] = useAppState(false); const [champDismissed, setChampDismissed] = useAppState(false); const [creating, setCreating] = useAppState(false); const [adminUser, setAdminUser] = useAppState(null); const [adminChecking, setAdminChecking] = useAppState(IS_ADMIN); // ── Load on mount ──────────────────────────────────────────── useAppEffect(() => { if (IS_ADMIN) { fetch('/api/admin/me') .then(r => r.ok ? r.json() : Promise.reject()) .then(d => { setAdminUser(d.username); setAdminChecking(false); if (IS_ADMIN_HOME) fetchRecent(); }) .catch(() => { window.location.href = '/admin/login?next=' + encodeURIComponent(_path); }); } else if (IS_CHAMP || IS_BATTLE || IS_VIEW) { fetchTournament(); } }, []); async function fetchTournament() { setLoading(true); try { const res = await fetch(`/api/tournaments/${TOURNAMENT_ID}`); if (!res.ok) { setNotFound(true); return; } const data = await res.json(); const t = backendToReact(data); setTournament(t); document.title = [t.title, t.name].filter(Boolean).join(' — '); if (t.finished && !champDismissed) { setTimeout(() => setShowChamp(true), 600); } } catch { setNotFound(true); } finally { setLoading(false); } } async function fetchRecent() { try { const res = await fetch('/api/tournaments'); const list = await res.json(); setRecent(list.map(r => ({ id: r.id, name: r.name, fighters: r.totalFighters || 0, status: r.status === 'running' ? 'live' : r.status === 'finished' ? 'finished' : 'draft', date: formatRelDate(r.createdAt), }))); } catch {} } // ── Delete tournament ──────────────────────────────────────── async function handleDeleteTournament(id) { const res = await fetch(`/api/tournaments/${id}`, { method: 'DELETE' }); if (res.ok) setRecent(prev => prev.filter(t => t.id !== id)); } // ── Admin logout ───────────────────────────────────────────── async function handleLogout() { await fetch('/admin/logout', { method: 'POST' }); window.location.href = '/admin/login'; } // ── Create tournament ──────────────────────────────────────── async function handleCreate({ name, title, rules, bgColor, winsNeeded, fighters, registrationMode }) { if (creating) return; setCreating(true); try { const res = await fetch('/api/tournaments', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, title, rules, bgColor, winsNeeded, fighters, registrationMode: !!registrationMode }), }); if (res.status === 401) { window.location.href = '/admin/login?next=/admin'; return; } const data = await res.json(); if (res.ok) { window.location.href = `/champion/${data.id}`; } } finally { setCreating(false); } } // ── Pick winner (calls API, refreshes state) ───────────────── async function handlePick(ri, mi, side) { if (!TOURNAMENT_ID) return; try { const res = await fetch(`/api/tournaments/${TOURNAMENT_ID}/draw`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ round: ri, match: mi, side }), }); if (!res.ok) return; const data = await res.json(); const t = backendToReact(data); setTournament(t); if (t.finished && !champDismissed) { setTimeout(() => setShowChamp(true), 600); } } catch {} } // ── Undo winner (reset match back to ready) ────────────────── async function handleUndo(ri, mi) { if (!TOURNAMENT_ID) return; try { const res = await fetch(`/api/tournaments/${TOURNAMENT_ID}/undo`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ round: ri, match: mi }), }); if (!res.ok) return; const data = await res.json(); const t = backendToReact(data); setTournament(t); setShowChamp(false); setChampDismissed(false); } catch {} } // ── Loading / error screens ────────────────────────────────── if (loading) { return (
Carregando...
); } if (notFound) { return (
404
Campeonato não encontrado.
← Criar novo
); } // ── Main render ────────────────────────────────────────────── return ( <> {screen === 'login' && ( )} {screen === 'admin-home' && !adminChecking && ( <>
Painel Admin
Admins {adminUser && {adminUser}}
)} {screen === 'admin-settings' && !adminChecking && TOURNAMENT_ID && ( )} {screen === 'admin-registrations' && !adminChecking && TOURNAMENT_ID && ( )} {screen === 'admin-admins' && !adminChecking && ( )} {screen === 'bracket' && tournament && ( { window.location.href = '/'; }} onShowPlayers={() => setShowPlayers(true)} cardStyle={t.cardStyle} anims={t.anims} hideNames={tournament.hideNames} /> )} {screen === 'view' && tournament && ( { window.location.href = `/inscricao/${TOURNAMENT_ID}`; }} onShowPlayers={() => setShowPlayers(true)} cardStyle={t.cardStyle} anims={t.anims} hideNames={tournament.hideNames} readOnly={true} /> )} {screen === 'battle' && TOURNAMENT_ID && ( )} {screen === 'inscricao' && TOURNAMENT_ID && ( )} {screen === 'rules' && TOURNAMENT_ID && ( )} {showPlayers && tournament && ( setShowPlayers(false)} /> )} {showChamp && tournament && ( { setShowChamp(false); setChampDismissed(true); }} onNew={() => { window.location.href = '/'; }} anims={t.anims} /> )} setTweak('cardStyle', v)} /> setTweak('anims', v)} /> {tournament && screen === 'bracket' && ( setShowChamp(true)} disabled={!tournament.finished} > Mostrar takeover do campeão fetchTournament()}> Recarregar dados { window.location.href = '/'; }}> Voltar para home )} ); } ReactDOM.createRoot(document.getElementById('root')).render();