"use client";

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 { buildSimMatches } from "@/lib/simulation";
import Bracket from "./Bracket";

export default function Simulation({ teams, matches }: { teams: Team[]; matches: Match[] }) {
  // ---- 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]);
  const simAnnex = useMemo(
    () => (simQGroups.length === 8 ? resolveAnnexC(simQGroups) : null),
    [simQGroups],
  );
  const simAnnexResolved = simAnnex != null;

  const simBracket = useMemo(
    () => resolveBracket(simMatches, teams, simTables, simThirds, simAnnex, simAnnexResolved, true),
    [simMatches, teams, simTables, simThirds, simAnnex, simAnnexResolved],
  );

  // Echte Tabellen/Bracket für fix/provisional-Flags (nur tatsächlich FINISHED).
  const realTables = useMemo(() => computeGroupTables(teams, matches), [teams, matches]);
  const realThirds = useMemo(() => computeThirdPlaceTable(realTables), [realTables]);
  const realQGroups = useMemo(() => qualifiedThirdGroups(realThirds), [realThirds]);
  const realAnnex = useMemo(
    () => (realQGroups.length === 8 ? resolveAnnexC(realQGroups) : null),
    [realQGroups],
  );
  const realBracket = useMemo(
    () => resolveBracket(matches, teams, realTables, realThirds, realAnnex, realAnnex != null),
    [matches, teams, realTables, realThirds, realAnnex],
  );

  // R32: provisional-Flags aus dem echten Bracket übernehmen.
  const realProvisional = useMemo(() => {
    const m = new Map<number, { home: boolean; away: boolean }>();
    for (const tie of realBracket.r32) {
      m.set(tie.matchNumber, { home: tie.home.provisional, away: tie.away.provisional });
    }
    return m;
  }, [realBracket]);

  // Folgerunden: decided-Flags aus echten Matches (status === FINISHED).
  const realDecided = useMemo(() => {
    const m = new Map<number, boolean>();
    for (const mt of matches) {
      if (mt.group == null && mt.matchNumber >= 73) {
        m.set(mt.matchNumber, mt.status === "FINISHED");
      }
    }
    return m;
  }, [matches]);

  // Sim-Bracket mit echten provisional-Flags mergen (inkl. Tooltip-Korrektur).
  const preResolved = useMemo(() => {
    const fixTooltip = (t: string | null, prov: boolean): string | null => {
      if (!t) return t;
      if (prov) return t.startsWith("aktuell ") ? t : `aktuell ${t}`;
      return t.startsWith("aktuell ") ? t.slice(8) : t;
    };

    const r32Fixed: ResolvedTie[] = simBracket.r32.map((tie) => {
      const rp = realProvisional.get(tie.matchNumber);
      if (!rp) return tie;
      return {
        ...tie,
        home: { ...tie.home, provisional: rp.home, tooltip: fixTooltip(tie.home.tooltip, rp.home) },
        away: { ...tie.away, provisional: rp.away, tooltip: fixTooltip(tie.away.tooltip, rp.away) },
      };
    });

    const laterFixed: Record<number, ResolvedTie> = {};
    for (const km of LATER_ROUNDS) {
      const tie = simBracket.later[km.matchNumber];
      if (!tie) continue;
      const homeProv = !(realDecided.get(km.fromHome) ?? false);
      const awayProv = !(realDecided.get(km.fromAway) ?? false);
      laterFixed[km.matchNumber] = {
        ...tie,
        home: { ...tie.home, provisional: homeProv },
        away: { ...tie.away, provisional: awayProv },
      };
    }

    return { r32: r32Fixed, later: laterFixed };
  }, [simBracket, realProvisional, realDecided]);

  return (
    <div>
      <div className="notice" style={{ marginBottom: 20 }}>
        Simulation — alle ungespielten Spiele sind mit dem Polymarket-Favoriten
        vorbelegt. Die angezeigten Wahrscheinlichkeiten stammen von Polymarket.
      </div>

      <h3 style={{ fontFamily: "var(--font-display)", fontSize: 15, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--ink-dim)", margin: "0 0 12px" }}>
        Simulierter K.o.-Baum
      </h3>
      <Bracket
        matches={simMatches}
        teams={teams}
        tables={simTables}
        thirds={simThirds}
        assignment={simAnnex}
        annexResolved={simAnnexResolved}
        preResolved={preResolved}
      />
    </div>
  );
}
