// Bracket screen — running tournament with clickable matches const { useState: useBState, useEffect: useBEffect, useMemo: useBMemo, useRef: useBRef } = React; // Build a sorted bracket from fighters list (with byes) function buildBracket(fighters) { const N = fighters.length; if (N < 2) return null; const rounds = Math.ceil(Math.log2(N)); const slots = Math.pow(2, rounds); const byes = slots - N; // Seed (1-indexed) const seeded = fighters.map((name, i) => ({ id: i + 1, seed: i + 1, name })); // Distribute byes: insert at standard positions (top-heavy) const padded = [...seeded]; for (let i = 0; i < byes; i++) padded.push({ id: 1000 + i, seed: null, name: 'Passe livre', bye: true }); // Match seeding: 1v16, 8v9, etc — simple pairing for prototype // Pair: i with N-1-i const pairs = []; for (let i = 0; i < slots / 2; i++) { pairs.push([padded[i], padded[slots - 1 - i]]); } // Build round 0 matches const r0Matches = pairs.map(([a, b]) => { const isBoth = a.bye && b.bye; const isAuto = (a.bye && !b.bye) || (b.bye && !a.bye); let status = 'ready'; let winner = null; if (isBoth) { status = 'bye'; winner = null; } else if (isAuto) { status = 'done'; winner = a.bye ? b : a; } return { a, b, winner, status }; }); const allRounds = [{ name: roundName(rounds, 0), matches: r0Matches }]; // Build subsequent rounds for (let r = 1; r < rounds; r++) { const prev = allRounds[r - 1].matches; const matches = []; for (let i = 0; i < prev.length; i += 2) { const a = prev[i].winner; const b = prev[i + 1]?.winner; const ready = a && b; const both = !a && !b; const auto = (a && !b) || (!a && b); matches.push({ a: a || null, b: b || null, winner: auto ? (a || b) : null, status: both ? 'bye' : auto ? 'done' : ready ? 'ready' : 'waiting', }); } allRounds.push({ name: roundName(rounds, r), matches }); } return { rounds: allRounds, totalRounds: rounds }; } function roundName(total, ri) { const remaining = Math.pow(2, total - ri); if (remaining === 2) return 'Final'; if (remaining === 4) return 'Semifinal'; if (remaining === 8) return 'Quartas'; if (remaining === 16) return 'Oitavas'; return `Rodada ${ri + 1}`; } // Pure: pick winner side, propagate forward function pickWinner(bracket, ri, mi, side) { const next = JSON.parse(JSON.stringify(bracket)); const m = next.rounds[ri].matches[mi]; if (m.status !== 'ready') return next; const winner = side === 'a' ? m.a : m.b; if (!winner) return next; m.winner = winner; m.status = 'done'; // Propagate let curRi = ri, curMi = mi; while (curRi + 1 < next.rounds.length) { const nri = curRi + 1; const nmi = Math.floor(curMi / 2); const slot = curMi % 2 === 0 ? 'a' : 'b'; const nextMatch = next.rounds[nri].matches[nmi]; nextMatch[slot] = winner; if (nextMatch.a && nextMatch.b) nextMatch.status = 'ready'; else if (!nextMatch.a && !nextMatch.b) nextMatch.status = 'waiting'; else nextMatch.status = 'waiting'; break; } return next; } function isFinished(bracket) { if (!bracket) return false; const last = bracket.rounds[bracket.rounds.length - 1]; return last.matches[0]?.status === 'done'; } function getChampion(bracket) { if (!isFinished(bracket)) return null; const last = bracket.rounds[bracket.rounds.length - 1]; return last.matches[0].winner; } // ── Match card ── function MatchCard({ match, ri, mi, onPick, onUndo, label, cardStyle, anims, tournamentId, hideNames, advancedKey, readOnly }) { const ready = match.status === 'ready'; const done = match.status === 'done'; const waiting = match.status === 'waiting'; const bye = match.status === 'bye'; const canUndo = done && !(match.a?.bye) && !(match.b?.bye); if (bye) { return
; } const cls = `match-card match-card--${cardStyle} match-card--${match.status} ${anims ? '' : 'no-anim'}`; const battleUrl = tournamentId ? `/battle/${tournamentId}/${ri}/${mi}` : null; return (
{label} {ready && !readOnly && ( <> escolha o vencedor {battleUrl && ( e.stopPropagation()} >⚔ )} )} {ready && readOnly && <> ao vivo} {done && finalizado} {canUndo && onUndo && !readOnly && ( )} {waiting && aguardando}
ready && match.a && onPick && onPick(ri, mi, 'a')} cardStyle={cardStyle} hideNames={hideNames} isAdvancing={advancedKey === `${ri}-${mi}-a`} readOnly={readOnly} />
VS
ready && match.b && onPick && onPick(ri, mi, 'b')} cardStyle={cardStyle} hideNames={hideNames} isAdvancing={advancedKey === `${ri}-${mi}-b`} readOnly={readOnly} />
); } function FighterRow({ fighter, side, match, onClick, cardStyle, hideNames, isAdvancing, readOnly }) { const isWinner = match.winner && fighter && match.winner.name === fighter.name && match.winner.seed === fighter.seed; const isLoser = match.status === 'done' && fighter && !isWinner && !fighter.bye; const isClickable = !readOnly && match.status === 'ready' && fighter && !fighter.bye; const c = fighter && !fighter.bye ? fighterColor(fighter.seed, fighter.name) : null; const cls = [ 'fighter-row', isWinner && 'fighter-row--winner', isLoser && 'fighter-row--loser', isClickable && 'fighter-row--clickable', fighter?.bye && 'fighter-row--bye', !fighter && 'fighter-row--empty', isAdvancing && 'fighter-row--advancing', ].filter(Boolean).join(' '); return ( ); } // ── Bracket layout (horizontal columns) ── function BracketView({ bracket, onPick, onUndo, cardStyle, anims, tournamentId, hideNames, readOnly }) { const N = bracket.rounds[0].matches.length; const COL_W = cardStyle === 'cinematic' ? 280 : cardStyle === 'minimal' ? 220 : 250; const COL_GAP = 56; const SLOT_MIN = cardStyle === 'cinematic' ? 164 : cardStyle === 'minimal' ? 90 : 140; const ref = useBRef(null); const [rect, setRect] = useBState({ w: 0, h: 0 }); const [zoom, setZoom] = useBState(() => window.innerWidth < 480 ? 0.55 : 1); const [advancedKey, setAdvancedKey] = useBState(null); const [isFullscreen, setIsFullscreen] = useBState(false); useBEffect(() => { function onFsChange() { setIsFullscreen(!!document.fullscreenElement); } document.addEventListener('fullscreenchange', onFsChange); return () => document.removeEventListener('fullscreenchange', onFsChange); }, []); function handlePick(ri, mi, side) { const nri = ri + 1; if (nri < bracket.rounds.length) { const nmi = Math.floor(mi / 2); const slot = mi % 2 === 0 ? 'a' : 'b'; const key = `${nri}-${nmi}-${slot}`; setAdvancedKey(key); setTimeout(() => setAdvancedKey(null), 900); } onPick(ri, mi, side); } function changeZoom(delta) { setZoom(z => Math.min(2.5, Math.max(0.35, parseFloat((z + delta).toFixed(2))))); } function toggleFullscreen() { if (!document.fullscreenElement) { document.documentElement.requestFullscreen(); } else { document.exitFullscreen(); } } useBEffect(() => { function update() { if (!ref.current) return; const r = ref.current.getBoundingClientRect(); setRect({ w: r.width, h: r.height }); } update(); window.addEventListener('resize', update); return () => window.removeEventListener('resize', update); }, []); const slotH = Math.max(SLOT_MIN, Math.min(200, Math.floor((rect.h - 50) / Math.max(N, 1)))); const totalH = N * slotH + 36; const totalW = bracket.rounds.length * (COL_W + COL_GAP) - COL_GAP; // Connector lines const lines = useBMemo(() => { const out = []; for (let ri = 0; ri < bracket.rounds.length - 1; ri++) { const x1 = ri * (COL_W + COL_GAP) + COL_W; const x2 = (ri + 1) * (COL_W + COL_GAP); const xMid = x1 + COL_GAP / 2; for (let j = 0; j < bracket.rounds[ri + 1].matches.length; j++) { const yTop = 36 + (j * 2 + 0.5) * Math.pow(2, ri) * (totalH - 36) / N; const yBot = 36 + (j * 2 + 1.5) * Math.pow(2, ri) * (totalH - 36) / N; const yMid = (yTop + yBot) / 2; const top = bracket.rounds[ri].matches[j * 2]; const bot = bracket.rounds[ri].matches[j * 2 + 1]; const next = bracket.rounds[ri + 1].matches[j]; if (top.status === 'bye' && bot.status === 'bye') continue; let d = ''; if (top.status !== 'bye') d += `M${x1} ${yTop} H${xMid} `; if (bot.status !== 'bye') d += `M${x1} ${yBot} H${xMid} `; d += `M${xMid} ${top.status === 'bye' ? yMid : yTop} V${bot.status === 'bye' ? yMid : yBot} `; if (next.status !== 'bye') d += `M${xMid} ${yMid} H${x2}`; const stroke = next.status === 'done' ? 'var(--accent)' : next.status === 'ready' ? 'var(--accent)' : 'var(--border)'; const opacity = next.status === 'done' ? 0.6 : next.status === 'ready' ? 0.4 : 1; out.push({ d, stroke, opacity }); } } return out; }, [bracket, totalH, N, COL_W]); return (
{/* Spacer establishes scrollable area matching scaled content */}
{lines.map((l, i) => ( ))} {bracket.rounds.map((round, ri) => (
{round.name} {round.matches.filter(m => m.status !== 'bye').length} {round.matches.filter(m => m.status !== 'bye').length === 1 ? 'combate' : 'combates'}
{round.matches.map((m, mi) => { const slotHi = Math.pow(2, ri) * (totalH - 36) / N; const top = mi * slotHi; return (
); })}
))}
{/* Floating zoom controls */}
); } function RegistrationOpenView({ tournament, tournamentId }) { const link = `${window.location.origin}/inscricao/${tournamentId}`; const [copied, setCopied] = React.useState(false); const [inscricoes, setInscricoes] = React.useState(null); // null = loading, [] = empty const [togglingId, setTogglingId] = React.useState(null); React.useEffect(() => { fetch(`/api/tournaments/${tournamentId}/inscricoes`) .then(r => r.ok ? r.json() : Promise.reject()) .then(data => setInscricoes(data)) .catch(() => setInscricoes([])); // not admin or error — hide list }, []); function copyLink() { navigator.clipboard.writeText(link); setCopied(true); setTimeout(() => setCopied(false), 2000); } async function setStatus(reg, newStatus) { setTogglingId(reg.id); try { const res = await fetch(`/api/inscricoes/${reg.id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ status: newStatus }), }); if (!res.ok) return; setInscricoes(prev => prev.map(r => r.id === reg.id ? { ...r, status: newStatus } : r)); } catch {} finally { setTogglingId(null); } } const statusLabel = { pending: 'Pendente', approved: 'Aprovado', paid: 'Pago', rejected: 'Rejeitado' }; return (
{tournament.name} {tournament.title && {tournament.title}}
⚙
{/* Link card */}
Inscrições abertas

{tournament.name}

{tournament.title &&
{tournament.title}
}

O chaveamento ainda não foi gerado. Compartilhe o link de inscrição com os participantes. Quando todas as inscrições forem aprovadas, o admin gera o chaveamento nas configurações.

{link}
{tournament.rules && ( Ver regulamento → )} ⚙ Configurações
{/* Inscriptions list — only shown if admin (API returns 401 otherwise) */} {inscricoes !== null && inscricoes.length > 0 && (
Inscrições {inscricoes.length} Gerenciar →
{inscricoes.map(reg => { const busy = togglingId === reg.id; const cpfFmt = reg.cpf.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4'); const phoneFmt = reg.phone.length === 11 ? reg.phone.replace(/(\d{2})(\d{5})(\d{4})/, '($1) $2-$3') : reg.phone.replace(/(\d{2})(\d{4})(\d{4})/, '($1) $2-$3'); return (
{reg.nickname ? <>{reg.nickname} — {reg.name} : reg.name}
{cpfFmt} · {phoneFmt}
{statusLabel[reg.status] || reg.status} {reg.status === 'pending' && ( <> )} {reg.status === 'approved' && ( <> )} {reg.status === 'paid' && ( )} {reg.status === 'rejected' && ( )}
); })}
{(() => { const approved = inscricoes.filter(r => r.status === 'approved' || r.status === 'paid').length; return (
{['pending','approved','paid','rejected'].map(s => { const n = inscricoes.filter(r => r.status === s).length; if (!n) return null; const lbl = { pending: 'pendentes', approved: 'aprovados', paid: 'pagos', rejected: 'rejeitados' }; return {n} {lbl[s]}; }).filter(Boolean).reduce((acc, el, i) => i === 0 ? [el] : [...acc, ' · ', el], [])}
); })()}
)}
); } function BracketScreen({ tournament, onPick, onUndo, onBack, onShowPlayers, cardStyle, anims, tournamentId, hideNames, readOnly }) { if (tournament.registering && !readOnly) { return ; } const champ = getChampion(tournament.bracket); const finished = !!champ; const totalMatches = tournament.bracket.rounds.flatMap(r => r.matches).filter(m => m.status !== 'bye').length; const doneMatches = tournament.bracket.rounds.flatMap(r => r.matches).filter(m => m.status === 'done').length; const liveMatches = tournament.bracket.rounds.flatMap(r => r.matches).filter(m => m.status === 'ready').length; return (
{tournament.name} {tournament.title && {tournament.title}}
{doneMatches}/{totalMatches} Combates
{liveMatches} Ao vivo
{tournament.fighters.length} Lutadores
{tournamentId && ( Regulamento )} {tournamentId && !readOnly && ( ⚙ )}
); } window.BracketScreen = BracketScreen; window.buildBracket = buildBracket; window.pickWinner = pickWinner; window.isFinished = isFinished; window.getChampion = getChampion;