// stats.js — "Stats" tab. Tournament-to-date aggregates derived ONLY from data // the project already has (results.json scores/status + optional per-match // stats, matches.json phase). Counts finished matches only, consistent with // computeStandings (live/scheduled ignored). Built as the evolving foundation // for the post-tournament stats screen (see .agents/stats-screen-plan.md): // sections gate on data so player/award/editorial blocks slot in later. import { getData, flagSrc, navigateTo } from './app.js'; import { t, translatePhase } from './i18n.js'; // "Goals by stage" collapses all 12 groups into one bucket; knockout phases // keep their own. Order used to render the chart left-to-right. const STAGE_ORDER = ['Round of 32', 'Round of 16', 'Quarterfinals', 'Semifinals', 'Third Place', 'Final']; // Per-team table: all 48 teams, 8 per page (6 fixed pages). Sortable columns — // existing standings.* labels are reused for the abbreviations the user already // knows from the Groups tab; the two new ones carry a full-name title tooltip. const PAGE_SIZE = 8; const COLUMNS = [ { key: 'played', label: 'standings.played', tip: 'tip.played' }, { key: 'won', label: 'standings.won', tip: 'tip.won' }, { key: 'drawn', label: 'standings.drawn', tip: 'tip.drawn' }, { key: 'lost', label: 'standings.lost', tip: 'tip.lost' }, { key: 'gf', label: 'standings.gf', tip: 'tip.gf' }, { key: 'ga', label: 'standings.ga', tip: 'tip.ga' }, { key: 'gd', label: 'standings.gd', tip: 'tip.gd' }, { key: 'points', label: 'standings.pts', tip: 'tip.pts' }, { key: 'gpg', label: 'stats.colGpg', tip: 'tip.gpg' }, { key: 'cleanSheets', label: 'stats.colCS', tip: 'tip.cs' }, ]; let model = null; // table interaction state — survives langchange re-renders (default on load: // most goals first, page 1), like the bracket keeps its zoom across re-renders. let sortKey = 'gf'; let sortDir = 'desc'; let teamPage = 0; function stageOf(phase) { return phase.startsWith('Group ') ? 'Group' : phase; } // Tournament-wide team aggregation over finished matches (group + knockout). // computeStandings() only covers group matches, so this is its own pass. // possession/shots/cards are gated per-match: a finished match without the // optional `stats` object simply doesn't contribute (no visible distortion). function aggregateTeams(finished, resultByMatchId) { const rows = new Map(); const row = (id) => { if (!rows.has(id)) { rows.set(id, { teamId: id, played: 0, won: 0, drawn: 0, lost: 0, gf: 0, ga: 0, cleanSheets: 0, possSum: 0, possCount: 0, shots: 0, cards: 0, }); } return rows.get(id); }; for (const m of finished) { const r = resultByMatchId.get(m.id); const home = row(m.homeTeam); const away = row(m.awayTeam); applySide(home, r.homeScore, r.awayScore); applySide(away, r.awayScore, r.homeScore); if (r.stats) { const s = r.stats; if (s.possession) { home.possSum += s.possession.home; home.possCount += 1; away.possSum += s.possession.away; away.possCount += 1; } if (s.shots) { home.shots += s.shots.home; away.shots += s.shots.away; } if (s.cards) { home.cards += s.cards.home; away.cards += s.cards.away; } } } return rows; } function applySide(row, gf, ga) { row.played += 1; row.gf += gf; row.ga += ga; if (ga === 0) row.cleanSheets += 1; if (gf > ga) row.won += 1; else if (gf === ga) row.drawn += 1; else row.lost += 1; } function buildStatsModel() { const { matches, resultByMatchId } = getData(); const finished = matches.filter((m) => resultByMatchId.get(m.id)?.status === 'finished'); let totalGoals = 0; let draws = 0; let decisive = 0; let biggestMargin = 0; const byStage = new Map(); for (const m of finished) { const r = resultByMatchId.get(m.id); const total = r.homeScore + r.awayScore; totalGoals += total; if (r.homeScore === r.awayScore) draws += 1; else decisive += 1; biggestMargin = Math.max(biggestMargin, Math.abs(r.homeScore - r.awayScore)); const stage = stageOf(m.phase); const bucket = byStage.get(stage) ?? { goals: 0, count: 0 }; bucket.goals += total; bucket.count += 1; byStage.set(stage, bucket); } const agg = aggregateTeams(finished, resultByMatchId); let cleanSheets = 0; for (const r of agg.values()) cleanSheets += r.cleanSheets; // one row per team for ALL 48 (teams that haven't played yet are real zeros, // not gaps), with the derived columns the table needs. const teamStats = getData().teams.map((team) => { const a = agg.get(team.id); const gf = a?.gf ?? 0; const ga = a?.ga ?? 0; const won = a?.won ?? 0; const drawn = a?.drawn ?? 0; const played = a?.played ?? 0; return { teamId: team.id, played, won, drawn, lost: a?.lost ?? 0, gf, ga, gd: gf - ga, points: won * 3 + drawn, cleanSheets: a?.cleanSheets ?? 0, gpg: played ? gf / played : 0, }; }); return { totalMatches: matches.length, finishedCount: finished.length, totalGoals, avgGoals: finished.length ? totalGoals / finished.length : 0, draws, decisive, biggestMargin, cleanSheets, byStage, teamStats, leaders: computeLeaders(teamStats), }; } // Highlight leaders consider only teams that have played, so a 0-game team's // empty record never counts as "best defense". Null before any match finishes. function computeLeaders(teamStats) { const played = teamStats.filter((row) => row.played > 0); if (!played.length) return null; return { bestAttack: [...played].sort((a, b) => b.gf - a.gf || b.gd - a.gd)[0], bestDefense: [...played].sort((a, b) => a.ga - b.ga || b.cleanSheets - a.cleanSheets || b.gd - a.gd)[0], mostCleanSheets: [...played].sort((a, b) => b.cleanSheets - a.cleanSheets || a.ga - b.ga)[0], }; } // ---------------------------------------------------------------- render export function initStats() { render(); // labels re-render on language change; the derived model never changes at // runtime (data is static per page load) so it is reused. document.addEventListener('langchange', render); // new published results change the aggregates → rebuild the memoized model document.addEventListener('datachange', () => { model = null; render(); }); } function render() { if (!model) model = buildStatsModel(); const root = document.getElementById('stats-root'); root.innerHTML = heroHTML() + overviewHTML() + teamsSectionHTML() + footerHTML(); root.querySelector('#stats-see-matches')?.addEventListener('click', () => navigateTo('matches')); const teamsHost = root.querySelector('#stats-teams-table'); if (teamsHost) { teamsHost.addEventListener('click', onTeamTableClick); renderTeamTable(); } setupCountUps(root); } function heroHTML() { const m = model; const progress = t('stats.heroProgress') .replace('{x}', String(m.finishedCount)) .replace('{y}', String(m.totalMatches)); const tiles = [ { value: m.totalGoals, decimals: 0, label: t('stats.tileGoals') }, { value: Number(m.avgGoals.toFixed(2)), decimals: 2, label: t('stats.tileAvg') }, { value: m.biggestMargin, decimals: 0, label: t('stats.tileBiggestMargin') }, { value: m.cleanSheets, decimals: 0, label: t('stats.tileCleanSheets') }, ]; return ` `; } function overviewHTML() { const m = model; const cards = [ { value: String(m.finishedCount), sub: `/ ${m.totalMatches}`, label: t('stats.played') }, { value: String(m.decisive), label: t('stats.decisive') }, { value: String(m.draws), label: t('stats.draws') }, ]; return `
`; } function goalsByStageHTML() { const order = ['Group', ...STAGE_ORDER].filter((stage) => model.byStage.has(stage)); if (!order.length) return ''; const max = Math.max(...order.map((stage) => model.byStage.get(stage).goals)); const rows = order.map((stage) => { const bucket = model.byStage.get(stage); const pct = max ? Math.round((bucket.goals / max) * 100) : 0; const label = stage === 'Group' ? t('stats.stageGroup') : translatePhase(stage); return `
${pairs}
`; } function leadersHTML() { const leaders = model.leaders; if (!leaders) return ''; const cards = [ { label: t('stats.bestAttack'), row: leaders.bestAttack, value: leaders.bestAttack.gf }, { label: t('stats.bestDefense'), row: leaders.bestDefense, value: leaders.bestDefense.ga }, { label: t('stats.mostCleanSheets'), row: leaders.mostCleanSheets, value: leaders.mostCleanSheets.cleanSheets }, ]; return `| # | ${t('standings.team')} | ${head}
|---|