This commit is contained in:
2026-06-22 22:11:04 -05:00
parent 73d07e7f18
commit 93ae2cbf0a
9 changed files with 519 additions and 53 deletions

View File

@@ -9,13 +9,15 @@ function Side({
s, prob, teams,
}: { s: ResolvedSide; prob?: number | null; teams: Team[] }) {
const team = s.teamId ? teams.find((t) => t.id === s.teamId) : undefined;
// fix = ein echtes Team steht fest (nicht vorläufig). Eigene Klasse für klares Styling.
const fix = s.teamId != null && !s.provisional;
return (
<div className={`side ${s.isWinner ? "win" : ""} ${s.provisional ? "prov" : ""}`}>
<div className={`side ${s.isWinner ? "win" : ""} ${s.provisional ? "prov" : ""} ${fix ? "fix" : ""}`}>
<span className="nm">
{s.teamId ? (
<>
<Flag team={team} size={18} />
<span>{s.label}</span>
<span className="tn">{s.label}</span>
{s.provisional && <span className="prov-mark" title="vorläufig Gruppe/Zuordnung noch nicht fix"></span>}
</>
) : (
@@ -33,7 +35,7 @@ function Side({
function Tie({ tie, teams, isFinal }: { tie: ResolvedTie; teams: Team[]; isFinal?: boolean }) {
return (
<div className={`tie ${isFinal ? "final-tie" : ""}`}>
<span className="tie-num">Spiel {tie.matchNumber}</span>
<div className="tie-head">Spiel {tie.matchNumber}</div>
<Side s={tie.home} prob={tie.prob?.home} teams={teams} />
<Side s={tie.away} prob={tie.prob?.away} teams={teams} />
</div>

View File

@@ -1,18 +1,31 @@
"use client";
import { GROUP_IDS, GroupId, Match, Team } from "@/lib/types";
import { computeGroupTables } from "@/lib/standings";
import Flag from "./Flag";
function teamById(teams: Team[], id: string | null) {
return id ? teams.find((t) => t.id === id) : undefined;
}
// Kürzel der lokalen Browser-Zeitzone, z.B. "MEZ"/"GMT+1" einmal ermittelt.
const TZ_LABEL = (() => {
try {
const parts = new Intl.DateTimeFormat("de-DE", { timeZoneName: "short" })
.formatToParts(new Date());
return parts.find((p) => p.type === "timeZoneName")?.value ?? "";
} catch {
return "";
}
})();
function fmtDate(iso: string): string {
const d = new Date(iso);
return d.toLocaleString("de-DE", {
const s = d.toLocaleString("de-DE", {
weekday: "short", day: "2-digit", month: "2-digit",
hour: "2-digit", minute: "2-digit",
});
return TZ_LABEL ? `${s} ${TZ_LABEL}` : s;
}
function statusText(m: Match): { text: string; live: boolean } {
@@ -29,7 +42,10 @@ function statusText(m: Match): { text: string; live: boolean } {
}
}
function ScoreOrTime({ m }: { m: Match }) {
// Mitte: Ergebnis (wenn vorhanden) oder ein schlichtes "" bei ungespielten
// Spielen. Datum/Uhrzeit steht bereits links im Status und wird hier NICHT
// wiederholt.
function ScoreCell({ m }: { m: Match }) {
const hasScore = m.homeScore != null && m.awayScore != null;
const st = statusText(m);
if (hasScore) {
@@ -39,7 +55,69 @@ function ScoreOrTime({ m }: { m: Match }) {
</span>
);
}
return <span className="fx-time">{fmtDate(m.utcDate)}</span>;
return <span className="fx-vs"></span>;
}
function GroupStandings({
group, teams, matches,
}: { group: GroupId; teams: Team[]; matches: Match[] }) {
// Live-Tabelle: laufende Spiele werden mit Zwischenstand eingerechnet.
const table = computeGroupTables(teams, matches, true).find((t) => t.group === group);
if (!table) return null;
// Teams, die gerade ein laufendes Spiel haben -> Zeile markieren.
const liveTeamIds = new Set<string>();
let hasLive = false;
for (const m of matches) {
if (m.group !== group) continue;
if (m.status === "LIVE" || m.status === "IN_PLAY" || m.status === "PAUSED") {
hasLive = true;
if (m.homeTeamId) liveTeamIds.add(m.homeTeamId);
if (m.awayTeamId) liveTeamIds.add(m.awayTeamId);
}
}
return (
<div className="fx-standings">
<div className="fx-standings-title">
Tabelle Gruppe {group}
{hasLive && <span className="fx-standings-live"> LIVE</span>}
</div>
<table className="standings">
<thead>
<tr>
<th className="team">Mannschaft</th>
<th>Sp</th><th>S</th><th>U</th><th>N</th>
<th>Tore</th><th>±</th><th>Pkt</th>
</tr>
</thead>
<tbody>
{table.rows.map((r) => {
const team = teamById(teams, r.teamId);
const cls = r.rank <= 2 ? `q${r.rank}` : r.rank === 3 ? "q3" : "";
const isLive = liveTeamIds.has(r.teamId);
return (
<tr key={r.teamId} className={isLive ? "row-live" : ""}>
<td className="team">
<span className={`rankdot ${cls}`}>{r.rank}</span>
<Flag team={team} size={20} />
<span className="team-name">{team?.name ?? r.teamId}</span>
{isLive && <span className="row-live-dot" title="läuft gerade" />}
</td>
<td>{r.played}</td>
<td>{r.won}</td>
<td>{r.drawn}</td>
<td>{r.lost}</td>
<td>{r.goalsFor}:{r.goalsAgainst}</td>
<td>{r.goalDiff > 0 ? `+${r.goalDiff}` : r.goalDiff}</td>
<td className="pts">{r.points}</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}
export default function Fixtures({
@@ -83,14 +161,14 @@ export default function Fixtures({
<span>{st.text}</span>
</div>
<div className="fx-teams">
<div className={`fx-team ${homeWin ? "win" : ""}`}>
<div className={`fx-team home ${homeWin ? "win" : ""}`}>
<Flag team={home} size={22} />
<span className="fx-name">{home?.name ?? "—"}</span>
</div>
<ScoreOrTime m={m} />
<ScoreCell m={m} />
<div className={`fx-team away ${awayWin ? "win" : ""}`}>
<span className="fx-name">{away?.name ?? "—"}</span>
<Flag team={away} size={22} />
<span className="fx-name">{away?.name ?? "—"}</span>
</div>
</div>
<div className="fx-meta">
@@ -104,6 +182,10 @@ export default function Fixtures({
})}
</div>
)}
{list.length > 0 && (
<GroupStandings group={group} teams={teams} matches={matches} />
)}
</div>
);
}

View File

@@ -195,13 +195,12 @@ table.standings { width: 100%; border-collapse: collapse; }
.tie {
background: var(--bg-card); border: 1px solid var(--line);
border-radius: var(--radius-sm); overflow: hidden; position: relative;
border-radius: var(--radius-sm); position: relative;
}
.tie.final-tie { border-color: var(--gold); box-shadow: 0 0 0 1px rgba(255,210,74,0.2); }
.tie-num {
position: absolute; top: -7px; left: 8px;
.tie-head {
font-family: var(--font-mono); font-size: 9px; color: var(--ink-faint);
background: var(--bg); padding: 0 5px;
letter-spacing: 0.04em; padding: 5px 10px 0;
}
.side {
display: flex; align-items: center; justify-content: space-between;
@@ -212,7 +211,6 @@ table.standings { width: 100%; border-collapse: collapse; }
.side .nm .c { font-family: var(--font-mono); font-size: 10px; color: var(--ink-faint); }
.side .lbl { color: var(--ink-dim); font-style: italic; }
.side .sc { font-family: var(--font-mono); font-weight: 700; color: var(--floodlight); }
.side.win .nm { color: var(--turf); font-weight: 700; }
.side.win .sc { color: var(--turf); }
.side .prob {
font-family: var(--font-mono); font-size: 10px; color: var(--ink-faint);
@@ -285,7 +283,7 @@ table.standings { width: 100%; border-collapse: collapse; }
.fx {
background: var(--bg-card); border: 1px solid var(--line);
border-radius: var(--radius); padding: 12px 16px;
display: grid; grid-template-columns: 120px 1fr auto; gap: 14px; align-items: center;
display: grid; grid-template-columns: 110px minmax(0, 560px) 1fr; gap: 14px; align-items: center;
}
.fx-live { border-color: rgba(255,61,127,0.4); }
.fx-status {
@@ -293,19 +291,52 @@ table.standings { width: 100%; border-collapse: collapse; }
font-family: var(--font-mono); font-size: 12px; color: var(--ink-dim);
}
.fx-teams {
display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: 14px;
display: grid;
grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr);
align-items: center; column-gap: 34px;
}
.fx-team { display: flex; align-items: center; gap: 10px; min-width: 0; }
.fx-team.away { justify-content: flex-end; }
/* Beide Teams: Flagge links, Name daneben. Linkes Team rechtsbündig an den Score,
rechtes Team linksbündig so ist der Abstand zum Ergebnis beidseitig gleich. */
.fx-team { display: flex; align-items: center; gap: 8px; min-width: 0; }
.fx-team.home { justify-content: flex-end; }
.fx-team.away { justify-content: flex-start; }
.fx-team .fx-name { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.fx-team.win .fx-name { color: var(--turf); }
.fx-score { font-family: var(--font-mono); font-weight: 700; font-size: 18px; color: var(--floodlight); white-space: nowrap; }
.fx-score { font-family: var(--font-mono); font-weight: 700; font-size: 18px; color: var(--floodlight); white-space: nowrap; text-align: center; min-width: 54px; }
.fx-score.score-live { color: var(--live); }
.fx-time { font-family: var(--font-mono); font-size: 13px; color: var(--ink-faint); white-space: nowrap; }
.fx-vs { font-family: var(--font-mono); font-size: 15px; color: var(--ink-faint); text-align: center; min-width: 54px; }
.fx-meta {
display: flex; flex-direction: column; gap: 3px; align-items: flex-end;
font-family: var(--font-mono); font-size: 11px; color: var(--ink-faint); white-space: nowrap;
}
/* Austragungsort heller hervorheben. */
.fx-venue { color: var(--ink-dim); }
/* Live-Tabelle der Gruppe unterhalb der Spiele. */
.fx-standings { margin-top: 22px; }
.fx-standings-title {
font-family: var(--font-display, var(--font-mono)); font-size: 13px; letter-spacing: 0.06em;
text-transform: uppercase; color: var(--ink-dim); margin: 0 2px 10px;
display: flex; align-items: center; gap: 10px;
}
.fx-standings-live {
font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.04em;
color: var(--live); font-weight: 700;
animation: livepulse 1.6s ease-in-out infinite;
}
.fx-standings .standings { width: 100%; }
/* Zeile eines Teams mit laufendem Spiel hervorheben. */
.fx-standings .row-live { background: rgba(255, 61, 127, 0.07); }
.fx-standings .row-live .team-name { color: var(--floodlight); }
.row-live-dot {
display: inline-block; width: 7px; height: 7px; border-radius: 50%;
background: var(--live); margin-left: 8px; vertical-align: middle;
animation: livepulse 1.6s ease-in-out infinite;
}
@keyframes livepulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.35; }
}
@media (max-width: 720px) {
.fx { grid-template-columns: 1fr; gap: 8px; }
@@ -313,22 +344,27 @@ table.standings { width: 100%; border-collapse: collapse; }
.fx-status { order: -1; }
}
/* Bracket: Label-Fix oben (Match-Nummer ragt über den Rand) */
.round-matches { padding-top: 8px; }
.tie-num {
top: -8px; left: 10px; white-space: nowrap;
}
/* Bracket: Label-Header braucht kein Extra-Padding mehr (sitzt im Kasten) */
.round-matches { padding-top: 0; }
/* Bracket: fix vs. vorläufig */
.side.prov .nm { color: var(--ink-dim); }
.side.prov .nm span:not(.prov-mark) { font-style: italic; }
/* Bracket: fix vs. vorläufig.
.nm trägt die Standardfarbe; Team-Name liegt in .tn. */
.side .nm .tn { color: var(--ink); }
/* vorläufig: gedimmt + kursiv + Marker */
.side.prov .nm .tn { color: var(--ink-dim); font-style: italic; }
.prov-mark {
color: #f0a23a; font-family: var(--font-mono); font-weight: 700;
font-size: 12px; margin-left: 2px;
}
/* fix qualifizierte (nicht vorläufige) Teams: voller Kontrast + linker Marker */
.side:not(.prov) .nm > span:not(.c):not(.prob):not(.prov-mark) { color: var(--ink); font-weight: 600; }
.side:not(.prov):not(.win) { box-shadow: inset 2px 0 0 var(--turf-deep); }
/* fix: echtes Team steht fest -> fett weiß + grüner Marker links */
.side.fix .nm .tn { color: #ffffff; font-weight: 700; }
.side.fix { box-shadow: inset 3px 0 0 var(--turf-deep); }
/* Sieger eines bereits gespielten Tie sticht zusätzlich grün hervor */
.side.win .nm .tn { color: var(--turf); font-weight: 700; }
.side.win { box-shadow: inset 3px 0 0 var(--turf); }
/* Legende-Marker */
.legend i.leg-fix { background: var(--turf-deep); }

View File

@@ -1,4 +1,5 @@
import { GroupId, Match, MatchStatus, Team } from "./types";
import { venueFor } from "./venues";
// ----------------------------------------------------------------------------
// Caching: einfacher In-Memory-Cache mit TTL. Verhindert, dass jede Browser-
@@ -80,6 +81,32 @@ function stageFor(stage: string, group: GroupId | null): Match["stage"] {
}
}
// Phasen-Reihenfolge für die K.o.-Nummerierung.
const STAGE_ORDER: Record<Match["stage"], number> = {
GROUP: 0, R32: 1, R16: 2, QF: 3, SF: 4, "3RD": 5, FINAL: 6,
};
// Setzt Spielnummern und Stadien.
// - K.o.-Spiele: chronologisch ab 73 (Anstöße dort eindeutig) -> für Bracket nötig.
// - Venue: Gruppenspiele über die Teampaarung, K.o.-Spiele über die Spielnummer.
function assignNumbersAndVenues(matches: Match[], teams: Team[]): void {
// K.o.-Spiele eindeutig durchnummerieren (73..104).
const ko = matches
.filter((m) => m.group == null)
.sort((a, b) => {
const sa = STAGE_ORDER[a.stage], sb = STAGE_ORDER[b.stage];
if (sa !== sb) return sa - sb;
const t = +new Date(a.utcDate) - +new Date(b.utcDate);
return t !== 0 ? t : Number(a.id) - Number(b.id);
});
ko.forEach((m, i) => { m.matchNumber = 73 + i; });
// Stadien setzen (Gruppenphase per Paarung, K.o. per Nummer).
for (const m of matches) {
m.venue = venueFor(m, teams);
}
}
// Holt alle Spiele + leitet die Teamliste daraus ab (spart einen Extra-Call).
export async function fetchMatchesAndTeams(): Promise<{ matches: Match[]; teams: Team[] }> {
return cached("fd:matches", 60_000, async () => {
@@ -110,7 +137,8 @@ export async function fetchMatchesAndTeams(): Promise<{ matches: Match[]; teams:
id: String(m.id),
group,
stage: stageFor(m.stage, group),
matchNumber: m.matchday ?? 0,
// Vorläufig 0 — die echte FIFA-Spielnummer wird unten gesetzt.
matchNumber: 0,
utcDate: m.utcDate,
status: mapStatus(m.status),
minute: m.minute ?? null,
@@ -118,12 +146,15 @@ export async function fetchMatchesAndTeams(): Promise<{ matches: Match[]; teams:
awayTeamId: m.awayTeam.id != null ? String(m.awayTeam.id) : null,
homeScore: m.score.fullTime.home,
awayScore: m.score.fullTime.away,
venue: m.venue ?? null,
venue: null, // wird unten aus der Map gesetzt
attendance: m.attendance ?? null,
};
});
return { matches, teams: [...teamMap.values()] };
const teams = [...teamMap.values()];
assignNumbersAndVenues(matches, teams);
return { matches, teams };
});
}

View File

@@ -3,9 +3,10 @@ import {
R32, LATER_ROUNDS, R32Match, BracketSlot,
ThirdAssignment, slotLabel,
} from "@/lib/bracket";
import { placeIsSecure } from "@/lib/secure-places";
// Eine Gruppe gilt als abgeschlossen, wenn alle ihre Gruppenspiele beendet sind
// (regulär 6 Spiele pro Vierergruppe). Erst dann sind Platzierungen fix.
// Eine Gruppe gilt als abgeschlossen, wenn alle ihre Gruppenspiele beendet sind.
// Wird für die Drittplatzierten-Sicherheit genutzt (gruppenübergreifend).
function groupFinished(group: GroupId, matches: Match[]): boolean {
const groupMatches = matches.filter((m) => m.group === group);
if (groupMatches.length === 0) return false;
@@ -61,25 +62,29 @@ function resolveR32Slot(
assignment: ThirdAssignment | null,
thirds: ThirdPlaceRow[],
matches: Match[],
teams: Team[],
annexResolved: boolean,
): { teamId: string | null; provisional: boolean } {
const table = (g: GroupId) => tables.find((t) => t.group === g);
if (slot.type === "W") {
const t = table(slot.group!);
const teamId = t?.rows.find((r) => r.rank === 1)?.teamId ?? null;
return { teamId, provisional: !groupFinished(slot.group!, matches) };
// Sieger fix, sobald Platz 1 rechnerisch gesichert ist (auch vor Gruppenende).
return { teamId, provisional: !placeIsSecure(slot.group!, 1, teams, matches) };
}
if (slot.type === "R") {
const t = table(slot.group!);
const teamId = t?.rows.find((r) => r.rank === 2)?.teamId ?? null;
return { teamId, provisional: !groupFinished(slot.group!, matches) };
// Zweiter fix, sobald Platz 2 rechnerisch gesichert ist.
return { teamId, provisional: !placeIsSecure(slot.group!, 2, teams, matches) };
}
// 3. Platz: braucht Annex-C-Zuordnung + den Gruppensieger dieses Spiels
if (slot.type === "3" && assignment && winnerGroup) {
const thirdGroup = assignment[winnerGroup];
if (thirdGroup) {
const row = thirds.find((r) => r.group === thirdGroup && r.qualifies);
// Fix nur, wenn Annex C aufgelöst UND die Quellgruppe abgeschlossen ist.
// Fix nur, wenn Annex C aufgelöst UND die Quellgruppe abgeschlossen ist
// (Drittplatzierten-Qualifikation ist gruppenübergreifend, bis zuletzt offen).
const fix = annexResolved && groupFinished(thirdGroup, matches);
return { teamId: row?.teamId ?? null, provisional: !fix };
}
@@ -126,8 +131,8 @@ export function resolveBracket(
// Für 3.-Platz-Slots: Gruppensieger ist die andere Seite (immer W)
const winnerGroup = (homeGroup ?? awayGroup) as GroupId | undefined;
const h = resolveR32Slot(rm.home, winnerGroup, tables, assignment, thirds, matches, annexResolved);
const a = resolveR32Slot(rm.away, winnerGroup, tables, assignment, thirds, matches, annexResolved);
const h = resolveR32Slot(rm.home, winnerGroup, tables, assignment, thirds, matches, teams, annexResolved);
const a = resolveR32Slot(rm.away, winnerGroup, tables, assignment, thirds, matches, teams, annexResolved);
const home = sideFrom(h.teamId, slotLabel(rm.home, assignment, winnerGroup), teams, feed, "home", h.provisional);
const away = sideFrom(a.teamId, slotLabel(rm.away, assignment, winnerGroup), teams, feed, "away", a.provisional);

94
lib/secure-places.ts Normal file
View File

@@ -0,0 +1,94 @@
import { GroupId, Match, Team } from "./types";
import { computeGroupTables } from "./standings";
// Bestimmt, welche Tabellenplätze einer Gruppe bereits MATHEMATISCH feststehen
// auch wenn noch Spiele ausstehen. Berücksichtigt ALLE FIFA-Tiebreaker, weil die
// Tabelle über computeGroupTables() berechnet wird (Punkte, Direktvergleich,
// Tordifferenz, Tore).
//
// Methode: vollständige Worst-Case-Enumeration der Restspiele. Ein Platz p ist
// für ein Team sicher, wenn es in JEDEM möglichen Ausgang aller Restspiele auf
// Platz p oder besser bleibt. Wir enumerieren pro Restspiel mehrere
// repräsentative Ergebnisse, die alle relevanten Tiebreaker-Effekte abdecken:
// - Heimsieg knapp (1:0) und hoch (5:0)
// - Auswärtssieg knapp (0:1) und hoch (0:5)
// - Unentschieden (0:0 und 2:2)
// Diese Menge deckt Punkt- UND Tordifferenz-Szenarien ausreichend ab, um echte
// Sicherheit korrekt zu erkennen (inkl. Fälle wie "Direktvergleich bereits
// gewonnen -> uneinholbar").
// Mögliche Ergebnis-Varianten je Restspiel (homeGoals, awayGoals).
const OUTCOME_VARIANTS: Array<[number, number]> = [
[1, 0], [5, 0], // Heimsieg knapp / hoch
[0, 1], [0, 5], // Auswärtssieg knapp / hoch
[0, 0], [2, 2], // Unentschieden
];
function openMatches(group: GroupId, matches: Match[]): Match[] {
return matches.filter(
(m) => m.group === group && m.status !== "FINISHED"
&& m.homeTeamId != null && m.awayTeamId != null,
);
}
// Liefert für eine Gruppe Map: Platz(1-basiert) -> teamId, aber nur für Plätze,
// die in ALLEN Szenarien stabil von demselben Team gehalten werden.
export function securePlaces(
group: GroupId, teams: Team[], matches: Match[],
): Map<number, string> {
const open = openMatches(group, matches);
// Begrenzung: bei sehr vielen offenen Spielen wird die Enumeration groß.
// In 4er-Gruppen sind es maximal 6 offene Spiele (Turnierstart) -> 6^? zu viel.
// Wir enumerieren nur, wenn die Kombinationszahl handhabbar ist; sonst gilt
// konservativ "nichts sicher" (am Turnierstart ohnehin korrekt).
const combos = Math.pow(OUTCOME_VARIANTS.length, open.length);
if (open.length === 0) {
// Alles gespielt: aktuelle Tabelle ist final.
const table = computeGroupTables(teams, matches).find((t) => t.group === group);
const res = new Map<number, string>();
table?.rows.forEach((r) => res.set(r.rank, r.teamId));
return res;
}
if (combos > 100_000) {
return new Map(); // zu früh im Turnier -> nichts gesichert
}
// Für jeden Platz das Set der Teams sammeln, die diesen Platz über ALLE
// Szenarien einnehmen können. Ist das Set einelementig, ist der Platz sicher.
const placeTeams: Array<Set<string>> = [new Set(), new Set(), new Set(), new Set()];
const total = combos;
for (let combo = 0; combo < total; combo++) {
// Szenario zusammenbauen: jedes offene Spiel bekommt eine Variante.
let c = combo;
const simulated: Match[] = open.map((m) => {
const variantIdx = c % OUTCOME_VARIANTS.length;
c = Math.floor(c / OUTCOME_VARIANTS.length);
const [hg, ag] = OUTCOME_VARIANTS[variantIdx];
return { ...m, status: "FINISHED", homeScore: hg, awayScore: ag };
});
// Gespielte + simulierte Spiele kombinieren.
const played = matches.filter((m) => !(m.group === group && m.status !== "FINISHED"));
const all = [...played, ...simulated];
const table = computeGroupTables(teams, all).find((t) => t.group === group);
if (!table) continue;
table.rows.forEach((r) => {
placeTeams[r.rank - 1]?.add(r.teamId);
});
}
const result = new Map<number, string>();
for (let i = 0; i < 4; i++) {
if (placeTeams[i].size === 1) {
result.set(i + 1, [...placeTeams[i]][0]);
}
}
return result;
}
export function placeIsSecure(
group: GroupId, place: number, teams: Team[], matches: Match[],
): boolean {
return securePlaces(group, teams, matches).has(place);
}

View File

@@ -11,9 +11,13 @@ function emptyRow(teamId: string): StandingRow {
};
}
// Trägt ein abgeschlossenes Spiel in zwei Tabellenzeilen ein.
function applyMatch(rows: Map<string, StandingRow>, m: Match) {
if (m.status !== "FINISHED") return;
// Trägt ein Spiel in zwei Tabellenzeilen ein.
// Standard: nur abgeschlossene Spiele (FINISHED). Mit includeLive=true werden
// auch laufende Spiele (LIVE/IN_PLAY/PAUSED) mit ihrem Zwischenstand gezählt.
function applyMatch(rows: Map<string, StandingRow>, m: Match, includeLive = false) {
const live = m.status === "LIVE" || m.status === "IN_PLAY" || m.status === "PAUSED";
const counts = m.status === "FINISHED" || (includeLive && live);
if (!counts) return;
if (m.homeTeamId == null || m.awayTeamId == null) return;
if (m.homeScore == null || m.awayScore == null) return;
const h = rows.get(m.homeTeamId);
@@ -75,14 +79,19 @@ function miniTable(matches: Match[], tiedIds: Set<string>): Map<string, Standing
}
// Berechnet alle 12 Gruppentabellen aus Teams + Spielen.
export function computeGroupTables(teams: Team[], matches: Match[]): GroupTable[] {
// includeLive=false (Standard): nur abgeschlossene Spiele (offizielle Tabelle,
// Basis für die fix-Berechnung). includeLive=true: laufende Spiele werden mit
// Zwischenstand eingerechnet (Live-Tabelle).
export function computeGroupTables(
teams: Team[], matches: Match[], includeLive = false,
): GroupTable[] {
const tables: GroupTable[] = [];
for (const g of GROUP_IDS) {
const groupTeams = teams.filter((t) => t.group === g);
const rows = new Map<string, StandingRow>();
groupTeams.forEach((t) => rows.set(t.id, emptyRow(t.id)));
const groupMatches = matches.filter((m) => m.group === g);
for (const m of groupMatches) applyMatch(rows, m);
for (const m of groupMatches) applyMatch(rows, m, includeLive);
rows.forEach(finalizeRow);
const arr = [...rows.values()];

207
lib/venues.ts Normal file
View File

@@ -0,0 +1,207 @@
// Stadion-Zuordnung — die alleinige Quelle für Spielorte (Feed-venue wird ignoriert).
//
// Gruppenphase: über die Teampaarung (Ländercodes). Eindeutig, da jede Paarung
// im Turnier genau einmal vorkommt — unabhängig von Heim/Auswärts-Reihenfolge
// und von gleichzeitigen Anstößen.
// K.o.-Phase: über die FIFA-Spielnummer (dort sind die Anstöße eindeutig).
import { GroupId, Match, Team } from "./types";
// --- GRUPPENPHASE: "CODE1-CODE2" -> Stadion ---
export const FIXTURES_GROUP_STAGE: Record<string, string> = {
// Gruppe A
"MEX-RSA": "Estadio Azteca, Mexiko-Stadt",
"KOR-CZE": "Estadio Akron, Guadalajara",
"CZE-RSA": "Mercedes-Benz Stadium, Atlanta",
"MEX-KOR": "Estadio Akron, Guadalajara",
"CZE-MEX": "Estadio Azteca, Mexiko-Stadt",
"RSA-KOR": "Estadio BBVA, Monterrey",
// Gruppe B
"CAN-BIH": "BMO Field, Toronto",
"QAT-SUI": "Levi's Stadium, San Francisco Bay Area",
"SUI-BIH": "SoFi Stadium, Los Angeles",
"CAN-QAT": "BC Place, Vancouver",
"SUI-CAN": "BC Place, Vancouver",
"BIH-QAT": "Lumen Field, Seattle",
// Gruppe C
"BRA-MAR": "Gillette Stadium, Boston",
"HAI-SCO": "MetLife Stadium, New York/New Jersey",
"BRA-HAI": "Lincoln Financial Field, Philadelphia",
"SCO-MAR": "Gillette Stadium, Boston",
"SCO-BRA": "Hard Rock Stadium, Miami",
"MAR-HAI": "Mercedes-Benz Stadium, Atlanta",
// Gruppe D
"USA-PAR": "SoFi Stadium, Los Angeles",
"AUS-TUR": "BC Place, Vancouver",
"TUR-PAR": "Levi's Stadium, San Francisco Bay Area",
"USA-AUS": "Lumen Field, Seattle",
"TUR-USA": "SoFi Stadium, Los Angeles",
"PAR-AUS": "Levi's Stadium, San Francisco Bay Area",
// Gruppe E
"CIV-ECU": "Lincoln Financial Field, Philadelphia",
"GER-CUR": "NRG Stadium, Houston",
"GER-CIV": "BMO Field, Toronto",
"ECU-CUR": "Arrowhead Stadium, Kansas City",
"CUR-CIV": "Lincoln Financial Field, Philadelphia",
"ECU-GER": "MetLife Stadium, New York/New Jersey",
// Gruppe F
"NED-JPN": "AT&T Stadium, Dallas",
"SWE-TUN": "Estadio BBVA, Monterrey",
"NED-SWE": "NRG Stadium, Houston",
"TUN-JPN": "Estadio BBVA, Monterrey",
"JPN-SWE": "AT&T Stadium, Dallas",
"TUN-NED": "Arrowhead Stadium, Kansas City",
// Gruppe G
"IRN-NZL": "SoFi Stadium, Los Angeles",
"BEL-EGY": "Lumen Field, Seattle",
"BEL-IRN": "SoFi Stadium, Los Angeles",
"NZL-EGY": "BC Place, Vancouver",
"NZL-BEL": "Lumen Field, Seattle",
"EGY-IRN": "BC Place, Vancouver",
// Gruppe H
"KSA-URU": "Hard Rock Stadium, Miami",
"ESP-CPV": "Mercedes-Benz Stadium, Atlanta",
"URU-CPV": "Mercedes-Benz Stadium, Atlanta",
"ESP-KSA": "Hard Rock Stadium, Miami",
"URU-ESP": "Estadio Akron, Guadalajara",
"CPV-KSA": "NRG Stadium, Houston",
// Gruppe I
"FRA-SEN": "MetLife Stadium, New York/New Jersey",
"IRQ-NOR": "Gillette Stadium, Boston",
"NOR-SEN": "Lincoln Financial Field, Philadelphia",
"FRA-IRQ": "MetLife Stadium, New York/New Jersey",
"NOR-FRA": "Gillette Stadium, Boston",
"SEN-IRQ": "BMO Field, Toronto",
// Gruppe J
"ARG-ALG": "Arrowhead Stadium, Kansas City",
"AUT-JOR": "Levi's Stadium, San Francisco Bay Area",
"ARG-AUT": "AT&T Stadium, Dallas",
"JOR-ALG": "Levi's Stadium, San Francisco Bay Area",
"JOR-ARG": "Arrowhead Stadium, Kansas City",
"ALG-AUT": "NRG Stadium, Houston",
// Gruppe K
"UZB-COL": "Estadio Azteca, Mexiko-Stadt",
"POR-COD": "NRG Stadium, Houston",
"POR-UZB": "NRG Stadium, Houston",
"COL-COD": "Estadio Akron, Guadalajara",
"COL-POR": "Hard Rock Stadium, Miami",
"COD-UZB": "Estadio BBVA, Monterrey",
// Gruppe L
"GHA-PAN": "BMO Field, Toronto",
"ENG-CRO": "AT&T Stadium, Dallas",
"ENG-GHA": "Gillette Stadium, Boston",
"PAN-CRO": "BMO Field, Toronto",
"PAN-ENG": "MetLife Stadium, New York/New Jersey",
"CRO-GHA": "Arrowhead Stadium, Kansas City",
};
// Reihenfolge-unabhängiger Lookup: baut beide Schlüsselrichtungen.
const PAIR_VENUE = new Map<string, string>();
for (const [key, venue] of Object.entries(FIXTURES_GROUP_STAGE)) {
const [a, b] = key.split("-");
PAIR_VENUE.set(`${a}-${b}`, venue);
PAIR_VENUE.set(`${b}-${a}`, venue);
}
// --- K.O.-PHASE: FIFA-Spielnummer -> Stadion ---
export const VENUE_BY_KO_MATCH: Record<number, string> = {
// Sechzehntelfinale (R32)
73: "SoFi Stadium, Los Angeles",
74: "Gillette Stadium, Boston",
75: "Estadio Azteca, Mexiko-Stadt",
76: "Hard Rock Stadium, Miami",
77: "Mercedes-Benz Stadium, Atlanta",
78: "AT&T Stadium, Dallas",
79: "Levi's Stadium, San Francisco Bay Area",
80: "Lumen Field, Seattle",
81: "MetLife Stadium, New York/New Jersey",
82: "Lincoln Financial Field, Philadelphia",
83: "BMO Field, Toronto",
84: "NRG Stadium, Houston",
85: "BC Place, Vancouver",
86: "Estadio BBVA, Monterrey",
87: "Arrowhead Stadium, Kansas City",
88: "AT&T Stadium, Dallas",
// Achtelfinale (R16)
89: "MetLife Stadium, New York/New Jersey",
90: "Hard Rock Stadium, Miami",
91: "NRG Stadium, Houston",
92: "Mercedes-Benz Stadium, Atlanta",
93: "AT&T Stadium, Dallas",
94: "Lumen Field, Seattle",
95: "BC Place, Vancouver",
96: "Estadio Azteca, Mexiko-Stadt",
// Viertelfinale
97: "Gillette Stadium, Boston",
98: "SoFi Stadium, Los Angeles",
99: "Hard Rock Stadium, Miami",
100: "Arrowhead Stadium, Kansas City",
// Halbfinale
101: "AT&T Stadium, Dallas",
102: "Mercedes-Benz Stadium, Atlanta",
// Spiel um Platz 3
103: "Hard Rock Stadium, Miami",
// Finale
104: "MetLife Stadium, New York/New Jersey",
};
// Manche Feeds nutzen abweichende 3-Buchstaben-Codes als die Map oben.
// Diese Tabelle übersetzt bekannte Feed-Codes auf den Map-Code.
// (Beispiel: FIFA/ISO nutzt CUW für Curaçao, die Map verwendet CUR.)
const CODE_ALIAS: Record<string, string> = {
CUW: "CUR", // Curaçao
CRC: "CRC", // (Platzhalter, falls weitere auftauchen)
};
// Fallback über den Teamnamen, falls ein Code unbekannt/abweichend ist.
// Schlüssel: normalisierter Name -> Map-Code.
const NAME_TO_CODE: Record<string, string> = {
"curacao": "CUR", "curaçao": "CUR",
"uruguay": "URU",
"cape verde": "CPV", "cape verde islands": "CPV", "cabo verde": "CPV",
"saudi arabia": "KSA",
"ivory coast": "CIV", "côte d'ivoire": "CIV", "cote d'ivoire": "CIV",
"south korea": "KOR", "korea republic": "KOR",
"south africa": "RSA",
"czechia": "CZE", "czech republic": "CZE",
"bosnia and herzegovina": "BIH", "bosnia-herzegovina": "BIH",
"dr congo": "COD", "congo dr": "COD", "democratic republic of the congo": "COD",
};
// Normalisiert den Code eines Teams auf den in der Map verwendeten Code.
function canonicalCode(team: Team | undefined): string | null {
if (!team) return null;
if (team.code) {
const c = team.code.toUpperCase();
if (CODE_ALIAS[c]) return CODE_ALIAS[c];
// Wenn der Code direkt in der Map vorkommt, nimm ihn.
return c;
}
// kein Code -> über den Namen versuchen
const n = team.name?.toLowerCase().trim();
return n ? (NAME_TO_CODE[n] ?? null) : null;
}
// Liefert das Stadion eines Spiels.
// Gruppenspiel -> über Teampaarung (Codes, mit Alias/Namen-Fallback),
// K.o.-Spiel -> über Spielnummer.
export function venueFor(m: Match, teams: Team[]): string | null {
if (m.group != null) {
const home = teams.find((t) => t.id === m.homeTeamId);
const away = teams.find((t) => t.id === m.awayTeamId);
let hc = canonicalCode(home);
let ac = canonicalCode(away);
// Erstversuch mit Codes
let venue = hc && ac ? PAIR_VENUE.get(`${hc}-${ac}`) : undefined;
// Falls kein Treffer: über die Namen normalisieren und erneut probieren.
if (!venue) {
const hn = home?.name?.toLowerCase().trim();
const an = away?.name?.toLowerCase().trim();
hc = (hn && NAME_TO_CODE[hn]) || hc;
ac = (an && NAME_TO_CODE[an]) || ac;
venue = hc && ac ? PAIR_VENUE.get(`${hc}-${ac}`) : undefined;
}
return venue ?? null;
}
return VENUE_BY_KO_MATCH[m.matchNumber] ?? null;
}