// Saison-Tipps + Rennen-Liste + Rennen-Detail screens

function SeasonScreen() {
  const { user, seasonPicks, scoring } = useStore();
  const SEED = window.SEED;
  const myPicks = seasonPicks[user.id] || {};
  const locked = scoring?.seasonLocked === true;

  const setPick = (key, val) => {
    setState(s => ({
      ...s,
      seasonPicks: { ...s.seasonPicks, [user.id]: { ...(s.seasonPicks[user.id] || {}), [key]: val } }
    }));
    window.showToast("✓ Gespeichert");
  };

  const cats = [
    { key: "driverChampion",   label: "Fahrer-Weltmeister",     points: (scoring || SEED.scoring).seasonChampion,     hint: "Wer holt 2026 die WDC-Krone?", kind: "driver" },
    { key: "constructor",      label: "Constructors Champion",  points: (scoring || SEED.scoring).seasonConstructor,  hint: "Welches Team gewinnt die Konstrukteurs-WM?", kind: "team" },
    { key: "destructor",       label: "Destructor",             points: (scoring || SEED.scoring).seasonDestructor,   hint: "Häufigster Crasher / Schadens-Champion", kind: "driver" },
    { key: "driverKicked",     label: "Fahrer wird gekickt",    points: (scoring || SEED.scoring).seasonDriverKicked, hint: "Wer verliert während der Saison sein Cockpit?", kind: "driver" },
    { key: "teamBossKicked",   label: "Teamchef-Wechsel",       points: (scoring || SEED.scoring).seasonTeamBossKicked, hint: "Welches Team trennt sich von seinem Teamchef?", kind: "team" },
    { key: "surprise",         label: "Biggest Surprise",       points: (scoring || SEED.scoring).seasonSurprise,     hint: "Größter positiver Sprung an Punkten/Platzierungen", kind: "driver" },
  ];

  const filled = cats.filter(c => myPicks[c.key]).length;

  return (
    <div className="container col" style={{ gap: 20, paddingBottom: 60 }}>
      <div>
        <button className="tab" onClick={() => setState({ view: "dashboard" })}
                style={{ paddingLeft: 0 }}>← BACK TO PIT</button>
        <SectionH
          title="Saison-Tipps"
          sub="EINMALIG PRO SAISON · VOR SAISONSTART"
          right={<span className={`chip ${filled === 6 ? "chip-good" : "chip-warn"}`}>{filled}/6 ABGEGEBEN</span>}
        />
      </div>

      <div className="card" style={{ padding: "16px 24px" }}>
        <div className="row" style={{ gap: 12 }}>
          <div className={`pulse ${locked ? "warn" : ""}`} style={{ color: locked ? "var(--warn)" : "var(--accent)" }}/>
          <div style={{ flex: 1 }}>
            <div className="h-tag">DEADLINE</div>
            <div style={{ fontSize: 14 }}>
              {locked
                ? "Saison-Tipps sind vom Admin gesperrt. Keine Änderungen mehr möglich."
                : "Saison-Tipps können bis zur Sperrung durch den Admin geändert werden."}
            </div>
          </div>
          {locked
            ? <span className="chip chip-warn">⚠ GELOCKT</span>
            : <span className="chip chip-good">OFFEN</span>}
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "1fr", gap: 16 }}>
        {cats.map(c => (
          <SeasonCard
            key={c.key}
            cat={c}
            value={myPicks[c.key]}
            onChange={v => setPick(c.key, v)}
            locked={locked}
          />
        ))}
      </div>

      <div className="card" style={{ padding: 18, textAlign: "center" }}>
        <div className="h-tag" style={{ marginBottom: 8 }}>STATUS</div>
        <div style={{ fontSize: 15, marginBottom: 12 }}>
          {locked
            ? (filled === 6 ? "Alle Saison-Tipps abgegeben." : `${filled}/6 Tipps abgegeben — Deadline vorbei.`)
            : (filled === 6 ? "Alle Saison-Tipps abgegeben. Du kannst sie noch ändern." : `Noch ${6 - filled} Tipp${6-filled === 1 ? "" : "s"} offen.`)}
        </div>
        <button className="btn btn-primary"
                style={{ justifyContent: "center" }}
                onClick={() => setState({ view: "dashboard" })}>
          ← ZURÜCK
        </button>
      </div>

      <AllSeasonPicksView cats={cats} />
    </div>
  );
}

function SeasonCard({ cat, value, onChange, locked }) {
  const [open, setOpen] = React.useState(false);
  const SEED = window.SEED;
  // Picker: nur aktive Fahrer zeigen; bereits gewählte inaktive Fahrer immer einschließen
  const list = cat.kind === "driver"
    ? SEED.drivers.filter(d => d.active !== false || d.id === value)
    : SEED.teams;
  const selected = value ? (cat.kind === "driver" ? getDriver(value) : getTeam(value)) : null;

  return (
    <div className="card" style={{ padding: 0, overflow: "hidden" }}>
      <div className="spread" style={{ padding: "14px 16px 14px 24px", borderBottom: open ? "1px solid var(--line)" : "none" }}>
        <div style={{ flex: 1 }}>
          <div className="row" style={{ gap: 8 }}>
            <span className="h-tag">+{cat.points} PKT</span>
            {value && <span className="chip chip-good">✓ GETIPPT</span>}
          </div>
          <div style={{ fontFamily: "var(--font-display)", fontSize: 26, marginTop: 4 }}>{cat.label}</div>
          <div className="muted" style={{ fontSize: 12 }}>{cat.hint}</div>
        </div>
        <button className="btn btn-ghost" onClick={() => setOpen(o => !o)} disabled={locked}>
          {open ? "ZU" : (selected ? "ÄNDERN" : "WÄHLEN")}
        </button>
      </div>

      {selected && !open && (
        <div style={{ padding: "12px 16px 12px 24px", background: "var(--bg-2)" }}>
          {cat.kind === "driver" ? (
            <div className="row" style={{ gap: 10 }}>
              <DriverNum num={selected.num} teamId={selected.team} size={32} />
              <div style={{ minWidth: 0 }}>
                <div style={{ fontWeight: 600 }}>
                  {selected.first} {selected.last}
                  {selected.active === false && (
                    <span className="h-mono" style={{ fontSize: 9, color: "var(--bad)", letterSpacing: "0.12em", marginLeft: 6 }}>✕ KEIN COCKPIT</span>
                  )}
                </div>
                <div className="h-mono muted" style={{ fontSize: 10 }}>{getTeam(selected.team).name.toUpperCase()}</div>
              </div>
            </div>
          ) : (
            <div className="row">
              <TeamLogo teamId={selected.id} size={32} />
              <div style={{ fontWeight: 600 }}>{selected.name}</div>
            </div>
          )}
        </div>
      )}

      {open && (
        <div style={{ padding: 12, display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))", gap: 8 }}>
          {list.map(item => (
            cat.kind === "driver" ? (
              <DriverPick key={item.id} driver={item}
                          selected={value === item.id}
                          onClick={() => { onChange(item.id); setOpen(false); }} />
            ) : (
              <TeamPick key={item.id} team={item}
                        selected={value === item.id}
                        onClick={() => { onChange(item.id); setOpen(false); }} />
            )
          ))}
        </div>
      )}
    </div>
  );
}

// -- Race list -----------------------------------------------------------
function RacesScreen() {
  const { raceState, racePicks, results, user } = useStore();
  const SEED = window.SEED;
  const nextRaceId = SEED.calendar.find(r => (raceState[r.id] || "upcoming") !== "finished")?.id;
  const finished = SEED.calendar.filter(r => raceState[r.id] === "finished").length;

  return (
    <div className="container col" style={{ gap: 24, paddingBottom: 60 }}>
      <SectionH
        title="Rennkalender"
        sub={`SAISON ${SEED.season} · ${finished}/${SEED.calendar.length} ABGESCHLOSSEN`}
      />

      <div style={{
        display: "grid",
        gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))",
        gap: 16,
      }}>
        {SEED.calendar.map((r, i) => {
          const st = raceState[r.id] || "upcoming";
          const myPicks = racePicks[r.id]?.[user.id];
          const hasPicks = myPicks && (myPicks.pole || myPicks.winner);
          const isNext = r.id === nextRaceId;
          const res = results[r.id];

          return (
            <div key={r.id}
              onClick={() => setState({ view: "race", currentRaceId: r.id })}
              style={{ cursor: "pointer" }}
            >
              <RaceCard
                race={r} idx={i} st={st}
                hasPicks={hasPicks} isNext={isNext}
                res={res}
              />
            </div>
          );
        })}
      </div>
    </div>
  );
}

function RaceCard({ race, idx, st, hasPicks, isNext, res }) {
  const finished = st === "finished";
  const pole   = res?.pole   ? getDriver(res.pole)   : null;
  const winner = res?.winner ? getDriver(res.winner) : null;

  return (
    <div className="card" style={{
      overflow: "hidden",
      transition: "transform 0.15s ease, box-shadow 0.15s ease",
      outline: isNext ? "2px solid var(--accent)" : "none",
      outlineOffset: "-1px",
    }}
    onMouseEnter={e => { e.currentTarget.style.transform = "translateY(-2px)"; e.currentTarget.style.boxShadow = "0 8px 32px rgba(0,0,0,0.5)"; }}
    onMouseLeave={e => { e.currentTarget.style.transform = ""; e.currentTarget.style.boxShadow = ""; }}
    >
      {/* Karten-Header — dunkles Bild-Ersatz mit Rundenummer */}
      <div style={{
        background: finished
          ? "linear-gradient(135deg, #1a1a2e 0%, #16213e 100%)"
          : isNext
            ? "linear-gradient(135deg, #2a1a1a 0%, #1e1a2e 100%)"
            : "linear-gradient(135deg, var(--bg-2) 0%, var(--bg-3) 100%)",
        padding: "20px 20px 16px",
        position: "relative",
        overflow: "hidden",
        minHeight: 100,
      }}>
        {/* Große Rundenummer als Dekorativ-Element */}
        <div style={{
          position: "absolute", right: -10, top: -10,
          fontFamily: "var(--font-display)", fontSize: 100,
          color: "rgba(255,255,255,0.04)", lineHeight: 1,
          userSelect: "none", pointerEvents: "none",
        }}>
          {String(idx + 1).padStart(2, "0")}
        </div>

        {/* Status-Badge + Sprint oben */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 12 }}>
          <span className="h-tag">RD {String(idx + 1).padStart(2, "0")}</span>
          <div style={{ display: "flex", gap: 6 }}>
            {race.sprint && (
              <span className="chip chip-warn" style={{ fontSize: 9, padding: "3px 8px" }}>SPRINT</span>
            )}
            {isNext && (
              <span className="chip" style={{
                fontSize: 9, padding: "3px 8px",
                background: "var(--accent)", color: "#fff",
                border: "none",
              }}>NÄCHSTES</span>
            )}
          </div>
        </div>

        {/* Land + Name */}
        <div>
          <div style={{
            fontFamily: "var(--font-display)", fontSize: 26, lineHeight: 1,
            color: "var(--ink-0)", marginBottom: 4,
          }}>
            {race.name}
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <FlagDot country={race.country} />
            <span style={{ fontSize: 12, color: "var(--ink-2)" }}>{formatDate(race.date)}</span>
          </div>
        </div>
      </div>

      {/* Karten-Body */}
      <div style={{ padding: "14px 20px 16px" }}>
        <div style={{ fontSize: 12, color: "var(--ink-3)", marginBottom: 10 }}>
          {race.circuit}
        </div>

        {/* Abgeschlossen: Top-Ergebnisse zeigen */}
        {finished && res ? (
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            {pole && (
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span className="h-tag" style={{ width: 40 }}>POLE</span>
                <DriverNum num={pole.num} teamId={pole.team} size={22} />
                <span style={{ fontSize: 13, fontWeight: 600 }}>{pole.last}</span>
              </div>
            )}
            {winner && (
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span className="h-tag" style={{ width: 40 }}>P1</span>
                <DriverNum num={winner.num} teamId={winner.team} size={22} />
                <span style={{ fontSize: 13, fontWeight: 600 }}>{winner.last}</span>
              </div>
            )}
          </div>
        ) : (
          /* Noch nicht ausgewertet: Pick-Status */
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            {hasPicks
              ? <span className="chip chip-good" style={{ fontSize: 9 }}>✓ Tipp abgegeben</span>
              : <span className="chip chip-warn" style={{ fontSize: 9 }}>○ Tipp offen</span>
            }
          </div>
        )}
      </div>

      {/* Footer-Zeile */}
      <div style={{
        padding: "10px 20px",
        borderTop: "1px solid rgba(255,255,255,0.06)",
        display: "flex", alignItems: "center", justifyContent: "space-between",
      }}>
        <span className={`chip ${
          finished ? "" :
          st === "pre-race" ? "chip-warn" :
          isNext && hasPicks ? "chip-good" : ""
        }`} style={{ fontSize: 9, padding: "3px 8px" }}>
          {finished ? "Abgeschlossen" :
           st === "pre-race" ? "Deadline läuft" :
           "Upcoming"}
        </span>
        <span style={{ fontSize: 12, color: "var(--accent)", fontWeight: 700 }}>→</span>
      </div>
    </div>
  );
}

// -- Race detail (tip + after-deadline view) -----------------------------
function RaceScreen() {
  const { currentRaceId, raceState, racePicks, results, user, scoring } = useStore();
  const sc = scoring || SEED.scoring;
  const SEED = window.SEED;
  const race = getRace(currentRaceId);
  if (!race) return null;
  const st = raceState[race.id] || "upcoming";
  const dl = getDeadlines(race);
  const myPicks = racePicks[race.id]?.[user.id] || {};
  const now = useNow(30000);

  // Alle Tipps haben dieselbe Deadline: vor FP1 (Zeit-basiert + raceState als Fallback)
  const allLocked = st === "finished" || now >= dl.fp1;

  const setPick = (key, val) => {
    setState(s => ({
      ...s,
      racePicks: {
        ...s.racePicks,
        [race.id]: {
          ...(s.racePicks[race.id] || {}),
          [user.id]: { ...(s.racePicks[race.id]?.[user.id] || {}), [key]: val }
        }
      }
    }));
    window.showToast("✓ Gespeichert");
  };

  return (
    <div className="container col" style={{ gap: 16, paddingBottom: 60 }}>
      <div>
        <button className="tab" style={{ paddingLeft: 0 }}
                onClick={() => setState({ view: "races" })}>← KALENDER</button>
      </div>

      {/* Hero */}
      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <div style={{
          background: "linear-gradient(135deg, #2a1510 0%, #1a1528 50%, #15151e 100%)",
          padding: "24px 24px 20px",
          position: "relative", overflow: "hidden",
        }}>
          {/* Decorative round number */}
          <div style={{
            position: "absolute", right: -12, top: -16,
            fontFamily: "var(--font-display)", fontSize: 140,
            color: "rgba(225,6,0,0.06)", lineHeight: 1,
            userSelect: "none", pointerEvents: "none",
          }}>
            {String(SEED.calendar.indexOf(race) + 1).padStart(2, "0")}
          </div>
          <div className="h-tag" style={{ marginBottom: 8 }}>
            RD {SEED.calendar.indexOf(race) + 1} · {race.country}
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 6 }}>
            <FlagDot country={race.country} />
            <h1 style={{
              fontFamily: "var(--font-display)", fontSize: 42, margin: 0,
              lineHeight: 1, color: "var(--ink-0)",
            }}>{race.name}</h1>
          </div>
          <div style={{ color: "var(--ink-3)", fontSize: 13 }}>{race.circuit} · {formatDate(race.date)}</div>
          {race.sprint && (
            <span className="chip chip-warn" style={{ marginTop: 12, display: "inline-flex", fontSize: 9 }}>
              SPRINT WEEKEND
            </span>
          )}
        </div>
      </div>

      {st === "finished" ? (
        <RaceResultView race={race} />
      ) : (
        <>
          {/* Pole */}
          <PickSection
            title="Pole Position"
            sub={`+${sc.pole} PKT · DEADLINE: VOR FP1`}
            deadline={dl.fp1}
            locked={allLocked}
            value={myPicks.pole}
            onChange={v => setPick("pole", v)}
            lockMsg={allLocked ? "Wochenende hat begonnen. Tipp gelockt." : null}
          />

          {/* Sprint (if applicable) */}
          {race.sprint && (
            <PickSection
              title="Sprint-Pole"
              sub={`+${sc.sprintPole} PKT · DEADLINE: VOR FP1`}
              deadline={dl.fp1}
              locked={allLocked}
              value={myPicks.sprintPole}
              onChange={v => setPick("sprintPole", v)}
            />
          )}
          {race.sprint && (
            <PickSection
              title="Sprint-Sieger"
              sub={`+${sc.sprintWinner} PKT · DEADLINE: VOR FP1`}
              deadline={dl.fp1}
              locked={allLocked}
              value={myPicks.sprintWinner}
              onChange={v => setPick("sprintWinner", v)}
            />
          )}

          {/* Race winner */}
          <PickSection
            title="Renn-Sieger"
            sub={`+${sc.raceWinner} PKT · DEADLINE: VOR FP1`}
            deadline={dl.fp1}
            locked={allLocked}
            value={myPicks.winner}
            onChange={v => setPick("winner", v)}
          />

          {/* Finishers slider */}
          <FinisherSection
            value={myPicks.finishers}
            onChange={v => setPick("finishers", v)}
            locked={allLocked}
            deadline={dl.fp1}
            scoring={sc}
          />

          {/* Submit / Status */}
          <div className="card" style={{ padding: 20 }}>
            <div style={{ display: "flex", gap: 16, alignItems: "flex-start", marginBottom: 16 }}>
              <div style={{
                width: 40, height: 40, borderRadius: "50%", flexShrink: 0,
                background: allLocked ? "rgba(255,208,0,0.1)" : "rgba(0,210,190,0.1)",
                border: `1px solid ${allLocked ? "var(--warn)" : "var(--good)"}`,
                display: "flex", alignItems: "center", justifyContent: "center",
                fontSize: 18,
              }}>
                {allLocked ? "⏱" : "✎"}
              </div>
              <div>
                <div style={{ fontWeight: 700, fontSize: 14, marginBottom: 4 }}>
                  {allLocked ? "Tipps gesperrt" : "Tipps abgeben"}
                </div>
                <div style={{ color: "var(--ink-2)", fontSize: 13, lineHeight: 1.6 }}>
                  {allLocked
                    ? "Die FP1-Deadline ist abgelaufen. Ergebnisse werden nach dem Rennen eingetragen."
                    : "Tipps werden automatisch gespeichert. Alle Tipps sind für alle Spieler sichtbar."}
                </div>
              </div>
            </div>
            <button className="btn btn-primary" style={{ justifyContent: "center", width: "100%" }}
                    onClick={() => setState({ view: "dashboard" })}>
              ← Zurück zum Pit Wall
            </button>
          </div>

          {/* Always show all picks — visibility before deadline is intentional */}
          <AfterDeadlinePicksView race={race} allLocked={allLocked} />
        </>
      )}
    </div>
  );
}

function PickSection({ title, sub, deadline, locked, value, onChange, lockMsg }) {
  const [open, setOpen] = React.useState(!value);
  const SEED = window.SEED;
  const sel = value ? getDriver(value) : null;

  return (
    <div className="card" style={{ padding: 0, overflow: "hidden", position: "relative" }}>
      <div className="spread" style={{ padding: "14px 16px", borderBottom: "1px solid var(--line)", background: "var(--bg-2)" }}>
        <div>
          <div className="h-tag">{sub}</div>
          <div style={{ fontFamily: "var(--font-display)", fontSize: 26, marginTop: 2 }}>{title}</div>
        </div>
        <div style={{ textAlign: "right" }}>
          {locked ? (
            <span className="chip chip-warn">⚠ GELOCKT</span>
          ) : (
            <Countdown ts={deadline} compact />
          )}
        </div>
      </div>

      {locked && lockMsg && (
        <div className="lock-tape" style={{ padding: "8px 16px", fontSize: 12, fontFamily: "var(--font-mono)", letterSpacing: "0.1em" }}>
          {lockMsg}
        </div>
      )}

      {sel && !open && (
        <div className="spread" style={{ padding: "12px 16px" }}>
          <div className="row" style={{ gap: 10 }}>
            <DriverNum num={sel.num} teamId={sel.team} size={36} />
            <div style={{ minWidth: 0 }}>
              <div style={{ fontWeight: 600 }}>
                {sel.first} {sel.last}
                {sel.active === false && (
                  <span className="h-mono" style={{ fontSize: 9, color: "var(--bad)", letterSpacing: "0.12em", marginLeft: 6 }}>✕ KEIN COCKPIT</span>
                )}
              </div>
              <div className="h-mono muted" style={{ fontSize: 10 }}>{getTeam(sel.team).name.toUpperCase()}</div>
            </div>
          </div>
          {!locked && <button className="btn btn-ghost" onClick={() => setOpen(true)}>ÄNDERN</button>}
        </div>
      )}

      {(!sel || open) && !locked && (
        <div style={{ padding: 12, display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))", gap: 8 }}>
          {SEED.drivers.filter(d => d.active !== false || value === d.id).map(d => (
            <DriverPick key={d.id} driver={d}
                        selected={value === d.id}
                        onClick={() => { onChange(d.id); setOpen(false); }} />
          ))}
        </div>
      )}
    </div>
  );
}

function FinisherSection({ value, onChange, locked, deadline, scoring }) {
  const v = value == null ? 16 : value;
  return (
    <div className="card" style={{ padding: 0, overflow: "hidden" }}>
      <div className="spread" style={{ padding: "14px 16px", borderBottom: "1px solid var(--line)", background: "var(--bg-2)" }}>
        <div>
          <div className="h-tag">+{scoring.finishers} PKT EXAKT · +{scoring.finishersClose} ±1 · DEADLINE: VOR FP1</div>
          <div style={{ fontFamily: "var(--font-display)", fontSize: 26, marginTop: 2 }}>Anzahl Finisher</div>
        </div>
        <div style={{ textAlign: "right" }}>
          {locked ? <span className="chip chip-warn">⚠ GELOCKT</span> : <Countdown ts={deadline} compact />}
        </div>
      </div>
      <div style={{ padding: "20px 18px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 16, marginBottom: 14 }}>
          <span className="h-display" style={{ fontSize: 60, color: value == null ? "var(--ink-3)" : "var(--accent)", lineHeight: 1, minWidth: "2.2ch" }}>{String(v).padStart(2,"0")}</span>
          <div>
            <div className="h-mono" style={{ fontSize: 11, color: "var(--ink-2)", letterSpacing: "0.18em" }}>VON 22</div>
            <div className="muted" style={{ fontSize: 12 }}>Autos beenden Rennen</div>
          </div>
        </div>
        <input type="range" min="0" max="22" step="1"
               value={v}
               disabled={locked}
               onChange={e => onChange(parseInt(e.target.value, 10))}
               style={{ width: "100%", accentColor: "var(--accent)" }} />
        <div className="spread" style={{ marginTop: 6 }}>
          <span className="h-mono muted" style={{ fontSize: 10 }}>0 (DNF-FEST)</span>
          <span className="h-mono muted" style={{ fontSize: 10 }}>22 (CLEAN RACE)</span>
        </div>
      </div>
    </div>
  );
}

function AfterDeadlinePicksView({ race, allLocked }) {
  const { racePicks } = useStore();
  const picks = racePicks[race.id] || {};
  const SEED = window.SEED;

  return (
    <div>
      <SectionH title="Alle Tipps" sub={allLocked ? "DEADLINE ABGELAUFEN · ALLE TIPPS SICHTBAR" : "LIVE · ALLE SPIELER IM ÜBERBLICK"} />
      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        {SEED.players.map((p, i) => {
          const pk = picks[p.id] || {};
          const hasAny = pk.pole || pk.winner || pk.sprintWinner || pk.finishers != null;
          return (
            <div key={p.id} style={{
              display: "grid", gridTemplateColumns: "auto 1fr",
              gap: 12, alignItems: "center",
              padding: "12px 14px",
              borderBottom: i === SEED.players.length - 1 ? "none" : "1px solid var(--line)",
              background: p.you ? "oklch(0.82 0.16 210 / 0.06)" : "transparent",
            }}>
              <Avatar player={p} size={32} />
              <div style={{ minWidth: 0 }}>
                <div style={{ fontWeight: 600 }}>
                  {p.name}
                  {p.you && <span className="h-mono" style={{ fontSize: 10, color: "var(--accent)", marginLeft: 8, letterSpacing: "0.15em" }}>YOU</span>}
                </div>
                <div className="h-mono" style={{ fontSize: 10, color: "var(--ink-2)", marginTop: 2 }}>
                  {hasAny ? [
                    `POLE ${pk.pole ? (getDriver(pk.pole)?.code ?? "?") : "—"}`,
                    `RACE ${pk.winner ? (getDriver(pk.winner)?.code ?? "?") : "—"}`,
                    race.sprint && pk.sprintPole ? `SPOLE ${getDriver(pk.sprintPole)?.code ?? "?"}` : null,
                    race.sprint && pk.sprintWinner ? `SPR ${getDriver(pk.sprintWinner)?.code ?? "?"}` : null,
                    pk.finishers != null ? `FIN ${pk.finishers}` : null,
                  ].filter(Boolean).join(" · ") : "KEINE TIPPS ABGEGEBEN"}
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function AllSeasonPicksView({ cats }) {
  const { seasonPicks } = useStore();
  const SEED = window.SEED;

  return (
    <div>
      <SectionH title="Alle Saison-Tipps" sub="LIVE · ALLE SPIELER IM ÜBERBLICK" />
      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <div style={{ overflowX: "auto" }}>
        {/* Header-Zeile */}
        <div style={{
          display: "grid",
          gridTemplateColumns: `140px repeat(${cats.length}, minmax(72px, 1fr))`,
          gap: 0,
          background: "var(--bg-2)",
          borderBottom: "1px solid var(--line)",
          padding: "8px 14px",
          minWidth: 580,
        }}>
          <div className="h-tag">SPIELER</div>
          {cats.map(c => (
            <div key={c.key} className="h-tag" style={{ fontSize: 9, textAlign: "center", padding: "0 4px" }}>
              {c.label.toUpperCase()}
            </div>
          ))}
        </div>

        {SEED.players.map((p, i) => {
          const pk = seasonPicks[p.id] || Object.create(null);
          return (
            <div key={p.id} style={{
              display: "grid",
              gridTemplateColumns: `140px repeat(${cats.length}, minmax(72px, 1fr))`,
              gap: 0,
              alignItems: "center",
              padding: "10px 14px",
              borderBottom: i === SEED.players.length - 1 ? "none" : "1px solid var(--line)",
              background: p.you ? "oklch(0.82 0.16 210 / 0.06)" : "transparent",
              minWidth: 580,
            }}>
              <div className="row" style={{ gap: 8 }}>
                <Avatar player={p} size={28} />
                <div style={{ fontWeight: 600, fontSize: 13, minWidth: 0 }}>
                  {p.name}
                  {p.you && <span className="h-mono" style={{ fontSize: 9, color: "var(--accent)", marginLeft: 6, letterSpacing: "0.15em" }}>DU</span>}
                </div>
              </div>
              {cats.map(c => {
                const val = pk[c.key];
                const item = val ? (c.kind === "driver" ? getDriver(val) : getTeam(val)) : null;
                return (
                  <div key={c.key} style={{ textAlign: "center", padding: "0 4px" }}>
                    {item ? (
                      c.kind === "driver" ? (
                        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 2 }}>
                          <DriverNum num={item.num} teamId={item.team} size={24} />
                          <span className="h-mono" style={{ fontSize: 9, color: "var(--ink-2)" }}>{item.code}</span>
                        </div>
                      ) : (
                        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 2 }}>
                          <TeamLogo teamId={item.id} size={24} />
                          <span className="h-mono" style={{ fontSize: 9, color: "var(--ink-2)" }}>{item.short}</span>
                        </div>
                      )
                    ) : (
                      <span className="h-mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>—</span>
                    )}
                  </div>
                );
              })}
            </div>
          );
        })}
        </div>
      </div>
    </div>
  );
}

// -- After-race result view ----------------------------------------------
function RaceResultView({ race }) {
  const { results, racePicks, user } = useStore();
  const res = results[race.id];
  const picks = racePicks[race.id] || {};
  const SEED = window.SEED;
  const { totals, scoring } = computeScores();

  if (!res) {
    return (
      <div className="card" style={{ padding: 24, textAlign: "center" }}>
        <div className="h-tag" style={{ marginBottom: 8 }}>KEINE ERGEBNISSE</div>
        <div className="muted" style={{ fontSize: 13 }}>
          Für dieses Rennen sind noch keine Ergebnisse verfügbar.
        </div>
      </div>
    );
  }

  const playerRows = SEED.players.map(p => {
    const pk = picks[p.id] || {};
    let pts = 0; const breakdown = [];
    if (res.pole && pk.pole === res.pole) { pts += scoring.pole; breakdown.push(`+${scoring.pole} POLE`); }
    if (res.winner && pk.winner === res.winner) { pts += scoring.raceWinner; breakdown.push(`+${scoring.raceWinner} SIEGER`); }
    if (race.sprint && res.sprintPole && pk.sprintPole === res.sprintPole) { const sp = scoring.sprintPole || 0; pts += sp; breakdown.push(`+${sp} S-POLE`); }
    if (race.sprint && res.sprintWinner && pk.sprintWinner === res.sprintWinner) { pts += scoring.sprintWinner; breakdown.push(`+${scoring.sprintWinner} SPRINT`); }
    if (res.finishers != null && pk.finishers != null) {
      if (pk.finishers === res.finishers) { pts += scoring.finishers; breakdown.push(`+${scoring.finishers} FINISHER`); }
      else if (Math.abs(pk.finishers - res.finishers) === 1) { pts += scoring.finishersClose; breakdown.push(`+${scoring.finishersClose} FINISHER ±1`); }
    }
    return { p, pk, pts, breakdown };
  }).sort((a,b) => b.pts - a.pts);

  return (
    <>
      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <div className="row" style={{ padding: "12px 16px", background: "var(--good)", color: "#001810" }}>
          <span className="pulse live" style={{ background: "#001810" }}/>
          <span className="h-mono" style={{ fontSize: 11, letterSpacing: "0.18em" }}>OFFIZIELLES ERGEBNIS</span>
        </div>
        <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 0 }}>
          <ResultCell label="POLE" driverId={res?.pole} />
          <ResultCell label="SIEGER" driverId={res?.winner} />
          {race.sprint && <ResultCell label="S-POLE" driverId={res?.sprintPole} />}
          {race.sprint && <ResultCell label="SPRINT" driverId={res?.sprintWinner} />}
          <ResultCell label="FINISHER" value={res?.finishers != null ? `${res.finishers}/22` : "—"} />
        </div>
      </div>

      <div>
        <SectionH title="Punkte des Rennens" sub="WER HAT WAS GETIPPT" />
        <div className="card" style={{ padding: 0, overflow: "hidden" }}>
          {playerRows.map((row, i) => (
            <div key={row.p.id} style={{
              display: "grid",
              gridTemplateColumns: "36px auto 1fr auto",
              gap: 12, alignItems: "center",
              padding: "12px 14px",
              borderBottom: i === playerRows.length - 1 ? "none" : "1px solid var(--line)",
              background: row.p.you ? "oklch(0.82 0.16 210 / 0.06)" : "transparent",
            }}>
              <span className="h-display" style={{ fontSize: 22, textAlign: "center", color: i === 0 ? "var(--accent)" : "var(--ink-2)" }}>
                {String(i+1).padStart(2,"0")}
              </span>
              <Avatar player={row.p} size={32}/>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontWeight: 600 }}>{row.p.name}{row.p.you && <span className="h-mono" style={{ fontSize: 10, color: "var(--accent)", marginLeft: 8, letterSpacing: "0.15em" }}>YOU</span>}</div>
                <div className="h-mono" style={{ fontSize: 10, color: "var(--ink-2)", marginTop: 2 }}>
                  POLE {row.pk.pole ? (getDriver(row.pk.pole)?.code ?? "?") : "—"} ·
                  RACE {row.pk.winner ? (getDriver(row.pk.winner)?.code ?? "?") : "—"}
                  {race.sprint && row.pk.sprintPole ? ` · SPOLE ${getDriver(row.pk.sprintPole)?.code ?? "?"}` : ""}
                  {race.sprint && row.pk.sprintWinner ? ` · SPR ${getDriver(row.pk.sprintWinner)?.code ?? "?"}` : ""}
                  {row.pk.finishers != null ? ` · FIN ${row.pk.finishers}` : ""}
                </div>
              </div>
              <div style={{ textAlign: "right" }}>
                <div className="tnum" style={{ fontSize: 22, color: row.pts > 0 ? "var(--good)" : "var(--ink-3)" }}>+{row.pts}</div>
                {row.breakdown.length > 0 && (
                  <div className="h-mono" style={{ fontSize: 9, color: "var(--ink-2)" }}>{row.breakdown.join(" · ")}</div>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
    </>
  );
}

Object.assign(window, { SeasonScreen, RacesScreen, RaceScreen });
