22 Commits

Author SHA1 Message Date
6e73cccdff staion 2026-06-28 13:43:40 -05:00
a60cf9c604 KO round 2026-06-28 11:56:33 -05:00
fafb9dce4b third place 2026-06-27 23:42:27 -05:00
4896fe7159 other dates 2026-06-27 16:58:28 -05:00
1a99bd8029 bessere Farbe 2026-06-27 16:32:47 -05:00
e9701ce25b KO: Stadion + Anstoss 2026-06-27 16:22:43 -05:00
4d838e2fb7 fix date/time 2026-06-27 15:58:18 -05:00
7bad12df68 stadien 2026-06-27 15:48:48 -05:00
89a9075391 rm logs + caching 2026-06-27 14:17:16 -05:00
2b3cadfcb5 third place fix und polymarket 2026-06-27 14:03:11 -05:00
a721de5b23 third place marks 2026-06-27 12:15:34 -05:00
bf931e70c0 third place fix 2026-06-27 07:58:38 -05:00
6bb6f9be7a fixes 2026-06-26 18:34:58 -05:00
6f0acaad4c new Live Scores 2026-06-26 14:25:22 -05:00
1985289a37 third place corrected 2026-06-26 13:25:39 -05:00
a38b3fa517 revert 2026-06-25 14:54:45 -05:00
49256e83c6 rm remote fonts 2026-06-25 14:50:41 -05:00
6eec396b8c env variables 2026-06-25 14:18:25 -05:00
1cd4ae3bfb unami 2026-06-25 12:00:36 -05:00
597d321a34 wrap 2026-06-24 23:06:56 -05:00
c9bdc0c5cf third place 2026-06-24 23:02:46 -05:00
a4a47b431a mobile 2026-06-24 22:55:05 -05:00
16 changed files with 1151 additions and 333 deletions

View File

@@ -5,3 +5,7 @@ FOOTBALL_DATA_TOKEN=dein_token_hier
# Polymarket-Slug des WM-Events (Standard: world-cup-2026).
# Den genauen Slug findest du in der Polymarket-URL nach /event/.
POLYMARKET_WC_SLUG=world-cup-2026
# Umami Analytics (selbst gehostet, cookiefrei)
# NEXT_PUBLIC_UMAMI_SRC=https://analytics.example.com/script.js
# NEXT_PUBLIC_UMAMI_ID=deine-website-id

View File

@@ -10,6 +10,12 @@ WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
ENV NEXT_TELEMETRY_DISABLED=1
ARG NEXT_PUBLIC_UMAMI_SRC
ARG NEXT_PUBLIC_UMAMI_ID
ENV NEXT_PUBLIC_UMAMI_SRC=${NEXT_PUBLIC_UMAMI_SRC}
ENV NEXT_PUBLIC_UMAMI_ID=${NEXT_PUBLIC_UMAMI_ID}
RUN npm run build
# --- Stufe 3: Runtime (standalone) ---

View File

@@ -1,7 +1,8 @@
import { NextResponse } from "next/server";
import { fetchMatchesAndTeams, fetchOdds, attachOdds } from "@/lib/feeds";
import { fetchMatchesAndTeams, fetchOdds, attachOdds, attachKOOdds, fetchLiveScores, applyLiveScores, assignKONumbersBySlots, fetchKOLiveData, attachKOLiveData } from "@/lib/feeds";
import { computeGroupTables, computeThirdPlaceTable } from "@/lib/standings";
import { qualifiedThirdGroups, resolveAnnexC } from "@/lib/bracket";
import { securelyQualifiedThirdTeams } from "@/lib/third-place-security";
// Diese Route wird vom Frontend gepollt. Sie ist der einzige Ort, der die
// Upstream-Feeds berührt — gecacht, damit Rate Limits eingehalten werden.
@@ -13,23 +14,48 @@ export async function GET() {
// Odds sind optional: fällt der Polymarket-Call aus, liefern wir trotzdem.
let matches = rawMatches;
let odds: Awaited<ReturnType<typeof fetchOdds>> | null = null;
try {
const odds = await fetchOdds();
odds = await fetchOdds();
matches = attachOdds(rawMatches, teams, odds);
} catch (err) {
console.error("[polymarket] fetchOdds fehlgeschlagen:", err);
}
// Live-Scores von worldcup26.ir (additiv, Fallback auf football-data)
try {
const liveScores = await fetchLiveScores();
matches = applyLiveScores(matches, teams, liveScores);
} catch (err) {
console.warn("[worldcup26] fetchLiveScores fehlgeschlagen:", err instanceof Error ? err.message : err);
}
const groupTables = computeGroupTables(teams, matches);
const groupTablesLive = computeGroupTables(teams, matches, true);
// prob-Feld normalisieren: immer null statt undefined, damit JSON konsistent ist
assignKONumbersBySlots(matches, teams);
if (odds) {
matches = attachKOOdds(matches, teams, odds);
}
// KO-Live-Daten (Tore, Minute) von worldcup26
try {
const koGames = await fetchKOLiveData();
matches = attachKOLiveData(matches, teams, koGames);
} catch (err) {
console.warn("[worldcup26] KO-Live-Daten fehlgeschlagen:", err instanceof Error ? err.message : err);
}
const normalizedMatches = matches.map((m) => ({ ...m, prob: m.prob ?? null }));
const thirdTable = computeThirdPlaceTable(groupTablesLive);
const qGroups = qualifiedThirdGroups(thirdTable);
const annex = qGroups.length === 8 ? resolveAnnexC(qGroups) : null;
// Sichere Drittplatzierte (Team-IDs, deren Top-8-Platz mathematisch feststeht)
const secureThirdTeams = securelyQualifiedThirdTeams(matches, teams);
return NextResponse.json({
updatedAt: new Date().toISOString(),
teams,
@@ -37,6 +63,7 @@ export async function GET() {
groupTables,
groupTablesLive,
thirdTable,
secureThirdTeams: [...secureThirdTeams],
annexAssignment: annex,
annexResolved: annex != null,
});

View File

@@ -1,9 +1,10 @@
"use client";
import { useState, useCallback } from "react";
import { useMemo, useState, useCallback } from "react";
import { GroupTable, Match, Team, ThirdPlaceRow } from "@/lib/types";
import { ThirdAssignment, orderedRound } from "@/lib/bracket";
import { resolveBracket, ResolvedSide, ResolvedTie } from "@/lib/resolve-bracket";
import { STADIUMS, MATCH_STADIUMS, MATCH_DATES } from "@/lib/stadiums";
import Flag from "./Flag";
interface TipState { x: number; y: number; text: string }
@@ -47,16 +48,31 @@ function Side({
);
}
function fmtMatchInfo(utcDate?: string, stadiumId?: string): string {
if (!utcDate) return "";
const d = new Date(utcDate);
const dateStr = d.toLocaleDateString("de-DE", { day: "numeric", month: "numeric" });
const timeStr = d.toLocaleTimeString("de-DE", { hour: "2-digit", minute: "2-digit" });
const city = stadiumId ? STADIUMS[stadiumId]?.city : "";
const parts = [`${dateStr}`, `${timeStr}`];
if (city) parts.push(city);
return parts.join(" ");
}
function Tie({
tie, teams, isFinal, onShowTip, onHideTip,
tie, teams, isFinal, matchInfo, onShowTip, onHideTip,
}: {
tie: ResolvedTie; teams: Team[]; isFinal?: boolean;
matchInfo?: string;
onShowTip: (text: string, x: number, y: number) => void;
onHideTip: () => void;
}) {
return (
<div className={`tie ${isFinal ? "final-tie" : ""}`}>
<div className="tie-head">Spiel {tie.matchNumber}</div>
<div className="match-badge">{tie.matchNumber}</div>
<div className="tie-meta">
{matchInfo || `Spiel ${tie.matchNumber}`}
</div>
<Side s={tie.home} prob={tie.prob?.home} teams={teams} onShowTip={onShowTip} onHideTip={onHideTip} />
<Side s={tie.away} prob={tie.prob?.away} teams={teams} onShowTip={onShowTip} onHideTip={onHideTip} />
</div>
@@ -77,6 +93,18 @@ export default function Bracket({
const r32ByNum = new Map(r32Array.map((t) => [t.matchNumber, t]));
// Slot-Nummer → formatierte Anzeige (Datum/Uhrzeit aus MATCH_DATES, Stadt aus MATCH_STADIUMS)
const matchMeta = useMemo(() => {
const meta = new Map<number, string>();
for (let n = 73; n <= 104; n++) {
const utcDate = MATCH_DATES[n];
const stadiumId = MATCH_STADIUMS[n];
const info = fmtMatchInfo(utcDate, stadiumId);
if (info) meta.set(n, info);
}
return meta;
}, []);
const sfOrder = orderedRound([104]);
const qfOrder = orderedRound(sfOrder);
const r16Order = orderedRound(qfOrder);
@@ -109,35 +137,35 @@ export default function Bracket({
<div className="round">
<div className="round-label">Letzte 32</div>
<div className="round-matches">
{r32.map((t) => <Tie key={t.matchNumber} tie={t} teams={teams} onShowTip={showTip} onHideTip={hideTip} />)}
{r32.map((t) => <Tie key={t.matchNumber} tie={t} teams={teams} matchInfo={matchMeta.get(t.matchNumber)} onShowTip={showTip} onHideTip={hideTip} />)}
</div>
</div>
<div className="round">
<div className="round-label">Achtelfinale</div>
<div className="round-matches">
{r16.map((t) => <Tie key={t.matchNumber} tie={t} teams={teams} onShowTip={showTip} onHideTip={hideTip} />)}
{r16.map((t) => <Tie key={t.matchNumber} tie={t} teams={teams} matchInfo={matchMeta.get(t.matchNumber)} onShowTip={showTip} onHideTip={hideTip} />)}
</div>
</div>
<div className="round">
<div className="round-label">Viertelfinale</div>
<div className="round-matches">
{qf.map((t) => <Tie key={t.matchNumber} tie={t} teams={teams} onShowTip={showTip} onHideTip={hideTip} />)}
{qf.map((t) => <Tie key={t.matchNumber} tie={t} teams={teams} matchInfo={matchMeta.get(t.matchNumber)} onShowTip={showTip} onHideTip={hideTip} />)}
</div>
</div>
<div className="round">
<div className="round-label">Halbfinale</div>
<div className="round-matches">
{sf.map((t) => <Tie key={t.matchNumber} tie={t} teams={teams} onShowTip={showTip} onHideTip={hideTip} />)}
{sf.map((t) => <Tie key={t.matchNumber} tie={t} teams={teams} matchInfo={matchMeta.get(t.matchNumber)} onShowTip={showTip} onHideTip={hideTip} />)}
</div>
</div>
<div className="round">
<div className="round-label">Finale</div>
<div className="round-matches">
{fin && <Tie tie={fin} teams={teams} isFinal onShowTip={showTip} onHideTip={hideTip} />}
{fin && <Tie tie={fin} teams={teams} isFinal matchInfo={matchMeta.get(fin.matchNumber)} onShowTip={showTip} onHideTip={hideTip} />}
{third && (
<div style={{ marginTop: 20 }}>
<div className="round-label" style={{ marginBottom: 8 }}>Spiel um Platz 3</div>
<Tie tie={third} teams={teams} onShowTip={showTip} onHideTip={hideTip} />
<Tie tie={third} teams={teams} matchInfo={matchMeta.get(third.matchNumber)} onShowTip={showTip} onHideTip={hideTip} />
</div>
)}
</div>

View File

@@ -0,0 +1,207 @@
"use client";
import { useMemo, useState, useEffect } from "react";
import { Match, Team } from "@/lib/types";
import { STADIUMS, MATCH_STADIUMS } from "@/lib/stadiums";
import Flag from "./Flag";
function fmtShortDate(iso: string): string {
const d = new Date(iso);
return d.toLocaleDateString("de-DE", { weekday: "short", day: "2-digit", month: "2-digit" });
}
function fmtTime(iso: string): string {
const d = new Date(iso);
return d.toLocaleTimeString("de-DE", { hour: "2-digit", minute: "2-digit" });
}
function scoreDisplay(m: Match): string {
if (m.status === "SCHEDULED" || (m.homeScore == null && m.awayScore == null)) return " : ";
return `${m.homeScore ?? 0} : ${m.awayScore ?? 0}`;
}
function statusLabel(m: Match): string {
switch (m.status) {
case "LIVE": case "IN_PLAY": return m.minute != null ? `${m.minute}'` : "Live";
case "PAUSED": return "Halbzeit";
case "FINISHED": return "Beendet";
default: return fmtTime(m.utcDate);
}
}
function isLive(m: Match): boolean {
return m.status === "LIVE" || m.status === "IN_PLAY" || m.status === "PAUSED";
}
export default function KoFixtures({ teams, matches }: { teams: Team[]; matches: Match[] }) {
const [mounted, setMounted] = useState(false);
useEffect(() => { setMounted(true); }, []);
const koMatches = useMemo(() => {
return matches
.filter((m) =>
m.group == null &&
m.homeTeamId != null && m.awayTeamId != null &&
// Nur Spiele mit bekannten Teams (keine TBD)
teams.some(t => t.id === m.homeTeamId) &&
teams.some(t => t.id === m.awayTeamId),
)
.sort((a, b) => {
// Live zuerst
const aLive = isLive(a) ? 1 : 0;
const bLive = isLive(b) ? 1 : 0;
if (aLive !== bLive) return bLive - aLive;
// Innerhalb Live/Upcoming/Finished: Datum aufsteigend
return +new Date(a.utcDate) - +new Date(b.utcDate);
});
}, [matches, teams]);
// Lokale Datums-Extraktion (vermeidet UTC-Tagesverschiebung bei US-Spielen)
function localDateKey(iso: string): string {
const d = new Date(iso);
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, "0");
const day = String(d.getDate()).padStart(2, "0");
return `${y}-${m}-${day}`;
}
// Nach Datum gruppieren (lokale Zeitzone nach Hydration, sonst UTC)
const groups = useMemo(() => {
const map = new Map<string, Match[]>();
for (const m of koMatches) {
const key = mounted ? localDateKey(m.utcDate) : m.utcDate.slice(0, 10);
if (!map.has(key)) map.set(key, []);
map.get(key)!.push(m);
}
return [...map.entries()];
}, [koMatches, mounted]);
if (koMatches.length === 0) {
return <div className="notice">Keine K.o.-Spiele mit bekannten Teams verfügbar.</div>;
}
return (
<div>
{groups.map(([date, groupMatches]) => (
<div key={date} style={{ marginBottom: 24 }}>
<h3 style={{
fontFamily: "var(--font-display)", fontSize: 13,
textTransform: "uppercase", letterSpacing: "0.06em",
color: "var(--ink-dim)", margin: "0 0 10px",
}}>
{fmtShortDate(groupMatches[0].utcDate)}
</h3>
<div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
{groupMatches.map((m) => {
const home = m.homeTeamId ? teams.find(t => t.id === m.homeTeamId) : undefined;
const away = m.awayTeamId ? teams.find(t => t.id === m.awayTeamId) : undefined;
const live = isLive(m);
const stageMap: Record<string, string> = {
R32: "R32", R16: "Achtelfinale", QF: "Viertelfinale",
SF: "Halbfinale", "3RD": "Platz 3", FINAL: "Finale",
};
const city = STADIUMS[MATCH_STADIUMS[m.matchNumber]]?.city;
return (
<div
key={m.id}
style={{
background: "var(--bg-card)", border: `1px solid ${live ? "var(--turf)" : "var(--line-soft)"}`,
borderRadius: "var(--radius-sm)", padding: "12px 14px",
}}
>
{/* Kopfzeile */}
<div style={{
display: "flex", justifyContent: "space-between", alignItems: "center",
marginBottom: 8, fontSize: 11,
fontFamily: "var(--font-mono)", color: "var(--ink-faint)",
}}>
<span>
{stageMap[m.stage] ?? m.stage} · Spiel {m.matchNumber || "—"}
{city ? ` · ${city}` : ""}
</span>
<span style={{ color: live ? "var(--turf)" : undefined, fontWeight: live ? 700 : undefined }}>
{statusLabel(m)}
</span>
</div>
{/* Teams + Score */}
<div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
<TeamLabel team={home} />
<span style={{
fontFamily: "var(--font-mono)", fontSize: 22, fontWeight: 700,
color: live ? "var(--turf)" : "var(--ink)",
padding: "0 16px",
}}>
{scoreDisplay(m)}
</span>
<TeamLabel team={away} reverse />
</div>
{/* Torabfolge */}
{m.goals && m.goals.length > 0 && (
<div style={{
marginTop: 8, padding: "8px 10px",
background: "var(--bg-raised)", borderRadius: "var(--radius-sm)",
fontSize: 12, fontFamily: "var(--font-mono)",
}}>
<div style={{ color: "var(--ink-faint)", fontSize: 10, marginBottom: 4 }}>
Tore
</div>
<div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
{m.goals.map((g, i) => (
<span key={i} style={{
display: "inline-flex", alignItems: "center", gap: 3,
color: g.team === "home" ? "var(--ink)" : "var(--ink)",
}}>
{g.team === "home" ? "⬆" : "⬇"}
<span style={{ color: "var(--turf)", fontWeight: 700 }}>
{g.scorer}
</span>
<span style={{ color: "var(--ink-faint)", fontSize: 10 }}>
{g.minute}&apos;
</span>
</span>
))}
</div>
</div>
)}
{/* Prob (falls vorhanden) */}
{m.prob && m.prob.home > 0 && (
<div style={{
marginTop: 6, fontSize: 10, color: "var(--ink-faint)",
fontFamily: "var(--font-mono)",
}}>
Polymarket: {Math.round(m.prob.home * 100)}% / {Math.round(m.prob.draw * 100)}% / {Math.round(m.prob.away * 100)}%
</div>
)}
</div>
);
})}
</div>
</div>
))}
</div>
);
}
function TeamLabel({ team, reverse }: { team?: Team; reverse?: boolean }) {
return (
<div style={{
display: "flex", alignItems: "center", gap: 8,
flexDirection: reverse ? "row-reverse" : "row",
flex: 1, minWidth: 0,
}}>
<Flag team={team} size={20} />
<span style={{
fontWeight: 600, fontSize: 14,
whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
maxWidth: 120,
}}>
{team?.localisedName ?? team?.name ?? "—"}
</span>
</div>
);
}

View File

@@ -1,73 +1,16 @@
"use client";
import { useState, useMemo, useCallback, useEffect } from "react";
import { useMemo } from "react";
import { Match, Team } from "@/lib/types";
import { computeGroupTables, computeThirdPlaceTable } from "@/lib/standings";
import { qualifiedThirdGroups, resolveAnnexC, LATER_ROUNDS } from "@/lib/bracket";
import { resolveBracket, ResolvedTie } from "@/lib/resolve-bracket";
import {
loadOverrides, saveOverrides, buildSimMatches,
defaultScore, SimOverrides,
} from "@/lib/simulation";
import { buildSimMatches } from "@/lib/simulation";
import Bracket from "./Bracket";
import ThirdPlace from "./ThirdPlace";
import Flag from "./Flag";
function teamById(teams: Team[], id: string | null) {
return id ? teams.find((t) => t.id === id) : undefined;
}
function fmtDate(iso: string): string {
const d = new Date(iso);
return d.toLocaleString("de-DE", {
weekday: "short", day: "2-digit", month: "2-digit",
hour: "2-digit", minute: "2-digit",
});
}
// Label für die Spielphase in der Liste
function phaseLabel(match: Match): string {
if (match.stage === "GROUP" && match.group) return `Gruppe ${match.group}`;
if (match.stage === "R32") return "Sechzehntelfinale";
if (match.stage === "R16") return "Achtelfinale";
if (match.stage === "QF") return "Viertelfinale";
if (match.stage === "SF") return "Halbfinale";
if (match.stage === "3RD") return "Spiel um Platz 3";
if (match.stage === "FINAL") return "Finale";
return match.stage;
}
export default function Simulation({ teams, matches }: { teams: Team[]; matches: Match[] }) {
const [overrides, setOverrides] = useState<SimOverrides>({});
useEffect(() => {
setOverrides(loadOverrides());
}, []);
const handleScore = useCallback((matchId: string, homeScore: number, awayScore: number) => {
setOverrides((prev) => {
const next = { ...prev, [matchId]: { homeScore, awayScore } };
saveOverrides(next);
return next;
});
}, []);
const handleReset = useCallback(() => {
setOverrides({});
saveOverrides({});
}, []);
const handleClear = useCallback((matchId: string) => {
setOverrides((prev) => {
const next = { ...prev };
delete next[matchId];
saveOverrides(next);
return next;
});
}, []);
// ---- Simulations-Pipeline ----
const simMatches = useMemo(() => buildSimMatches(matches, overrides), [matches, overrides]);
// ---- Simulations-Pipeline (Polymarket-Defaults, keine manuellen Overrides) ----
const simMatches = useMemo(() => buildSimMatches(matches, {}), [matches]);
const simTables = useMemo(() => computeGroupTables(teams, simMatches), [teams, simMatches]);
const simThirds = useMemo(() => computeThirdPlaceTable(simTables), [simTables]);
const simQGroups = useMemo(() => qualifiedThirdGroups(simThirds), [simThirds]);
@@ -149,95 +92,14 @@ export default function Simulation({ teams, matches }: { teams: Team[]; matches:
return { r32: r32Fixed, later: laterFixed };
}, [simBracket, realProvisional, realDecided]);
// ---- Eingabeliste: offene Spiele aus dem echten Feed ----
const openMatches = useMemo(
() =>
matches
.filter((m) => m.status !== "FINISHED")
.sort((a, b) => +new Date(a.utcDate) - +new Date(b.utcDate)),
[matches],
);
const groupPhase = openMatches.filter((m) => m.stage === "GROUP");
const koPhase = openMatches.filter((m) => m.stage !== "GROUP");
// KO-Eingaben erst freigeben, wenn alle Gruppenspiele beendet sind.
const groupPhaseComplete = matches
.filter((m) => m.group != null)
.every((m) => m.status === "FINISHED");
const hasChanges = Object.keys(overrides).length > 0;
return (
<div>
<div className="notice" style={{ marginBottom: 20 }}>
Simulation Ergebnisse frei wählbar, beeinflusst nicht die echten Daten.
Alle ungespielten Spiele sind vorbelegt mit dem Polymarket-Favoriten.
Eingaben werden im Browser gespeichert.
Simulation alle ungespielten Spiele sind mit dem Polymarket-Favoriten
vorbelegt. Die angezeigten Wahrscheinlichkeiten stammen von Polymarket.
</div>
{/* ---- Eingabeliste ---- */}
<div style={{ marginBottom: 28 }}>
<div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
<h3 style={{ fontFamily: "var(--font-display)", fontSize: 15, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--ink-dim)", margin: 0 }}>
Offene Spiele ({openMatches.length})
</h3>
{hasChanges && (
<button
onClick={handleReset}
style={{
fontFamily: "var(--font-mono)", fontSize: 11,
color: "var(--ink-faint)", background: "var(--bg-card)",
border: "1px solid var(--line)", borderRadius: "var(--radius-sm)",
padding: "5px 12px", cursor: "pointer",
}}
>
Auf Polymarket-Defaults zurücksetzen
</button>
)}
</div>
{groupPhase.length > 0 && (
<div style={{ marginBottom: 16 }}>
<div style={{ fontFamily: "var(--font-display)", fontSize: 12, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--ink-faint)", marginBottom: 8 }}>
Gruppenphase
</div>
<div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
{groupPhase.map((m) => (
<SimRow key={m.id} match={m} teams={teams} overrides={overrides} onScore={handleScore} onClear={handleClear} />
))}
</div>
</div>
)}
{koPhase.length > 0 && (
<div>
<div style={{ fontFamily: "var(--font-display)", fontSize: 12, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--ink-faint)", marginBottom: 8 }}>
K.o.-Phase
</div>
{groupPhaseComplete ? (
<div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
{koPhase.map((m) => (
<SimRow key={m.id} match={m} teams={teams} overrides={overrides} onScore={handleScore} onClear={handleClear} />
))}
</div>
) : (
<div className="notice" style={{ fontSize: 13 }}>
K.o.-Spiele werden zur Eingabe freigegeben, sobald die Gruppenphase abgeschlossen ist.
</div>
)}
</div>
)}
</div>
{/* ---- Drittplatzierte (simuliert) ---- */}
<h3 style={{ fontFamily: "var(--font-display)", fontSize: 15, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--ink-dim)", margin: "0 0 12px" }}>
Drittplatzierte (simuliert)
</h3>
<ThirdPlace rows={simThirds} teams={teams} />
{/* ---- Simulierter K.o.-Baum ---- */}
<h3 style={{ fontFamily: "var(--font-display)", fontSize: 15, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--ink-dim)", margin: "28px 0 12px" }}>
Simulierter K.o.-Baum
</h3>
<Bracket
@@ -252,99 +114,3 @@ export default function Simulation({ teams, matches }: { teams: Team[]; matches:
</div>
);
}
// ---- Einzelne Eingabezeile ----
function SimRow({
match, teams, overrides, onScore, onClear,
}: {
match: Match; teams: Team[]; overrides: SimOverrides; onScore: (id: string, h: number, a: number) => void;
onClear: (id: string) => void;
}) {
const home = teamById(teams, match.homeTeamId);
const away = teamById(teams, match.awayTeamId);
const def = defaultScore(match);
const ov = overrides[match.id];
const homeVal = ov?.homeScore ?? def?.homeScore;
const awayVal = ov?.awayScore ?? def?.awayScore;
const homeChanged = ov != null;
const isKO = match.stage !== "GROUP";
const inputStyle = (changed: boolean): React.CSSProperties => ({
width: 36,
height: 28,
textAlign: "center",
fontFamily: "var(--font-mono)",
fontSize: 14,
fontWeight: 700,
color: changed ? "var(--turf)" : "var(--ink)",
background: "var(--bg-raised)",
border: `1px solid ${changed ? "var(--turf)" : "var(--line)"}`,
borderRadius: "var(--radius-sm)",
outline: "none",
MozAppearance: "textfield",
});
return (
<div className="sim-row" style={{
display: "flex", alignItems: "center", gap: 10,
padding: "6px 12px",
background: "var(--bg-card)", border: "1px solid var(--line-soft)",
borderRadius: "var(--radius-sm)",
fontSize: 13,
}}>
<span className="sim-row-phase" style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--ink-faint)", minWidth: 75 }}>
{phaseLabel(match)}
</span>
<span style={{ display: "flex", alignItems: "center", gap: 6, minWidth: 0, flex: 1, justifyContent: "flex-end" }}>
<Flag team={home} size={18} />
<span style={{ fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", maxWidth: 140 }}>
{home?.localisedName ?? home?.name ?? "—"}
</span>
</span>
<input
type="number"
min={0}
style={inputStyle(homeChanged)}
value={homeVal ?? ""}
placeholder=""
onChange={(e) => {
const v = parseInt(e.target.value, 10);
if (!isNaN(v) && v >= 0) {
onScore(match.id, v, awayVal ?? (isKO ? 0 : 1));
} else if (e.target.value === "") {
// Bei Leerung: Standard wiederherstellen
const fallback = def;
if (fallback) onScore(match.id, fallback.homeScore, fallback.awayScore);
}
}}
/>
<span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, color: "var(--ink-faint)" }}>:</span>
<input
type="number"
min={0}
style={inputStyle(homeChanged)}
value={awayVal ?? ""}
placeholder=""
onChange={(e) => {
const v = parseInt(e.target.value, 10);
if (!isNaN(v) && v >= 0) {
onScore(match.id, homeVal ?? (isKO ? 0 : 1), v);
} else if (e.target.value === "") {
const fallback = def;
if (fallback) onScore(match.id, fallback.homeScore, fallback.awayScore);
else onClear(match.id);
}
}}
/>
<span style={{ display: "flex", alignItems: "center", gap: 6, minWidth: 0, flex: 1 }}>
<span style={{ fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", maxWidth: 140 }}>
{away?.localisedName ?? away?.name ?? "—"}
</span>
<Flag team={away} size={18} />
</span>
<span className="sim-row-date" style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--ink-faint)", minWidth: 100, textAlign: "right" }}>
{fmtDate(match.utcDate)}
</span>
</div>
);
}

View File

@@ -3,12 +3,13 @@
import { Team, ThirdPlaceRow } from "@/lib/types";
export default function ThirdPlace({
rows, teams,
}: { rows: ThirdPlaceRow[]; teams: Team[] }) {
rows, teams, secureTeams,
}: { rows: ThirdPlaceRow[]; teams: Team[]; secureTeams?: string[] }) {
const name = (id: string) => {
const t = teams.find((t) => t.id === id);
return t?.localisedName ?? t?.name ?? id;
};
const secureSet = secureTeams ? new Set(secureTeams) : null;
return (
<div className="third-wrap">
@@ -35,7 +36,12 @@ export default function ThirdPlace({
>
<td>{r.overallRank}</td>
<td>{r.group}</td>
<td style={{ fontWeight: 600 }}>{name(r.teamId)}</td>
<td className={r.played === 3 ? "team-complete" : ""} style={{ fontWeight: 600 }}>
{name(r.teamId)}
{secureSet?.has(r.teamId) && (
<span style={{ color: "var(--turf)", marginLeft: 6, fontSize: 13 }} title="sicher qualifiziert"></span>
)}
</td>
<td>{r.played}</td>
<td className="pts">{r.points}</td>
<td>{r.goalDiff > 0 ? `+${r.goalDiff}` : r.goalDiff}</td>

View File

@@ -47,7 +47,7 @@ body {
a { color: inherit; text-decoration: none; }
.wrap { max-width: 1240px; margin: 0 auto; padding: 0 20px; }
.wrap { max-width: 1240px; margin: 0 auto; padding: 0 20px 0 0; }
/* ---------- Header / Hero ---------- */
.masthead {
@@ -180,6 +180,9 @@ table.standings { width: 100%; border-collapse: collapse; }
.qual-badge.yes { background: rgba(74,222,128,0.16); color: var(--turf); }
.qual-badge.no { background: rgba(95,109,146,0.16); color: var(--ink-faint); }
/* Drittplatzierte: Teamname grün, wenn alle 3 Gruppenspiele gespielt */
.third-table td.team-complete { color: var(--turf); }
/* ---------- Bracket ---------- */
.bracket-banner {
display: flex; align-items: center; gap: 12px; flex-wrap: wrap;
@@ -217,9 +220,17 @@ table.standings { width: 100%; border-collapse: collapse; }
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-head {
font-family: var(--font-mono); font-size: 9px; color: var(--ink-faint);
.tie-meta {
font-family: var(--font-mono); font-size: 9px; color: rgba(255,255,255,0.55);
letter-spacing: 0.04em; padding: 5px 10px 0;
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.match-badge {
position: absolute; top: -6px; right: -6px;
font-family: var(--font-mono); font-size: 9px; font-weight: 700;
line-height: 18px; min-width: 18px; text-align: center;
border-radius: 999px; padding: 0 4px;
background: #1a2744; color: #ffffff; border: 1px solid rgba(255,255,255,0.15);
}
.side {
display: flex; align-items: center; justify-content: space-between;
@@ -282,6 +293,7 @@ table.standings { width: 100%; border-collapse: collapse; }
.wrap { padding: 0 12px; }
/* ---------- mobil: Header ---------- */
.masthead { padding: 0 12px; }
.masthead-inner { padding: 10px 0; gap: 8px; }
.brand { gap: 6px; }
.brand-mark { font-size: 18px; }
@@ -289,15 +301,13 @@ table.standings { width: 100%; border-collapse: collapse; }
.status-pill { font-size: 10px; padding: 4px 10px; gap: 5px; }
.dot { width: 6px; height: 6px; }
/* ---------- mobil: Tabs (horizontal scroll, kein Umbruch) ---------- */
/* ---------- mobil: Tabs (zwei Zeilen, kein horizontaler Scroll) ---------- */
.masthead-tabs {
overflow-x: auto;
flex-wrap: nowrap;
-webkit-overflow-scrolling: touch;
scrollbar-width: none;
flex-wrap: wrap;
justify-content: center;
gap: 2px 4px;
}
.masthead-tabs::-webkit-scrollbar { display: none; }
.tab { padding: 10px 14px; font-size: 12px; white-space: nowrap; flex-shrink: 0; }
.tab { padding: 8px 13px; font-size: 12px; }
.section { padding: 18px 0 48px; }
@@ -320,7 +330,8 @@ table.standings { width: 100%; border-collapse: collapse; }
.fx-score { font-size: 16px; min-width: 44px; }
.fx-vs { font-size: 14px; min-width: 44px; }
.fx-name { font-size: 13px; max-width: 110px; }
.grp-chip { width: 34px; height: 34px; font-size: 12px; }
.grp-switch { gap: 8px; }
.grp-chip { width: 40px; height: 40px; font-size: 14px; }
/* ---------- mobil: Drittplatzierte ---------- */
.third-table th { font-size: 9px; padding: 8px 6px; }
@@ -338,7 +349,7 @@ table.standings { width: 100%; border-collapse: collapse; }
.round { min-width: 170px; }
.round-label { font-size: 10px; }
.round-matches { gap: 8px; }
.tie-head { font-size: 8px; padding: 3px 8px 0; }
.tie-meta { font-size: 8px; padding: 3px 8px 0; }
.side { padding: 6px 8px; font-size: 11px; }
.side .nm { gap: 5px; }
.prov-mark { font-size: 10px; }

View File

@@ -1,4 +1,5 @@
import type { Metadata } from "next";
import Script from "next/script";
import "./globals.css";
export const metadata: Metadata = {
@@ -23,7 +24,17 @@ export default function RootLayout({ children }: { children: React.ReactNode })
rel="stylesheet"
/>
</head>
<body>{children}</body>
<body>
{children}
{process.env.NEXT_PUBLIC_UMAMI_SRC && process.env.NEXT_PUBLIC_UMAMI_ID && (
<Script
defer
src={process.env.NEXT_PUBLIC_UMAMI_SRC}
data-website-id={process.env.NEXT_PUBLIC_UMAMI_ID}
strategy="afterInteractive"
/>
)}
</body>
</html>
);
}

View File

@@ -8,6 +8,7 @@ import ThirdPlace from "./components/ThirdPlace";
import Bracket from "./components/Bracket";
import Fixtures from "./components/Fixtures";
import Simulation from "./components/Simulation";
import KoFixtures from "./components/KoFixtures";
interface ApiData {
updatedAt: string;
@@ -16,16 +17,17 @@ interface ApiData {
groupTables: GroupTable[];
groupTablesLive: GroupTable[];
thirdTable: ThirdPlaceRow[];
secureThirdTeams: string[];
annexAssignment: ThirdAssignment | null;
annexResolved: boolean;
}
type Tab = "groups" | "fixtures" | "thirds" | "bracket" | "sim";
type Tab = "groups" | "groupfixtures" | "kofixtures" | "thirds" | "bracket" | "sim";
export default function Home() {
const [data, setData] = useState<ApiData | null>(null);
const [error, setError] = useState<string | null>(null);
const [tab, setTab] = useState<Tab>("groups");
const [tab, setTab] = useState<Tab>("kofixtures");
// Zuletzt gewählte Gruppe für den Spiele-Tab. null = noch keine gewählt.
const [fixturesGroup, setFixturesGroup] = useState<GroupId | null>(null);
@@ -52,7 +54,7 @@ export default function Home() {
// Klick auf einen Gruppen-Header: Gruppe merken und zum Spiele-Tab wechseln.
const openGroupFixtures = useCallback((g: GroupId) => {
setFixturesGroup(g);
setTab("fixtures");
setTab("groupfixtures");
}, []);
const anyLive = data?.matches.some(
@@ -76,14 +78,17 @@ export default function Home() {
: "Lade Daten…"}
</span>
<nav className="tabs masthead-tabs">
<button className={`tab ${tab === "kofixtures" ? "active" : ""}`} onClick={() => setTab("kofixtures")}>
K.O.-Spiele
</button>
<button className={`tab ${tab === "groups" ? "active" : ""}`} onClick={() => setTab("groups")}>
Gruppen
</button>
<button
className={`tab ${tab === "fixtures" ? "active" : ""}`}
onClick={() => { if (!fixturesGroup) setFixturesGroup("A"); setTab("fixtures"); }}
className={`tab ${tab === "groupfixtures" ? "active" : ""}`}
onClick={() => { if (!fixturesGroup) setFixturesGroup("A"); setTab("groupfixtures"); }}
>
{fixturesGroup ? `Spiele Gruppe ${fixturesGroup}` : "Spiele"}
{fixturesGroup ? `Gruppenspiele ${fixturesGroup}` : "Gruppenspiele"}
</button>
<button className={`tab ${tab === "thirds" ? "active" : ""}`} onClick={() => setTab("thirds")}>
Drittplatzierte
@@ -115,20 +120,23 @@ export default function Home() {
</div>
)}
{data && tab === "kofixtures" && (
<KoFixtures teams={data.teams} matches={data.matches} />
)}
{data && tab === "groups" && (
<Groups
tables={data.groupTablesLive} teams={data.teams} matches={data.matches}
onOpenGroup={openGroupFixtures}
/>
)}
{data && tab === "fixtures" && fixturesGroup && (
{data && tab === "groupfixtures" && fixturesGroup && (
<Fixtures
group={fixturesGroup} teams={data.teams} matches={data.matches}
onSelectGroup={setFixturesGroup}
/>
)}
{data && tab === "thirds" && (
<ThirdPlace rows={data.thirdTable} teams={data.teams} />
<ThirdPlace rows={data.thirdTable} teams={data.teams} secureTeams={data.secureThirdTeams} />
)}
{data && tab === "bracket" && (
<Bracket

View File

@@ -4,7 +4,11 @@
services:
wm2026:
build: .
build:
context: .
args:
NEXT_PUBLIC_UMAMI_SRC: ${NEXT_PUBLIC_UMAMI_SRC:-}
NEXT_PUBLIC_UMAMI_ID: ${NEXT_PUBLIC_UMAMI_ID:-}
image: wm2026-board:latest
container_name: wm2026
restart: unless-stopped

View File

@@ -1,6 +1,8 @@
import { GroupId, Match, MatchStatus, Team } from "./types";
import { venueFor } from "./venues";
import { localisedTeamName } from "./team-mappings";
import { R32, LATER_ROUNDS, resolveAnnexC, qualifiedThirdGroups } from "./bracket";
import { computeGroupTables, computeThirdPlaceTable } from "./standings";
// ----------------------------------------------------------------------------
// Caching: einfacher In-Memory-Cache mit TTL. Verhindert, dass jede Browser-
@@ -88,26 +90,74 @@ const STAGE_ORDER: Record<Match["stage"], number> = {
};
// 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.
// K.o.-Spiele: Nummerierung über Slot-Auflösung (assignKONumbersBySlots),
// NICHT mehr chronologisch — die FIFA-Nummern folgen der Bracket-Topologie.
// 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);
}
}
// Vergibt K.o.-Match-Nummern über Slot-Auflösung (FIFA-Topologie)
// statt chronologisch. Für R32-Matches mit Team-IDs wird der Slot gesucht,
// dessen aufgelöste Teams dem Feed-Paar entsprechen.
export function assignKONumbersBySlots(matches: Match[], teams: Team[]): void {
const tables = computeGroupTables(teams, matches);
const thirds = computeThirdPlaceTable(tables);
const qGroups = qualifiedThirdGroups(thirds);
const annex = qGroups.length === 8 ? resolveAnnexC(qGroups) : null;
const byPair = new Map<string, Match>();
for (const m of matches) {
if (m.group != null || !m.homeTeamId || !m.awayTeamId) continue;
byPair.set(`${m.homeTeamId}::${m.awayTeamId}`, m);
byPair.set(`${m.awayTeamId}::${m.homeTeamId}`, m);
}
for (const slot of R32) {
const homeGroup = slot.home.type === "W" ? slot.home.group : undefined;
const awayGroup = slot.away.type === "W" ? slot.away.group : undefined;
const wg = (homeGroup ?? awayGroup) as GroupId | undefined;
let hid: string | null = null;
if (slot.home.type === "W" && slot.home.group) {
hid = tables.find(t => t.group === slot.home.group)?.rows.find(r => r.rank === 1)?.teamId ?? null;
} else if (slot.home.type === "R" && slot.home.group) {
hid = tables.find(t => t.group === slot.home.group)?.rows.find(r => r.rank === 2)?.teamId ?? null;
} else if (slot.home.type === "3" && annex && wg) {
const tg = annex[wg];
if (tg) hid = thirds.find(r => r.group === tg && r.qualifies)?.teamId ?? null;
}
let aid: string | null = null;
if (slot.away.type === "W" && slot.away.group) {
aid = tables.find(t => t.group === slot.away.group)?.rows.find(r => r.rank === 1)?.teamId ?? null;
} else if (slot.away.type === "R" && slot.away.group) {
aid = tables.find(t => t.group === slot.away.group)?.rows.find(r => r.rank === 2)?.teamId ?? null;
} else if (slot.away.type === "3" && annex && wg) {
const tg = annex[wg];
if (tg) aid = thirds.find(r => r.group === tg && r.qualifies)?.teamId ?? null;
}
if (hid && aid) {
const fm = byPair.get(`${hid}::${aid}`);
if (fm) fm.matchNumber = slot.matchNumber;
}
}
// R16Finale: per Stage + Datum den LATER_ROUNDS-Slots zuordnen
for (const stage of ["R16", "QF", "SF", "3RD", "FINAL"] as const) {
const sm = matches.filter(m => m.stage === stage && m.group == null && m.matchNumber === 0)
.sort((a, b) => +new Date(a.utcDate) - +new Date(b.utcDate));
const ls = LATER_ROUNDS.filter(k => k.stage === (stage === "3RD" ? "3RD" : stage));
for (let i = 0; i < sm.length && i < ls.length; i++) {
sm[i].matchNumber = ls[i].matchNumber;
}
}
}
// 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 () => {
@@ -154,6 +204,7 @@ export async function fetchMatchesAndTeams(): Promise<{ matches: Match[]; teams:
});
const teams = [...teamMap.values()];
assignNumbersAndVenues(matches, teams);
return { matches, teams };
@@ -183,6 +234,7 @@ interface PmMarket {
}
export interface ParsedOdds {
slug: string;
homeCode: string;
awayCode: string;
homeName: string;
@@ -190,6 +242,7 @@ export interface ParsedOdds {
pHome: number;
pDraw: number;
pAway: number;
startTime: string | null;
}
// Normalisiert Teamcodes zwischen Polymarket-Slug und Feed (3-Buchstaben).
@@ -214,7 +267,7 @@ function safeParse<T>(s: string, fallback: T): T {
// Holt alle WM-Spiele über den Series-Endpoint mit Pagination.
// Parst pro Event die drei Moneyline-Märkte (Heim/Draw/Auswärts).
export async function fetchOdds(): Promise<ParsedOdds[]> {
return cached("pm:odds", 120_000, async () => {
return cached("pm:odds", 300_000, async () => {
const allEvents: PmEvent[] = [];
for (let offset = 0; ; offset += 100) {
const url = `${PM_BASE}/events?series_id=${PM_SERIES}&active=true&closed=false&limit=100&offset=${offset}`;
@@ -227,9 +280,9 @@ export async function fetchOdds(): Promise<ParsedOdds[]> {
allEvents.push(...page);
if (page.length < 100) break;
}
//console.log("[polymarket] events fetched:", allEvents.length);
const parsed: ParsedOdds[] = [];
for (const ev of allEvents) {
// Slug: fifwc-{home}-{away}-{yyyy}-{mm}-{dd}
const slugParts = ev.slug.replace("fifwc-", "").split("-");
@@ -239,10 +292,12 @@ export async function fetchOdds(): Promise<ParsedOdds[]> {
let pHome = 0, pDraw = 0, pAway = 0;
let homeName = "", awayName = "";
let marketGameStartTime: string | null = null;
for (const mk of ev.markets ?? []) {
if (mk.sportsMarketType && mk.sportsMarketType !== "moneyline") continue;
if (mk.closed) continue;
if (!marketGameStartTime) marketGameStartTime = (mk as any).gameStartTime ?? null;
const prices = safeParse<string[]>(mk.outcomePrices, []).map(Number);
if (prices.length < 2) continue;
const yes = prices[0]; // erster Preis = "Yes"-Wahrscheinlichkeit
@@ -266,7 +321,8 @@ export async function fetchOdds(): Promise<ParsedOdds[]> {
}
if (pHome > 0 || pDraw > 0 || pAway > 0) {
parsed.push({ homeCode, awayCode, homeName, awayName, pHome, pDraw, pAway });
const startTime = marketGameStartTime ?? (ev as any).gameStartTime ?? (ev as any).endDate ?? (ev as any).startDate;
parsed.push({ slug: ev.slug, homeCode, awayCode, homeName, awayName, pHome, pDraw, pAway, startTime });
}
}
@@ -312,7 +368,9 @@ export function attachOdds(matches: Match[], teams: Team[], odds: ParsedOdds[]):
}
}
return matches.map((m) => {
const attachedOdds = new Set<ParsedOdds>();
const result = matches.map((m) => {
if (!m.homeTeamId || !m.awayTeamId) return m;
// Suche in oddsMatch nach einer Kombination die beide Team-IDs matcht
for (const [o, ids] of oddsMatch) {
@@ -321,6 +379,7 @@ export function attachOdds(matches: Match[], teams: Team[], odds: ParsedOdds[]):
if ((ids.homeId === m.homeTeamId && ids.awayId === m.awayTeamId) ||
(ids.homeId === m.awayTeamId && ids.awayId === m.homeTeamId)) {
const swapped = ids.homeId === m.awayTeamId;
attachedOdds.add(o);
return {
...m,
prob: {
@@ -333,4 +392,359 @@ export function attachOdds(matches: Match[], teams: Team[], odds: ParsedOdds[]):
}
return m;
});
return result;
}
// ----------------------------------------------------------------------------
// KO-Odds-Fallback: löst R32-Paarungen auf und verknüpft Polymarket-Events
// mit K.o.-Feed-Matches, die noch keine Team-IDs im Feed haben.
// ----------------------------------------------------------------------------
// Löst für jeden R32-Slot (73-88) die aktuellen Team-Paarungen auf Basis der
// Gruppentabellen und Annex-C-Zuordnung. Gibt eine Map matchNumber → Paarung
// zurück, NUR wenn beide Team-IDs eindeutig bekannt sind (kein Raten).
function resolveR32Pairings(matches: Match[], teams: Team[]): Map<number, { homeTeamId: string; awayTeamId: string }> {
const tables = computeGroupTables(teams, matches);
const thirds = computeThirdPlaceTable(tables);
const qGroups = qualifiedThirdGroups(thirds);
const annex = qGroups.length === 8 ? resolveAnnexC(qGroups) : null;
const pairings = new Map<number, { homeTeamId: string; awayTeamId: string }>();
for (const slot of R32) {
const homeGroup = slot.home.type === "W" ? slot.home.group : undefined;
const awayGroup = slot.away.type === "W" ? slot.away.group : undefined;
const wg = (homeGroup ?? awayGroup) as GroupId | undefined;
let hid: string | null = null;
if (slot.home.type === "W" && slot.home.group) {
hid = tables.find(t => t.group === slot.home.group)?.rows.find(r => r.rank === 1)?.teamId ?? null;
} else if (slot.home.type === "R" && slot.home.group) {
hid = tables.find(t => t.group === slot.home.group)?.rows.find(r => r.rank === 2)?.teamId ?? null;
} else if (slot.home.type === "3" && annex && wg) {
const tg = annex[wg];
if (tg) hid = thirds.find(r => r.group === tg && r.qualifies)?.teamId ?? null;
}
let aid: string | null = null;
if (slot.away.type === "W" && slot.away.group) {
aid = tables.find(t => t.group === slot.away.group)?.rows.find(r => r.rank === 1)?.teamId ?? null;
} else if (slot.away.type === "R" && slot.away.group) {
aid = tables.find(t => t.group === slot.away.group)?.rows.find(r => r.rank === 2)?.teamId ?? null;
} else if (slot.away.type === "3" && annex && wg) {
const tg = annex[wg];
if (tg) aid = thirds.find(r => r.group === tg && r.qualifies)?.teamId ?? null;
}
if (hid && aid) {
pairings.set(slot.matchNumber, { homeTeamId: hid, awayTeamId: aid });
}
}
return pairings;
}
// Extrahiert das Datum (YYYY-MM-DD) aus einem Polymarket-Slug.
// Slug-Format: fifwc-{home}-{away}-{yyyy}-{mm}-{dd}
function slugToDate(slug: string): string | null {
const parts = slug.split("-");
if (parts.length < 3) return null;
const y = parts[parts.length - 3];
const m = parts[parts.length - 2];
const d = parts[parts.length - 1];
if (/^\d{4}$/.test(y) && /^\d{2}$/.test(m) && /^\d{2}$/.test(d)) {
return `${y}-${m}-${d}`;
}
return null;
}
// Zweiter Durchlauf für attachOdds: ordnet Polymarket-Events K.o.-Feed-Matches
// zu, die (noch) keine Team-IDs im Feed haben. Arbeitet direkt auf den
// aufgelösten R32-Paarungen (resolveR32Pairings). Identifiziert das Ziel-
// Feed-Match über die Slot-matchNumber (Stufe 1) oder Datums-Lookup aus dem
// Slug (Stufe 2) — KEINE chronologische Nummernvergabe.
// Mutiert matches in-place, setzt nur bei Matches OHNE bestehende prob.
export function attachKOOdds(matches: Match[], teams: Team[], odds: ParsedOdds[]): Match[] {
const pairings = resolveR32Pairings(matches, teams);
if (pairings.size === 0) return matches;
const idByName = new Map<string, string>();
for (const t of teams) {
const nn = normName(t.name);
if (!idByName.has(nn)) idByName.set(nn, t.id);
}
const idByCode = new Map(teams.map((t) => [t.code.toLowerCase(), t.id]));
for (const [matchNum, pairing] of pairings) {
if (!pairing.homeTeamId || !pairing.awayTeamId) continue;
// Finde Polymarket-Event für dieses Team-Paar
let matchedEvent: ParsedOdds | null = null;
for (const o of odds) {
const hn = normName(o.homeName);
const an = normName(o.awayName);
const homeId = idByName.get(hn) ?? idByCode.get(o.homeCode);
const awayId = idByName.get(an) ?? idByCode.get(o.awayCode);
if (!homeId || !awayId) continue;
if ((homeId === pairing.homeTeamId && awayId === pairing.awayTeamId) ||
(homeId === pairing.awayTeamId && awayId === pairing.homeTeamId)) {
matchedEvent = o;
break;
}
}
if (!matchedEvent) continue;
// Ziel-Feed-Match identifizieren
let targetMatch: Match | undefined;
// Stufe 1: bereits nummeriertes R32-Match (via assignKONumbersBySlots Pass 1)
targetMatch = matches.find(m =>
m.stage === "R32" && m.group == null && m.matchNumber === matchNum,
);
// Stufe 2: Datums-Lookup aus Polymarket-Slug für unnummerierte Matches
if (!targetMatch) {
const slugDate = slugToDate(matchedEvent.slug);
if (slugDate) {
const candidates = matches.filter(m =>
m.stage === "R32" && m.group == null && m.matchNumber === 0 &&
m.utcDate.slice(0, 10) === slugDate,
);
if (candidates.length === 1) {
targetMatch = candidates[0];
targetMatch.matchNumber = matchNum;
} else if (candidates.length > 1) {
// Tie-breaker: falls Polymarket-Event eine Startzeit hat, nächstgelegenes Feed-Match
if (matchedEvent.startTime) {
const eventTime = new Date(matchedEvent.startTime).getTime();
let best: Match | undefined;
let bestDiff = Infinity;
for (const c of candidates) {
const diff = Math.abs(new Date(c.utcDate).getTime() - eventTime);
if (diff < bestDiff) { bestDiff = diff; best = c; }
}
// Nur zuordnen, wenn Zeitdifferenz plausibel (<4h)
if (best && bestDiff < 4 * 60 * 60 * 1000) {
targetMatch = best;
targetMatch.matchNumber = matchNum;
}
}
}
}
}
if (!targetMatch) continue;
// prob nicht überschreiben, falls schon gesetzt
if (targetMatch.prob) continue;
const homeIdFromEvent = idByName.get(normName(matchedEvent.homeName)) ??
idByCode.get(matchedEvent.homeCode);
const swapped = homeIdFromEvent === pairing.awayTeamId;
targetMatch.prob = {
home: swapped ? matchedEvent.pAway : matchedEvent.pHome,
draw: matchedEvent.pDraw,
away: swapped ? matchedEvent.pHome : matchedEvent.pAway,
};
}
return matches;
}
// ----------------------------------------------------------------------------
// worldcup26.ir: schnelle Live-Scores (additiv, Fallback auf football-data)
// ----------------------------------------------------------------------------
const WC26_BASE = "https://worldcup26.ir";
interface Wc26Game {
home_team_name_en?: string;
away_team_name_en?: string;
group?: string;
matchday?: string;
home_score?: string;
away_score?: string;
time_elapsed?: string;
goals?: Array<{ name?: string; minute?: string; team?: string }>;
current_minute?: string;
}
interface LiveScore {
homeName: string;
awayName: string;
group: string;
matchday: string;
homeScore: number | null;
awayScore: number | null;
status: string; // "IN_PLAY" | "FINISHED"
}
// Ruft alle Spiele von worldcup26.ir ab.
export async function fetchLiveScores(): Promise<LiveScore[]> {
const res = await fetch(`${WC26_BASE}/get/games`, {
cache: "no-store",
headers: { "User-Agent": "wm2026-board/1.0" },
signal: AbortSignal.timeout(5000),
});
if (!res.ok) throw new Error(`worldcup26 ${res.status}`);
const data = (await res.json()) as { games: Wc26Game[] };
const games = data.games ?? [];
const scores: LiveScore[] = [];
for (const g of games) {
if (!g.home_team_name_en || !g.away_team_name_en) continue;
const hScore = parseScore(g.home_score);
const aScore = parseScore(g.away_score);
let status = "";
switch (g.time_elapsed) {
case "live": status = "IN_PLAY"; break;
case "finished": status = "FINISHED"; break;
default: continue; // notstarted → überspringen
}
// Nur anwenden, wenn mindestens ein Score vorhanden ist
if (hScore == null && aScore == null) continue;
scores.push({
homeName: g.home_team_name_en,
awayName: g.away_team_name_en,
group: g.group ?? "",
matchday: String(g.matchday ?? ""),
homeScore: hScore,
awayScore: aScore,
status,
});
}
console.log("[worldcup26] spiele:", scores.length);
return scores;
}
function parseScore(s: string | undefined): number | null {
if (!s || s === "null") return null;
const n = Number(s);
return Number.isFinite(n) ? n : null;
}
// Wendet worldcup26-Live-Scores auf football-data-Matches an.
// Matching über normalisierte Teamnamen + group + matchday.
export function applyLiveScores(
matches: Match[], teams: Team[], liveScores: LiveScore[],
): Match[] {
// Build lookup: normName(home)::normName(away)::group::matchday → match
// Für Group-Phase ist die Paarung eindeutig (jedes Paar spielt 1x).
const byPair = new Map<string, Match>();
for (const m of matches) {
if (m.group == null) continue; // nur Gruppenphase
if (!m.homeTeamId || !m.awayTeamId) continue;
const ht = teams.find((t) => t.id === m.homeTeamId);
const at = teams.find((t) => t.id === m.awayTeamId);
if (!ht || !at) continue;
const hn = normName(ht.name);
const an = normName(at.name);
// Beide Richtungen
byPair.set(`${hn}::${an}::${m.group}`, m);
byPair.set(`${an}::${hn}::${m.group}`, m);
}
const result = [...matches];
let applied = 0;
for (const ls of liveScores) {
const hn = normName(ls.homeName);
const an = normName(ls.awayName);
const key = `${hn}::${an}::${ls.group}`;
const fdMatch = byPair.get(key);
if (!fdMatch) continue;
const idx = result.findIndex((m) => m.id === fdMatch.id);
if (idx < 0) continue;
result[idx] = {
...result[idx],
homeScore: ls.homeScore ?? result[idx].homeScore,
awayScore: ls.awayScore ?? result[idx].awayScore,
status: ls.status as Match["status"],
};
applied++;
}
if (applied > 0) console.log("[worldcup26] auf matches angewandt:", applied);
return result;
}
// Holt KO-Live-Daten von worldcup26 (Tore, Minute) und hängt sie an die Feed-Matches.
export async function fetchKOLiveData(): Promise<Wc26Game[]> {
try {
const res = await fetch(`${WC26_BASE}/get/games`, {
cache: "no-store",
headers: { "User-Agent": "wm2026-board/1.0" },
signal: AbortSignal.timeout(5000),
});
if (!res.ok) throw new Error(`worldcup26 ${res.status}`);
const data = (await res.json()) as { games: Wc26Game[] };
return (data.games ?? []).filter(g => {
const grp = (g.group ?? "").toUpperCase();
return grp === "" || grp === "R32" || grp === "R16" || grp === "QF" || grp === "SF" || grp === "3RD" || grp === "FINAL" || grp === "FINALIST";
});
} catch {
return [];
}
}
// Hängt worldcup26-KO-Live-Daten an die Matches an (Tore, Minute, Scores).
export function attachKOLiveData(matches: Match[], teams: Team[], koGames: Wc26Game[]): Match[] {
if (koGames.length === 0) return matches;
const nameById = new Map<string, string>();
for (const t of teams) {
const nn = normName(t.name);
if (!nameById.has(nn)) nameById.set(nn, t.id);
}
return matches.map((m) => {
if (m.group != null) return m; // nur K.o.-Spiele
const hId = m.homeTeamId;
const aId = m.awayTeamId;
const hName = hId ? teams.find(t => t.id === hId)?.name : null;
const aName = aId ? teams.find(t => t.id === aId)?.name : null;
// Finde worldcup26-Spiel über Teamnamen
const wm = koGames.find(g => {
if (!hName || !aName) return false;
const gh = normName(g.home_team_name_en ?? "");
const ga = normName(g.away_team_name_en ?? "");
return (gh === normName(hName) && ga === normName(aName)) ||
(gh === normName(aName) && ga === normName(hName));
});
if (!wm) return m;
const result = { ...m };
// Live-Score + Status
if (wm.time_elapsed === "live" || wm.time_elapsed === "finished") {
result.status = wm.time_elapsed === "finished" ? "FINISHED" : "IN_PLAY";
const hs = parseScore(wm.home_score);
const as = parseScore(wm.away_score);
if (hs != null) result.homeScore = hs;
if (as != null) result.awayScore = as;
}
// Spielminute
if (wm.current_minute) {
const min = parseInt(wm.current_minute, 10);
if (!isNaN(min)) result.minute = min;
}
// Torereignisse
if (wm.goals && wm.goals.length > 0) {
result.goals = wm.goals.map(g => ({
scorer: g.name ?? "?",
minute: parseInt(g.minute ?? "0", 10) || 0,
team: g.team?.toLowerCase() === "away" ? "away" as const : "home" as const,
}));
}
return result;
});
}

View File

@@ -4,6 +4,7 @@ import {
ThirdAssignment, slotLabel,
} from "@/lib/bracket";
import { placeIsSecure } from "@/lib/secure-places";
import { thirdSlotIsSecure, securelyQualifiedThirdTeams } from "@/lib/third-place-security";
// Ein aufgelöster Teilnehmer einer K.o.-Begegnung.
export interface ResolvedSide {
@@ -46,15 +47,6 @@ function loserOf(m: Match | undefined): string | null {
return null;
}
// Prüft, ob die gesamte Gruppenphase abgeschlossen ist.
// Erst dann stehen die Drittplatzierten-Rangliste und die
// Annex-C-Zuordnung final fest.
function groupStageComplete(matches: Match[]): boolean {
const groupMatches = matches.filter((m) => m.group != null);
if (groupMatches.length === 0) return false;
return groupMatches.every((m) => m.status === "FINISHED");
}
// Löst einen R32-Slot (W/R/3) zu einer Team-ID auf, sofern bereits bekannt.
// provisional = true, solange die zugrunde liegende Gruppe/Zuordnung nicht fix ist.
function resolveR32Slot(
@@ -66,6 +58,7 @@ function resolveR32Slot(
matches: Match[],
teams: Team[],
annexResolved: boolean,
secureTeamIds: Set<string>,
): { teamId: string | null; provisional: boolean; tooltip: string | null } {
const table = (g: GroupId) => tables.find((t) => t.group === g);
if (slot.type === "W") {
@@ -89,11 +82,14 @@ function resolveR32Slot(
const thirdGroup = assignment[winnerGroup];
if (thirdGroup) {
const row = thirds.find((r) => r.group === thirdGroup && r.qualifies);
// Fix nur, wenn ALLE drei Bedingungen erfüllt sind:
// Fix nur, wenn ALLE Bedingungen erfüllt sind:
// 1. Annex C aufgelöst (8 Dritte zuweisbar)
// 2. Komplette Gruppenphase beendet (Dritten-Rangliste final)
// 3. Das Team gehört gesichert zu den besten 8
const fix = annexResolved && groupStageComplete(matches) && row?.qualifies === true;
// 2. Der Slot ist in allen noch möglichen Konstellationen stabil
// 3. Das konkrete Team ist sicher qualifiziert (kann nicht aus Top 8 fallen)
// 4. Die Gruppe hat alle Spiele gespielt (Team bekannt)
const slotStable = thirdSlotIsSecure(winnerGroup, matches, teams);
const teamSecure = row?.teamId ? secureTeamIds.has(row.teamId) : false;
const fix = annexResolved && slotStable && teamSecure && row?.qualifies === true;
const provisional = !fix;
const prefix = provisional ? "aktuell " : "";
return {
@@ -148,6 +144,7 @@ export function resolveBracket(
const losers = new Map<number, string | null>();
// Map: Match-Nummer -> ist das Spiel beendet (Sieger fix)?
const decided = new Map<number, boolean>();
const secureTeamIds = securelyQualifiedThirdTeams(matches, teams);
const r32: ResolvedTie[] = R32.map((rm: R32Match) => {
const feed = feedMatch(matches, rm.matchNumber);
@@ -156,26 +153,26 @@ 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, teams, annexResolved);
const a = resolveR32Slot(rm.away, winnerGroup, tables, assignment, thirds, matches, teams, annexResolved);
const h = resolveR32Slot(rm.home, winnerGroup, tables, assignment, thirds, matches, teams, annexResolved, secureTeamIds);
const a = resolveR32Slot(rm.away, winnerGroup, tables, assignment, thirds, matches, teams, annexResolved, secureTeamIds);
const home = sideFrom(h.teamId, slotLabel(rm.home, assignment, winnerGroup), teams, feed, "home", h.provisional, h.tooltip);
const away = sideFrom(a.teamId, slotLabel(rm.away, assignment, winnerGroup), teams, feed, "away", a.provisional, a.tooltip);
const feedWinner = winnerOf(feed);
if (resolveWinners && !feedWinner && feed && h.teamId && a.teamId
// Sim-Modus: Gewinner NUR aus Scores + Slot-Team-IDs ableiten.
// feedWinner (aus feed.homeTeamId/awayTeamId) wird IGNORIERT,
// weil matchNumber-Zuweisung (assignNumbersAndVenues) von der
// FIFA-Nummerierung abweichen kann → feed gehört evtl. zum falschen Spiel.
if (resolveWinners && feed && h.teamId && a.teamId
&& feed.homeScore != null && feed.awayScore != null) {
// Simulation: Gewinner aus Scores und aufgelösten Team-IDs ableiten
if (feed.homeScore > feed.awayScore) {
winners.set(rm.matchNumber, h.teamId);
losers.set(rm.matchNumber, loserOf(feed) ?? a.teamId);
} else if (feed.awayScore > feed.homeScore) {
winners.set(rm.matchNumber, a.teamId);
losers.set(rm.matchNumber, loserOf(feed) ?? h.teamId);
} else {
// Unentschieden → Heim gewinnt
winners.set(rm.matchNumber, h.teamId);
losers.set(rm.matchNumber, loserOf(feed) ?? a.teamId);
}
// Simulation: Gewinner aus Scores und aufgelösten Team-IDs ableiten.
// Nutze NICHT feed.homeTeamId/awayTeamId (sind null für KO-Matches),
// sondern die aufgelösten h.teamId / a.teamId aus resolveR32Slot.
const homeWins = feed.homeScore > feed.awayScore;
const awayWins = feed.awayScore > feed.homeScore;
const winnerId = homeWins ? h.teamId : awayWins ? a.teamId : h.teamId;
winners.set(rm.matchNumber, winnerId);
losers.set(rm.matchNumber, loserOf(feed) ?? (homeWins ? a.teamId : awayWins ? h.teamId : a.teamId));
} else {
winners.set(rm.matchNumber, feedWinner);
losers.set(rm.matchNumber, loserOf(feed));
@@ -193,6 +190,7 @@ export function resolveBracket(
const src = km.losers ? losers : winners;
const homeId = src.get(km.fromHome) ?? null;
const awayId = src.get(km.fromAway) ?? null;
// Ein Folgeteam ist fix, wenn das speisende Spiel beendet ist.
const homeProv = !(decided.get(km.fromHome) ?? false);
const awayProv = !(decided.get(km.fromAway) ?? false);
@@ -204,18 +202,13 @@ export function resolveBracket(
const away = sideFrom(awayId, awayLabel, teams, feed, "away", awayProv, awayTtip);
const feedWinner = winnerOf(feed);
if (resolveWinners && !feedWinner && feed && homeId && awayId
if (resolveWinners && feed && homeId && awayId
&& feed.homeScore != null && feed.awayScore != null) {
if (feed.homeScore > feed.awayScore) {
winners.set(km.matchNumber, homeId);
losers.set(km.matchNumber, loserOf(feed) ?? awayId);
} else if (feed.awayScore > feed.homeScore) {
winners.set(km.matchNumber, awayId);
losers.set(km.matchNumber, loserOf(feed) ?? homeId);
} else {
winners.set(km.matchNumber, homeId);
losers.set(km.matchNumber, loserOf(feed) ?? awayId);
}
const homeWins = feed.homeScore > feed.awayScore;
const awayWins = feed.awayScore > feed.homeScore;
const winnerId = homeWins ? homeId : awayWins ? awayId : homeId;
winners.set(km.matchNumber, winnerId);
losers.set(km.matchNumber, loserOf(feed) ?? (homeWins ? awayId : awayWins ? homeId : awayId));
} else {
winners.set(km.matchNumber, feedWinner);
losers.set(km.matchNumber, loserOf(feed));

74
lib/stadiums.ts Normal file
View File

@@ -0,0 +1,74 @@
// Statische Stadion-Daten für WM 2026.
export const STADIUMS: Record<string, { name: string; city: string }> = {
"1": { name: "Estadio Azteca", city: "Mexico City" },
"2": { name: "Estadio Akron", city: "Guadalajara" },
"3": { name: "Estadio BBVA", city: "Monterrey" },
"4": { name: "AT&T Stadium", city: "Dallas" },
"5": { name: "NRG Stadium", city: "Houston" },
"6": { name: "GEHA Field at Arrowhead Stadium", city: "Kansas City" },
"7": { name: "Mercedes-Benz Stadium", city: "Atlanta" },
"8": { name: "Hard Rock Stadium", city: "Miami" },
"9": { name: "Gillette Stadium", city: "Boston" },
"10": { name: "Lincoln Financial Field", city: "Philadelphia" },
"11": { name: "MetLife Stadium", city: "New York/New Jersey" },
"12": { name: "BMO Field", city: "Toronto" },
"13": { name: "BC Place", city: "Vancouver" },
"14": { name: "Lumen Field", city: "Seattle" },
"15": { name: "Levi's Stadium", city: "San Francisco Bay Area" },
"16": { name: "SoFi Stadium", city: "Los Angeles" },
};
// K.o.-Spielnummer → ISO-8601 UTC-Anstoßzeit (FIFA-Spielplan, statisch).
export const MATCH_DATES: Record<number, string> = {
// Letzte 32 (28.06. - 03.07.)
73: "2026-06-28T19:00:00Z", // 28.06. 14:00
74: "2026-06-29T20:30:00Z", // 29.06. 15:30
75: "2026-06-30T01:00:00Z", // 29.06. 20:00 (UTC nächster Tag)
76: "2026-06-29T17:00:00Z", // 29.06. 12:00
77: "2026-06-30T21:00:00Z", // 30.06. 16:00
78: "2026-06-30T17:00:00Z", // 30.06. 12:00
79: "2026-07-01T01:00:00Z", // 30.06. 20:00 (UTC nächster Tag)
80: "2026-07-01T16:00:00Z", // 01.07. 11:00
81: "2026-07-02T00:00:00Z", // 01.07. 19:00 (UTC nächster Tag)
82: "2026-07-01T20:00:00Z", // 01.07. 15:00
83: "2026-07-02T23:00:00Z", // 02.07. 18:00
84: "2026-07-02T19:00:00Z", // 02.07. 14:00
85: "2026-07-03T03:00:00Z", // 02.07. 22:00 (UTC nächster Tag)
86: "2026-07-03T22:00:00Z", // 03.07. 17:00
87: "2026-07-04T01:30:00Z", // 03.07. 20:30 (UTC nächster Tag)
88: "2026-07-03T18:00:00Z", // 03.07. 13:00
// Achtelfinale (04.07. - 07.07.)
89: "2026-07-04T21:00:00Z", // 04.07. 16:00
90: "2026-07-04T17:00:00Z", // 04.07. 12:00
91: "2026-07-05T20:00:00Z", // 05.07. 15:00
92: "2026-07-06T00:00:00Z", // 05.07. 19:00 (UTC nächster Tag)
93: "2026-07-06T19:00:00Z", // 06.07. 14:00
94: "2026-07-07T00:00:00Z", // 06.07. 19:00 (UTC nächster Tag)
95: "2026-07-07T16:00:00Z", // 07.07. 11:00
96: "2026-07-07T20:00:00Z", // 07.07. 15:00
// Viertelfinale (09.07. - 11.07.)
97: "2026-07-09T20:00:00Z", // 09.07. 15:00
98: "2026-07-10T19:00:00Z", // 10.07. 14:00
99: "2026-07-11T21:00:00Z", // 11.07. 16:00
100: "2026-07-12T01:00:00Z",// 11.07. 20:00 (UTC nächster Tag)
// Halbfinale (14.07. - 15.07.)
101: "2026-07-14T19:00:00Z",// 14.07. 14:00
102: "2026-07-15T19:00:00Z",// 15.07. 14:00
// Spiel um Platz 3 (18.07.)
103: "2026-07-18T21:00:00Z",// 18.07. 16:00
// Finale (19.07.)
104: "2026-07-19T19:00:00Z",// 19.07. 14:00
};
// K.o.-Spielnummer → stadium_id (FIFA-Quelle, statisch).
export const MATCH_STADIUMS: Record<number, string> = {
73: "16", 74: "9", 75: "3", 76: "5", 77: "11", 78: "4", 79: "1", 80: "7",
81: "15", 82: "14", 83: "12", 84: "16", 85: "13", 86: "8", 87: "6", 88: "4",
89: "10", 90: "5", 91: "11", 92: "1", 93: "4", 94: "14", 95: "7", 96: "13",
97: "9", 98: "16", 99: "8", 100: "6", 101: "4", 102: "7", 103: "8", 104: "11",
};

252
lib/third-place-security.ts Normal file
View File

@@ -0,0 +1,252 @@
import { GroupId, GROUP_IDS, Match, Team } from "./types";
import { computeGroupTables, computeThirdPlaceTable } from "./standings";
import { resolveAnnexC, qualifiedThirdGroups } from "./bracket";
// Repräsentative Ergebnis-Varianten je Restspiel (decken alle Punktkombinationen ab).
const OUTCOMES: Array<[number, number]> = [
[1, 0], // Heimsieg
[0, 1], // Auswärtssieg
[0, 0], // Unentschieden
];
interface ThirdInfo {
teamId: string;
points: number;
goalsFor: number;
goalsAgainst: number;
goalDiff: number;
}
interface GroupThirdState {
finished: boolean;
third: ThirdInfo | null;
minPoints: number;
maxPoints: number;
possibleTeamIds: Set<string>;
}
function openMatches(group: GroupId, matches: Match[]): Match[] {
return matches.filter(
(m) => m.group === group && m.status !== "FINISHED"
&& m.homeTeamId != null && m.awayTeamId != null,
);
}
function enumerateThirdPossibilities(
group: GroupId, teams: Team[], matches: Match[],
): { minPoints: number; maxPoints: number; teamIds: Set<string> } {
const open = openMatches(group, matches);
const played = matches.filter(
(m) => m.group === group && (m.status === "FINISHED" || m.homeTeamId == null || m.awayTeamId == null),
);
let minP = Infinity, maxP = -Infinity;
const teamIds = new Set<string>();
if (open.length === 0) {
const table = computeGroupTables(teams, matches).find((t) => t.group === group);
const third = table?.rows.find((r) => r.rank === 3);
if (third) { minP = maxP = third.points; teamIds.add(third.teamId); }
return { minPoints: minP, maxPoints: maxP, teamIds };
}
const totalCombos = Math.pow(OUTCOMES.length, open.length);
if (totalCombos > 500) return { minPoints: 0, maxPoints: 9, teamIds };
for (let combo = 0; combo < totalCombos; combo++) {
let c = combo;
const simulated: Match[] = open.map((m) => {
const variantIdx = c % OUTCOMES.length;
c = Math.floor(c / OUTCOMES.length);
const [hg, ag] = OUTCOMES[variantIdx];
return { ...m, status: "FINISHED" as const, homeScore: hg, awayScore: ag };
});
const all = [...played, ...simulated];
const table = computeGroupTables(teams, all).find((t) => t.group === group);
const third = table?.rows.find((r) => r.rank === 3);
if (third) { minP = Math.min(minP, third.points); maxP = Math.max(maxP, third.points); teamIds.add(third.teamId); }
}
return { minPoints: minP === Infinity ? 0 : minP, maxPoints: maxP === -Infinity ? 9 : maxP, teamIds };
}
function buildThirdStates(matches: Match[], teams: Team[]): Map<GroupId, GroupThirdState> {
const states = new Map<GroupId, GroupThirdState>();
for (const g of GROUP_IDS) {
const gm = matches.filter((m) => m.group === g);
const allDone = gm.length > 0 && gm.every((m) => m.status === "FINISHED");
const table = computeGroupTables(teams, matches).find((t) => t.group === g);
const thirdRow = table?.rows.find((r) => r.rank === 3);
let third: ThirdInfo | null = null;
if (thirdRow) third = { teamId: thirdRow.teamId, points: thirdRow.points, goalsFor: thirdRow.goalsFor, goalsAgainst: thirdRow.goalsAgainst, goalDiff: thirdRow.goalDiff };
if (allDone && third) {
states.set(g, { finished: true, third, minPoints: third.points, maxPoints: third.points, possibleTeamIds: new Set([third.teamId]) });
} else {
const { minPoints, maxPoints, teamIds } = enumerateThirdPossibilities(g, teams, matches);
states.set(g, { finished: false, third, minPoints, maxPoints, possibleTeamIds: teamIds });
}
}
return states;
}
function classifyGroups(states: Map<GroupId, GroupThirdState>): {
lockedIn: Set<GroupId>; lockedOut: Set<GroupId>; contested: Set<GroupId>;
} {
const lockedIn = new Set<GroupId>();
const lockedOut = new Set<GroupId>();
const contested = new Set<GroupId>();
for (const g of GROUP_IDS) {
const st = states.get(g)!;
if (st.finished && !st.third) { lockedOut.add(g); continue; }
let countCouldBeBetter = 0;
for (const other of GROUP_IDS) {
if (other === g) continue;
const os = states.get(other)!;
if (os.maxPoints > st.minPoints) countCouldBeBetter++;
else if (os.maxPoints === st.minPoints && !st.finished && os.finished) countCouldBeBetter++;
}
const alwaysTop8 = countCouldBeBetter <= 7;
let countDefinitelyBetter = 0;
for (const other of GROUP_IDS) {
if (other === g) continue;
const os = states.get(other)!;
if (os.minPoints > st.maxPoints) countDefinitelyBetter++;
else if (os.minPoints === st.maxPoints && os.finished && !st.finished) countDefinitelyBetter++;
}
const neverTop8 = countDefinitelyBetter >= 8;
if (alwaysTop8) lockedIn.add(g);
else if (neverTop8) lockedOut.add(g);
else contested.add(g);
}
return { lockedIn, lockedOut, contested };
}
// --- Public API ---
// Liefert die Team-IDs der Dritten, die mathematisch sicher unter den Top 8
// der gruppenübergreifenden Dritten-Tabelle sind. Prüft für jedes Team aus
// einer FERTIGEN Gruppe (played === 3), ob es in ALLEN noch möglichen
// Restspiel-Konstellationen von maximal 7 anderen Dritten überholt werden kann.
export function securelyQualifiedThirdTeams(matches: Match[], teams: Team[]): Set<string> {
const states = buildThirdStates(matches, teams);
const secureTeams = new Set<string>();
for (const g of GROUP_IDS) {
const st = states.get(g)!;
if (!st.finished || !st.third || st.possibleTeamIds.size !== 1) continue;
const my = st.third;
let couldBeBetter = 0;
for (const og of GROUP_IDS) {
if (og === g) continue;
const os = states.get(og)!;
if (os.finished && os.third) {
if (os.third.points > my.points) couldBeBetter++;
else if (os.third.points === my.points && os.third.goalDiff > my.goalDiff) couldBeBetter++;
else if (os.third.points === my.points && os.third.goalDiff === my.goalDiff && os.third.goalsFor > my.goalsFor) couldBeBetter++;
} else {
if (os.maxPoints > my.points) couldBeBetter++;
else if (os.maxPoints === my.points && !os.finished) couldBeBetter++;
}
}
if (couldBeBetter <= 7) secureTeams.add(my.teamId);
}
return secureTeams;
}
// Liefert die Gruppen, deren Dritter mathematisch sicher unter den Top 8 ist.
// (Gruppen-Ebene — für Fix-Markierung im Baum, nicht für Team-Häkchen.)
export function securelyQualifiedThirdGroups(matches: Match[], teams: Team[]): GroupId[] {
const states = buildThirdStates(matches, teams);
const { lockedIn } = classifyGroups(states);
return [...lockedIn];
}
// Prüft, ob ein bestimmter Dritten-Slot (Gegner des Siegers von `winnerGroup`)
// in ALLEN noch möglichen Konstellationen identisch bleibt.
export function thirdSlotIsSecure(winnerGroup: GroupId, matches: Match[], teams: Team[]): boolean {
const states = buildThirdStates(matches, teams);
const { lockedIn, contested } = classifyGroups(states);
if (lockedIn.size > 8) {
// Alle Gruppen fertig oder zu viele lockedIn → die 8 tatsächlich qualifizierten
// Dritten bestimmen (nicht die 12 lockedIn-Gruppen).
const tables = computeGroupTables(teams, matches);
const thirds = computeThirdPlaceTable(tables);
const qGroups = qualifiedThirdGroups(thirds);
if (qGroups.length !== 8) return false;
const assignment = resolveAnnexC(qGroups);
if (!assignment) return false;
const ag = assignment[winnerGroup];
if (!ag) return false;
const ss = states.get(ag);
if (!ss) return false;
return ss.finished && ss.third != null && ss.possibleTeamIds.size === 1;
}
if (lockedIn.size === 8) {
const assignment = resolveAnnexC([...lockedIn]);
if (!assignment) return false;
const ag = assignment[winnerGroup];
if (!ag) return false;
const ss = states.get(ag);
if (!ss) return false;
const result = ss.finished && ss.third != null && ss.possibleTeamIds.size === 1;
return result;
}
if (lockedIn.size + contested.size < 8) return false;
const contestedArr = [...contested];
const need = 8 - lockedIn.size;
const combos = combinations(contestedArr.length, need);
if (combos > 200) return false;
let stableGroup: GroupId | null = null;
for (const indices of enumerateCombinations(contestedArr.length, need)) {
const qGroups: GroupId[] = [...lockedIn, ...indices.map((i) => contestedArr[i])];
if (qGroups.length !== 8) continue;
const assignment = resolveAnnexC(qGroups);
if (!assignment) continue;
const ag = assignment[winnerGroup];
if (!ag) return false;
if (stableGroup === null) stableGroup = ag;
else if (stableGroup !== ag) return false;
}
if (stableGroup === null) return false;
const ss = states.get(stableGroup);
if (!ss) return false;
const result = ss.finished && ss.third != null && ss.possibleTeamIds.size === 1;
return result;
}
// --- Combinatorics helpers ---
function combinations(n: number, k: number): number {
if (k < 0 || k > n) return 0;
if (k === 0 || k === n) return 1;
let r = 1;
for (let i = 1; i <= k; i++) r = r * (n - i + 1) / i;
return Math.round(r);
}
function* enumerateCombinations(n: number, k: number): Generator<number[]> {
if (k === 0) { yield []; return; }
if (k > n) return;
const idx = Array.from({ length: k }, (_, i) => i);
while (true) {
yield [...idx];
let i = k - 1;
while (i >= 0 && idx[i] === n - k + i) i--;
if (i < 0) break;
idx[i]++;
for (let j = i + 1; j < k; j++) idx[j] = idx[j - 1] + 1;
}
}

View File

@@ -21,6 +21,12 @@ export interface Team {
export type MatchStatus =
| "SCHEDULED" | "LIVE" | "IN_PLAY" | "PAUSED" | "FINISHED";
export interface GoalEvent {
scorer: string; // Torschützen-Name
minute: number; // Spielminute
team: "home" | "away";
}
export interface Match {
id: string;
group: GroupId | null; // null = K.o.-Spiel
@@ -37,6 +43,7 @@ export interface Match {
prob?: { home: number; draw: number; away: number } | null;
venue?: string | null; // Austragungsort
attendance?: number | null; // Zuschauerzahl, falls verfügbar
goals?: GoalEvent[] | null; // Torereignisse von worldcup26.ir
}
// Eine berechnete Tabellenzeile innerhalb einer Gruppe.