/* Courtside public board. Renders entirely from the state JSON embedded in the page, then keeps it fresh over a WebSocket. No framework, no build step. */ (() => { const app = document.getElementById('app'); let state = JSON.parse(document.getElementById('state').textContent); const myTeam = app.dataset.team || null; const display = app.dataset.display === '1'; const seenAlerts = new Set(); const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); const name = t => t ? esc(t.name) : 'TBD'; const isMine = m => myTeam && (m.a?.id === myTeam || m.b?.id === myTeam); const phaseLabel = { checkin: 'Registration open', closed: 'Registration closed', live: 'Live', final: 'Final' }; const score = m => m.status === 'final' ? m.sets.map(s => `${s[0]}–${s[1]}`).join(', ') : m.status === 'forfeit' ? 'forfeit' : m.live ? `${m.live[0]}–${m.live[1]}` : m.status === 'live' ? '0–0' : ''; const rulesLine = r => `${r.teamSize}s · to ${r.pointsTo}, win by ${r.winBy}${r.cap ? `, cap ${r.cap}` : ''}${r.bestOf > 1 ? `, best of ${r.bestOf}` : ''}`; function render() { const s = state; const mine = myTeam ? [...s.teams, ...s.withdrawn].find(t => t.id === myTeam) : null; const parts = []; if (!display) parts.push(`
${esc(s.date ?? '')} · ${phaseLabel[s.phase]}

${esc(s.name)}

${rulesLine(s.rules)}${s.avgMatchMin ? ` · matches running ~${s.avgMatchMin} min` : ''}

`); else parts.push(`

${esc(s.name)}

${phaseLabel[s.phase]}
`); if (s.banner) parts.push(``); if (s.champion) parts.push(`
Champion

${esc(s.champion)}

`); if (mine) parts.push(renderMyTeam(mine)); if (s.phase === 'live') { parts.push(renderCourts()); parts.push(renderUpNext()); } if (s.phase === 'closed' && !s.pools.length) parts.push(`

Schedule coming

Registration is closed with ${s.teams.length} teams. The organizer is generating pools now; this page will update on its own.

`); if (s.bracket.length) parts.push(renderBracket()); if (s.pools.length) parts.push(renderPools()); if (!s.pools.length && !s.bracket.length) parts.push(renderRoster()); if (s.withdrawn.length && !display) parts.push(`

Withdrawn: ${s.withdrawn.map(t => esc(t.name)).join(', ')}

`); app.innerHTML = parts.join(''); notifyMine(); } function renderMyTeam(t) { const s = state; const my = [...s.pools.flatMap(p => p.matches), ...s.bracket].filter(isMine); const live = my.find(m => m.status === 'live'); const next = s.upNext.find(isMine) ?? my.find(m => m.status === 'on_deck' || (m.status === 'pending' && m.a && m.b)); const played = my.filter(m => m.status === 'final' || m.status === 'forfeit'); const w = played.filter(m => m.winner === t.id).length; let now; if (t.status === 'withdrawn') now = `

Your team has withdrawn from the tournament.

`; else if (live) now = `

You're on Court ${live.court} now vs ${name(live.a?.id === t.id ? live.b : live.a)}

`; else if (next) now = `

Next: vs ${name(next.a?.id === t.id ? next.b : next.a)}${next.court ? ` on Court ${next.court}` : ''}${next.etaMin != null ? ` in about ${next.etaMin} min` : ''}

`; else if (s.phase === 'final') now = `

Tournament over. Thanks for playing.

`; else if (s.phase === 'live') now = `

No match scheduled yet. Waiting on results from other courts.

`; else now = `

Waiting for play to start.

`; return `
Your team

${esc(t.name)}

${now}

${played.length ? `Record ${w}–${played.length - w}` : 'No results yet'}${t.poolId ? ` · Pool ${esc(t.poolId)}` : ''}

${my.length ? `` : ''} ${!display && 'Notification' in window && Notification.permission === 'default' ? `` : ''}
`; } function renderCourts() { return `
${state.courts.map(c => { const m = c.match; if (c.status === 'paused') return `
Court ${c.court}
Paused
`; if (!m) return `
Court ${c.court}
Open
`; return `
Court ${c.court} · ${m.stage === 'pool' ? `Pool ${esc(m.a && state.teams.find(t => t.id === m.a.id)?.poolId || '')} R${m.round}` : (m.label ?? `Bracket R${m.round}`)}
${name(m.a)}
${score(m) || '0–0'}
${name(m.b)}
`; }).join('')}
`; } function renderUpNext() { if (!state.upNext.length) return ''; return `
Up next
${state.upNext.map((u, i) => `
${i === 0 ? 'On deck' : 'Then'}${name(u.a)} vs ${name(u.b)}Court ${u.court} · ~${u.etaMin} min
`).join('')}
`; } function renderPools() { return `
${state.pools.map(p => `

Pool ${esc(p.id)}

${p.standings.map((r, i) => ``).join('')}
TeamWLPts+/−
${i + 1}. ${esc(r.name)}${r.decidedBy ? `*` : ''}${r.w}${r.l}${r.pf}–${r.pa}${r.pointDiff > 0 ? '+' : ''}${r.pointDiff}
Matches
    ${p.matches.map(m => `
  • R${m.round}${name(m.a)}${score(m) || (m.court ? `C${m.court}` : '·')}${name(m.b)}
  • `).join('')}
`).join('')}
`; } function renderBracket() { const groups = [['bracket', 'Bracket'], ['losers', 'Losers bracket'], ['final', 'Finals']]; return `

${state.bracket.some(m => m.stage === 'losers') ? 'Double elimination' : 'Bracket'}

${groups.map(([stage, title]) => { const ms = state.bracket.filter(m => m.stage === stage && !(m.conditional && m.status !== 'final' && !m.a)); if (!ms.length) return ''; const rounds = [...new Set(ms.map(m => m.round))].sort((a, b) => a - b); return `

${title}

${rounds.map(r => `
${roundName(stage, r, rounds.length, ms)}
${ms.filter(m => m.round === r).map(m => `
${m.label ? `
${esc(m.label)}
` : ''}
${name(m.a)}${m.sets[0] ? m.sets.map(s => s[0]).join(' ') : ''}
${name(m.b)}${m.sets[0] ? m.sets.map(s => s[1]).join(' ') : ''}
${m.status === 'live' ? `
Court ${m.court}${m.live ? ` · ${m.live[0]}–${m.live[1]}` : ''}
` : m.status === 'forfeit' ? '
forfeit
' : ''}
`).join('')}
`).join('')}
`; }).join('')}
`; } function roundName(stage, r, total, ms) { if (stage === 'final') return r === 1 ? 'Grand final' : 'Reset'; if (stage === 'losers') return `LB round ${r}`; const left = total - r; const inRound = ms.filter(m => m.round === r && m.label !== '3rd place').length; return left === 0 ? 'Final' : left === 1 ? 'Semifinals' : left === 2 ? 'Quarterfinals' : `Round of ${inRound * 2}`; } function renderRoster() { return `

Teams (${state.teams.length})

    ${state.teams.map(t => `
  1. ${esc(t.name)} (${t.players})
  2. `).join('')}
`; } // ---- alerts for the team page ---- function notifyMine() { if (!myTeam) return; for (const a of state.recentAlerts) { const key = `${a.kind}:${a.match ?? a.at}`; if (seenAlerts.has(key)) continue; seenAlerts.add(key); if (!(a.kind === 'broadcast' || a.teams.includes(myTeam))) continue; if (Date.now() - a.at > 10 * 60 * 1000) continue; // stale on first load toast(a.text); try { navigator.vibrate?.([200, 100, 200]); } catch {} if ('Notification' in window && Notification.permission === 'granted') { try { new Notification('Courtside', { body: a.text, tag: key }); } catch {} } } } function toast(text) { const el = document.createElement('div'); el.className = 'toast'; el.textContent = text; document.body.appendChild(el); setTimeout(() => el.remove(), 8000); } document.addEventListener('click', e => { if (e.target.id === 'notify') Notification.requestPermission().then(render); }); // first paint: skip toasts for alerts that already happened for (const a of state.recentAlerts) seenAlerts.add(`${a.kind}:${a.match ?? a.at}`); // ---- live updates ---- let retry = 1000; function connect() { const ws = new WebSocket(`${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}/ws/${state.slug}`); ws.onmessage = ev => { state = JSON.parse(ev.data); retry = 1000; render(); }; ws.onclose = () => { setTimeout(connect, retry); retry = Math.min(retry * 2, 15000); }; ws.onerror = () => ws.close(); } render(); connect(); // belt and braces: a full refresh every 2 minutes in case a proxy drops the socket silently setInterval(() => fetch(`/t/${state.slug}/state.json`).then(r => r.json()).then(s => { state = s; render(); }).catch(() => {}), 120000); if (display) setInterval(() => document.documentElement.scrollTo({ top: (Date.now() / 1000 | 0) % 2 ? 0 : document.body.scrollHeight, behavior: 'smooth' }), 15000); })();