// Leaderboard, Admin, Datamodel screens

function LeaderboardScreen() {
  const [expanded, setExpanded] = React.useState(null);
  const SEED = window.SEED;
  const { totals } = computeScores();
  const finishedRaces = SEED.calendar.filter(r => getState().raceState[r.id] === "finished");

  const ranked = SEED.players.map(p => ({
    p, score: totals[p.id].total,
  })).sort((a, b) => b.score - a.score);

  ranked.forEach((row, i) => {
    row.rank = i === 0 || row.score < ranked[i - 1].score ? i + 1 : ranked[i - 1].rank;
  });

  const podiumColors = { 1: "#FFD700", 2: "#C0C0C0", 3: "#CD7F32" };

  return (
    <div className="container col" style={{ gap: 20, paddingBottom: 60 }}>
      <SectionH title="Tabelle" sub="CHAMPIONSHIP STANDINGS" />

      {/* Podium */}
      {ranked.length >= 3 && (
        <div className="card" style={{ padding: 0, overflow: "hidden" }}>
          <div style={{ padding: "12px 20px", borderBottom: "1px solid rgba(255,255,255,0.06)", display: "flex", alignItems: "center", gap: 8 }}>
            <div className="h-tag">Podium</div>
            {ranked[0]?.rank === ranked[1]?.rank && (
              <span className="chip chip-warn" style={{ fontSize: 9 }}>GLEICHSTAND</span>
            )}
          </div>
          <div style={{
            display: "grid", gridTemplateColumns: "1fr 1.15fr 1fr",
            gap: 1, background: "rgba(255,255,255,0.04)",
          }}>
            {[ranked[1], ranked[0], ranked[2]].map((row, idx) => {
              const place = row.rank;
              const isFirst = place === 1;
              return (
                <div key={row.p.id} style={{
                  background: isFirst ? "rgba(225,6,0,0.06)" : "var(--bg-1)",
                  padding: "24px 16px 20px",
                  textAlign: "center",
                  display: "flex", flexDirection: "column", alignItems: "center", gap: 8,
                }}>
                  <div style={{
                    width: 48, height: 48, borderRadius: "50%",
                    background: "var(--bg-3)",
                    border: `2px solid ${podiumColors[place]}`,
                    display: "flex", alignItems: "center", justifyContent: "center",
                    fontSize: 24,
                  }}>
                    {row.p.avatar || row.p.name?.[0]}
                  </div>
                  <div style={{ fontWeight: 700, fontSize: 14 }}>{row.p.name}</div>
                  <div style={{
                    fontFamily: "var(--font-display)", fontSize: 48,
                    color: podiumColors[place], lineHeight: 1,
                  }}>P{place}</div>
                  <div style={{
                    fontFamily: "var(--font-mono)", fontSize: 16,
                    color: "var(--ink-1)", fontWeight: 600,
                  }}>{row.score} <span style={{ fontSize: 11, color: "var(--ink-3)" }}>PKT</span></div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Standings-Tabelle */}
      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        {ranked.map((row, i) => {
          const isMe = row.p.id === useStore.getState?.()?.user?.id || row.p.you;
          const isExpanded = expanded === row.p.id;
          return (
            <div key={row.p.id}>
              <div className={`lb-row ${isMe ? "you" : ""}`}
                   style={{ cursor: "pointer" }}
                   onClick={() => setExpanded(isExpanded ? null : row.p.id)}>

                {/* Rang */}
                <div className={`rk ${row.rank === 1 ? "top1" : ""}`}
                     style={{ fontFamily: "var(--font-display)", fontSize: 24, textAlign: "center", lineHeight: 1 }}>
                  {row.rank}
                </div>

                {/* Name + Avatar */}
                <div style={{ display: "flex", alignItems: "center", gap: 12, minWidth: 0 }}>
                  <div style={{
                    width: 36, height: 36, borderRadius: "50%",
                    background: "var(--bg-3)", border: "1px solid rgba(255,255,255,0.1)",
                    display: "flex", alignItems: "center", justifyContent: "center",
                    fontSize: 18, flexShrink: 0,
                  }}>
                    {row.p.avatar || row.p.name?.[0]}
                  </div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontWeight: 700, fontSize: 14 }}>
                      {row.p.name}
                      {isMe && <span style={{
                        marginLeft: 8, fontSize: 9, fontWeight: 700,
                        background: "var(--accent)", color: "#fff",
                        padding: "2px 6px", borderRadius: 10,
                        fontFamily: "var(--font-ui)", letterSpacing: "0.08em",
                      }}>DU</span>}
                    </div>
                    <div className="h-tag" style={{ marginTop: 2 }}>
                      {finishedRaces.length} Rennen gewertet
                    </div>
                  </div>
                </div>

                {/* Punkte */}
                <div style={{ textAlign: "right" }}>
                  <div style={{ fontFamily: "var(--font-display)", fontSize: 28, lineHeight: 1, color: row.rank === 1 ? "var(--accent)" : "var(--ink-0)" }}>
                    {row.score}
                  </div>
                  <div className="h-tag">PKT</div>
                  {row.rank !== 1 && (
                    <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--ink-3)", marginTop: 1 }}>
                      {ranked[0].score - row.score} PKT auf P1
                    </div>
                  )}
                </div>

                {/* Expand-Button */}
                <div style={{
                  width: 28, height: 28, borderRadius: "50%",
                  background: isExpanded ? "var(--accent)" : "rgba(255,255,255,0.06)",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  fontSize: 12, color: isExpanded ? "#fff" : "var(--ink-2)",
                  flexShrink: 0, transition: "all 0.15s ease",
                }}>
                  {isExpanded ? "▲" : "▼"}
                </div>
              </div>

              {/* Aufschlüsselung */}
              {isExpanded && (
                <div style={{
                  background: "rgba(0,0,0,0.25)",
                  borderBottom: "1px solid rgba(255,255,255,0.06)",
                  padding: "16px 20px",
                }}>
                  <div className="h-tag" style={{ marginBottom: 12 }}>Punkte pro Rennen</div>
                  {finishedRaces.length === 0 ? (
                    <div className="muted" style={{ fontSize: 12 }}>Noch keine abgeschlossenen Rennen.</div>
                  ) : (
                    <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                      {finishedRaces.map(r => {
                        const pts = totals[row.p.id]?.byRace[r.id] || 0;
                        const bk = totals[row.p.id]?.byRaceBreakdown?.[r.id] || {};
                        const hasPick = !!(getState().racePicks[r.id]?.[row.p.id]);
                        const scored = hasPick ? [
                          bk.pole           ? "POLE"   : null,
                          bk.raceWinner     ? "WIN"    : null,
                          bk.sprintPole     ? "SPR-P"  : null,
                          bk.sprintWinner   ? "SPRINT" : null,
                          bk.finishers      ? "FIN"    : null,
                          bk.finishersClose ? "FIN\xb11" : null,
                        ].filter(Boolean) : [];
                        return (
                          <div key={r.id} style={{
                            background: "var(--bg-2)",
                            border: "1px solid rgba(255,255,255,0.07)",
                            borderRadius: 8,
                            borderTop: `3px solid ${pts > 0 ? "var(--good)" : hasPick ? "rgba(255,255,255,0.07)" : "rgba(255,180,0,0.25)"}`,
                            padding: "8px 12px", minWidth: 72, textAlign: "center",
                            opacity: hasPick ? 1 : 0.55,
                          }}>
                            <div className="h-tag" style={{ fontSize: 9 }}>
                              {r.name.replace(" Grand Prix","").replace(" GP","")}
                            </div>
                            <div style={{
                              fontFamily: "var(--font-display)", fontSize: 22, lineHeight: 1,
                              color: pts > 0 ? "var(--good)" : "var(--ink-3)", marginTop: 4,
                            }}>{hasPick ? "+" + pts : "—"}</div>
                            {!hasPick && (
                              <div style={{ fontSize: 8, color: "var(--warn)", fontFamily: "var(--font-mono)", marginTop: 3, opacity: 0.8 }}>KEIN TIPP</div>
                            )}
                            {scored.length > 0 && (
                              <div style={{ marginTop: 5, display: "flex", flexDirection: "column", gap: 2, alignItems: "center" }}>
                                {scored.map(label => (
                                  <span key={label} style={{
                                    fontSize: 8, fontFamily: "var(--font-mono)",
                                    color: "var(--good)", letterSpacing: "0.05em",
                                  }}>{label}</span>
                                ))}
                              </div>
                            )}
                          </div>
                        );
                      })}
                    </div>
                  )}
                  {totals[row.p.id]?.season > 0 && (
                    <div style={{ marginTop: 12 }}>
                      <div className="h-tag" style={{ marginBottom: 8 }}>Saison-Bonus</div>
                      <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                        {Object.entries(totals[row.p.id].seasonBreakdown || {}).map(([key, pts]) => {
                          const label = ({ driverChampion: "WDC", constructor: "WCC", destructor: "DESTRUCTOR", driverKicked: "FAHRER RAUS", teamBossKicked: "BOSS RAUS", surprise: "SURPRISE" })[key] || key;
                          return (
                            <div key={key} style={{
                              background: "var(--bg-2)", border: "1px solid rgba(255,255,255,0.07)",
                              borderRadius: 8, borderTop: "3px solid var(--good)",
                              padding: "6px 10px", textAlign: "center",
                            }}>
                              <div className="h-tag" style={{ fontSize: 9 }}>{label}</div>
                              <div style={{ fontFamily: "var(--font-display)", fontSize: 18, color: "var(--good)", lineHeight: 1, marginTop: 2 }}>+{pts}</div>
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  )}
                </div>
              )}
            </div>
          );
        })}
      </div>

    </div>
  );
}

// -- Announcement admin section ------------------------------------------
function AnnouncementAdminSection({ scoring }) {
  const SEED = window.SEED;
  const current = scoring?.announcement || null;
  const [draft, setDraft] = React.useState(current?.text || "");

  const save = () => {
    if (!draft.trim()) return;
    setState(s => ({
      ...s,
      scoring: {
        ...(s.scoring || SEED.scoring),
        announcement: { id: Date.now().toString(), text: draft.trim() },
      },
    }));
    showToast("✓ Nachricht veröffentlicht");
  };

  const clear = () => {
    setDraft("");
    setState(s => ({
      ...s,
      scoring: { ...(s.scoring || SEED.scoring), announcement: null },
    }));
    showToast("Nachricht entfernt");
  };

  return (
    <div className="card" style={{ padding: 0, overflow: "hidden" }}>
      <div style={{ padding: "14px 16px", background: "var(--bg-2)", borderBottom: "1px solid var(--line)" }}>
        <div className="h-tag">INFO-BANNER · WIRD ALLEN SPIELERN ANGEZEIGT</div>
        <div style={{ fontFamily: "var(--font-display)", fontSize: 24, marginTop: 2 }}>Ankündigung</div>
      </div>
      <div style={{ padding: 16, display: "flex", flexDirection: "column", gap: 12 }}>
        {current && (
          <div style={{ fontSize: 12, color: "var(--good)", fontFamily: "var(--font-mono)", letterSpacing: "0.08em" }}>
            ● AKTIV: „{current.text}"
          </div>
        )}
        <textarea
          className="input"
          rows={3}
          placeholder="Nachricht eingeben… z.B. Neu: Sprint-Pole tippen jetzt möglich!"
          value={draft}
          onChange={e => setDraft(e.target.value)}
          style={{ resize: "vertical", fontFamily: "var(--font-ui)", fontSize: 14, lineHeight: 1.5 }}
        />
        <div style={{ display: "flex", gap: 8 }}>
          <button className="btn btn-primary" onClick={save} disabled={!draft.trim()}>
            VERÖFFENTLICHEN
          </button>
          {current && (
            <button className="btn btn-ghost" onClick={clear} style={{ color: "var(--bad)" }}>
              ENTFERNEN
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

// -- Admin ---------------------------------------------------------------
function ApiSyncSection() {
  const [status, setStatus]   = React.useState('idle');   // idle | loading | done | error
  const [message, setMessage] = React.useState('');
  const [syncedCount, setSyncedCount] = React.useState(null);
  const [lastSync, setLastSync]       = React.useState(null);

  const sync = async () => {
    if (status === 'loading') return;
    setStatus('loading');
    setMessage('');
    try {
      const [, { results, raceState, count }] = await Promise.all([
        window.f1Api.syncDrivers(setMessage),
        window.f1Api.syncSeason(setMessage),
      ]);
      setState(s => ({
        ...s,
        results:   { ...s.results,   ...results   },
        raceState: { ...s.raceState, ...raceState },
      }));
      setSyncedCount(count);
      setLastSync(new Date().toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' }));
      setStatus('done');
    } catch (err) {
      setStatus('error');
      setMessage(err.message || 'Unbekannter Fehler');
    }
  };

  const statusColor = { idle: 'var(--ink-2)', loading: 'var(--accent)', done: 'var(--good)', error: 'var(--bad)' }[status];
  const statusIcon  = { idle: '○', loading: '◉', done: '✓', error: '✕' }[status];

  return (
    <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
      <div style={{ padding: '14px 16px', background: 'var(--bg-2)', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <div className="h-tag">JOLPICA F1-API · LÄUFT AUTOMATISCH BEI LOGIN</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 24, marginTop: 2 }}>Ergebnis-Sync</div>
        </div>
        <span className="chip chip-cyan" style={{ fontSize: 10 }}>AUTO</span>
      </div>
      <div style={{ padding: '14px 16px' }}>
        <div style={{ fontSize: 13, color: 'var(--ink-1)', marginBottom: 14, lineHeight: 1.6 }}>
          Pole, Sieger, Sprint-Sieger und Finisher-Anzahl werden beim Admin-Login automatisch
          von der <strong style={{ color: 'var(--ink-0)' }}>Jolpica F1-API</strong> geladen
          und in der Datenbank gespeichert. Manuell auslösbar bei Bedarf.
        </div>

        {(status !== 'idle' || lastSync) && (
          <div style={{
            padding: '8px 12px', marginBottom: 12,
            background: 'var(--bg-3)', borderLeft: `3px solid ${statusColor}`,
            fontSize: 12, color: statusColor, fontFamily: 'var(--font-mono)',
            letterSpacing: '0.06em', lineHeight: 1.7,
          }}>
            <span style={{ marginRight: 8 }}>{statusIcon}</span>
            {status === 'loading' && (message || 'Lade...')}
            {status === 'done'    && `${syncedCount} Rennen synchronisiert · Stand ${lastSync}`}
            {status === 'error'   && message}
          </div>
        )}

        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <button className="btn btn-ghost" onClick={sync} disabled={status === 'loading'}>
            {status === 'loading' ? '⏳  LADE DATEN...' : '↻  JETZT SYNCHRONISIEREN'}
          </button>
        </div>

        <div className="h-mono" style={{ marginTop: 12, fontSize: 10, color: 'var(--ink-3)' }}>
          QUELLE: api.jolpi.ca/ergast/f1 · KEIN ECHTZEIT-FEED · DATEN ERSCHEINEN ~1H NACH RENNENDE
        </div>
      </div>
    </div>
  );
}

function AdminScreen() {
  const SEED = window.SEED;
  const { results, raceState, scoring } = useStore();
  const cur = scoring || SEED.scoring;

  const [editingRace, setEditingRace] = React.useState(null);
  const finished = SEED.calendar.filter(r => raceState[r.id] === "finished");

  return (
    <div className="container col" style={{ gap: 16, paddingBottom: 60 }}>
      <SectionH title="Admin" sub="ERGEBNIS-EINGABE & PUNKTE-KONFIG" right={<span className="chip chip-cyan">ROLLE: ADMIN</span>} />

      {/* Scoring config */}
      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <div style={{ padding: "14px 16px", background: "var(--bg-2)", borderBottom: "1px solid var(--line)" }}>
          <div className="h-tag">PUNKTE-KONFIGURATION · DEFAULT WERTE</div>
          <div style={{ fontFamily: "var(--font-display)", fontSize: 24, marginTop: 2 }}>Scoring-Tabelle</div>
        </div>
        <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))", gap: 0 }}>
          {[
            ["pole", "Pole Position", "pro Rennen"],
            ["raceWinner", "Renn-Sieger", "pro Rennen"],
            ["sprintPole", "Sprint-Pole", "Sprint-Wochenenden"],
            ["sprintWinner", "Sprint-Sieger", "Sprint-Wochenenden"],
            ["finishers", "Finisher (exakt)", "pro Rennen"],
            ["finishersClose", "Finisher (±1)", "Trostpreis"],
            ["seasonChampion", "Fahrer-WM", "einmalig pro Saison"],
            ["seasonConstructor", "Constructors", "einmalig pro Saison"],
            ["seasonDestructor", "Destructor", "einmalig pro Saison"],
            ["seasonDriverKicked", "Fahrer gekickt", "einmalig pro Saison"],
            ["seasonTeamBossKicked", "Teamchef gekickt", "einmalig pro Saison"],
            ["seasonSurprise", "Biggest Surprise", "einmalig pro Saison"],
          ].map(([k, l, hint]) => (
            <div key={k} style={{ padding: "12px 14px", borderTop: "1px solid var(--line)", borderRight: "1px solid var(--line)" }}>
              <div className="h-tag">{hint}</div>
              <div style={{ fontWeight: 600, fontSize: 14, marginTop: 2 }}>{l}</div>
              <div className="row" style={{ marginTop: 8, gap: 6 }}>
                <input
                  type="number" min="0" max="99"
                  className="input tnum" style={{ width: 64, padding: "6px 8px", fontSize: 16 }}
                  value={cur[k]}
                  onChange={e => {
                    const v = parseInt(e.target.value, 10) || 0;
                    setState(s => ({ ...s, scoring: { ...(s.scoring || SEED.scoring), [k]: v } }));
                  }}
                />
                <span className="h-mono" style={{ fontSize: 11, color: "var(--ink-2)" }}>PKT</span>
              </div>
            </div>
          ))}
        </div>
        <div style={{ padding: 12, borderTop: "1px solid var(--line)", display: "flex", justifyContent: "flex-end", gap: 8 }}>
          <button className="btn btn-ghost" onClick={() => setState({ scoring: null })}>DEFAULTS WIEDERHERSTELLEN</button>
        </div>
      </div>

      {/* Season Picks Lock */}
      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <div style={{ padding: "14px 16px", background: "var(--bg-2)", borderBottom: "1px solid var(--line)" }}>
          <div className="h-tag">SAISON-TIPPS</div>
          <div style={{ fontFamily: "var(--font-display)", fontSize: 24, marginTop: 2 }}>Abstimmungs-Lock</div>
        </div>
        <div className="spread" style={{ padding: "16px 16px", alignItems: "center" }}>
          <div>
            <div style={{ fontSize: 14, marginBottom: 4 }}>
              {scoring?.seasonLocked
                ? "Saison-Tipps sind gesperrt."
                : "Saison-Tipps sind offen — Spieler können noch ändern."}
            </div>
            <div className="muted" style={{ fontSize: 12 }}>
              Gesperrt: Niemand kann Saison-Tipps mehr abgeben oder ändern.
            </div>
          </div>
          <button
            className={`btn ${scoring?.seasonLocked ? "btn-ghost" : "btn-primary"}`}
            onClick={() => setState(s => ({
              ...s,
              scoring: { ...(s.scoring || SEED.scoring), seasonLocked: !s.scoring?.seasonLocked }
            }))}
          >
            {scoring?.seasonLocked ? "ENTSPERREN" : "SPERREN"}
          </button>
        </div>
      </div>

      {/* Announcement */}
      <AnnouncementAdminSection scoring={scoring} />

      {/* API Sync */}
      <ApiSyncSection />

      {/* Manuelle Korrekturen */}
      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <div style={{ padding: "14px 16px", background: "var(--bg-2)", borderBottom: "1px solid var(--line)" }}>
          <div className="h-tag">FALLBACK · NUR BEI API-FEHLERN</div>
          <div style={{ fontFamily: "var(--font-display)", fontSize: 24, marginTop: 2 }}>Manuelle Korrekturen</div>
        </div>
        <div style={{ padding: "10px 16px" }}>
          {finished.length === 0 && (
            <div className="muted" style={{ padding: "10px 0", fontSize: 13 }}>Noch keine abgeschlossenen Rennen.</div>
          )}
          {finished.map(r => (
            <div key={r.id} className="spread" style={{ padding: "10px 0", borderBottom: "1px solid var(--bg-3)" }}>
              <div>
                <span style={{ fontWeight: 600 }}>{r.name}</span>
                <span className="h-mono muted" style={{ fontSize: 11, marginLeft: 10 }}>
                  POLE: {results[r.id]?.pole ? getDriver(results[r.id].pole)?.code ?? "?" : "—"} ·
                  WIN: {results[r.id]?.winner ? getDriver(results[r.id].winner)?.code ?? "?" : "—"}
                  {r.sprint ? ` · SPOLE: ${results[r.id]?.sprintPole ? getDriver(results[r.id].sprintPole)?.code ?? "?" : "—"}` : ""}
                </span>
              </div>
              <button className="btn btn-ghost" onClick={() => setEditingRace(r.id)}>KORRIGIEREN</button>
            </div>
          ))}
        </div>
      </div>

      {editingRace && <ResultModal raceId={editingRace} close={() => setEditingRace(null)} />}

      {/* Saison-Ergebnisse */}
      <SeasonResultsSection scoring={scoring} />

      {/* Neustart */}
      <ResetSection />

      {/* Spielerverwaltung */}
      <PlayerManagement />
    </div>
  );
}

function ResultModal({ raceId, close }) {
  const SEED = window.SEED;
  const race = getRace(raceId);
  const cur = useStore(s => s.results[raceId]) || { pole: null, winner: null, sprintWinner: null, finishers: 18 };
  const [draft, setDraft] = React.useState(cur);

  const save = () => {
    setState(s => ({
      ...s,
      results: { ...s.results, [raceId]: draft },
      raceState: { ...s.raceState, [raceId]: "finished" }
    }));
    close();
  };

  return (
    <div onClick={close} style={{
      position: "fixed", inset: 0, background: "rgba(0,0,0,0.7)", zIndex: 100,
      display: "grid", placeItems: "center", padding: 16, overflowY: "auto",
    }}>
      <div onClick={e => e.stopPropagation()} className="card"
           style={{ width: "100%", maxWidth: 520, padding: 0, overflow: "hidden" }}>
        <div style={{
          background: "linear-gradient(135deg, #2a1510 0%, #1a1528 100%)",
          padding: "18px 20px", borderBottom: "1px solid rgba(255,255,255,0.06)",
          position: "relative", overflow: "hidden",
        }}>
          <div style={{
            position: "absolute", right: -8, top: -12,
            fontFamily: "var(--font-display)", fontSize: 80,
            color: "rgba(225,6,0,0.08)", lineHeight: 1,
            userSelect: "none", pointerEvents: "none",
          }}>RES</div>
          <div className="h-tag">ERGEBNIS · {race.country}</div>
          <div style={{ fontFamily: "var(--font-display)", fontSize: 26, marginTop: 4 }}>{race.name}</div>
        </div>
        <div className="col" style={{ padding: 18, gap: 14 }}>
          <DriverSelect label="POLE POSITION" value={draft.pole} onChange={v => setDraft({...draft, pole: v})} />
          {race.sprint && <DriverSelect label="SPRINT-POLE" value={draft.sprintPole} onChange={v => setDraft({...draft, sprintPole: v})} />}
          {race.sprint && <DriverSelect label="SPRINT-SIEGER" value={draft.sprintWinner} onChange={v => setDraft({...draft, sprintWinner: v})} />}
          <DriverSelect label="RENN-SIEGER" value={draft.winner} onChange={v => setDraft({...draft, winner: v})} />
          <div>
            <div className="h-tag" style={{ marginBottom: 6 }}>FINISHER</div>
            <input type="number" min="0" max="22" className="input tnum"
                   value={draft.finishers ?? 18}
                   onChange={e => setDraft({...draft, finishers: parseInt(e.target.value, 10)})}/>
          </div>
        </div>
        <div className="row" style={{ padding: 14, borderTop: "1px solid var(--line)", justifyContent: "flex-end", gap: 8 }}>
          <button className="btn btn-ghost" onClick={close}>ABBRECHEN</button>
          <button className="btn btn-primary" onClick={save}>✓ SPEICHERN & PUNKTE BERECHNEN</button>
        </div>
      </div>
    </div>
  );
}

function DriverSelect({ label, value, onChange }) {
  return (
    <div>
      <div className="h-tag" style={{ marginBottom: 6 }}>{label}</div>
      <select className="input" value={value || ""} onChange={e => onChange(e.target.value || null)}>
        <option value="">— wählen —</option>
        {window.SEED.drivers.map(d => (
          <option key={d.id} value={d.id}>#{d.num} {d.first} {d.last} ({getTeam(d.team).short})</option>
        ))}
      </select>
    </div>
  );
}


// ---- Neustart: alle Tipps löschen --------------------------------------
function ResetSection() {
  const [phase, setPhase] = React.useState("idle"); // idle | confirm | running | done
  const sb = window._supabase;

  const doReset = async () => {
    setPhase("running");
    try {
      // Alle Tipps aus DB löschen (RLS: Admin darf alle Zeilen löschen)
      const [rp, sp] = await Promise.all([
        sb.from('race_picks').delete().neq('race_id', '___never___'),
        sb.from('season_picks').delete().neq('user_id', '00000000-0000-0000-0000-000000000000'),
      ]);
      if (rp.error) throw rp.error;
      if (sp.error) throw sp.error;

      // Lokalen Store leeren
      window.setState(s => ({ ...s, racePicks: {}, seasonPicks: {} }));
      setPhase("done");
      setTimeout(() => setPhase("idle"), 3000);
      showToast("Alle Tipps wurden zurückgesetzt.", "ok");
    } catch (err) {
      console.error("[reset]", err);
      showToast("Fehler beim Zurücksetzen: " + err.message, "err");
      setPhase("idle");
    }
  };

  return (
    <div className="card" style={{ padding: 0, overflow: "hidden" }}>
      <div style={{ padding: "14px 16px", background: "var(--bg-2)", borderBottom: "1px solid var(--line)" }}>
        <div className="h-tag">SAISONSTART</div>
        <div style={{ fontFamily: "var(--font-display)", fontSize: 24, marginTop: 2 }}>Neustart</div>
      </div>
      <div style={{ padding: 16 }}>
        <div style={{ fontSize: 13, marginBottom: 12, color: "var(--ink-1)", lineHeight: 1.5 }}>
          Löscht <strong>alle Tipps aller Spieler</strong> (Renn- und Saison-Tipps). Rennergebnisse
          und Rennstatus bleiben erhalten. Kann nicht rückgängig gemacht werden.
        </div>
        {phase === "idle" && (
          <button className="btn btn-ghost" style={{ color: "var(--bad)" }}
                  onClick={() => setPhase("confirm")}>
            ALLE TIPPS ZURÜCKSETZEN
          </button>
        )}
        {phase === "confirm" && (
          <div className="col" style={{ gap: 10 }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: "var(--bad)" }}>
              Bist du sicher? Diese Aktion kann nicht rückgängig gemacht werden.
            </div>
            <div className="row" style={{ gap: 8 }}>
              <button className="btn btn-primary" style={{ background: "var(--bad)" }}
                      onClick={doReset}>
                JA, JETZT ZURÜCKSETZEN
              </button>
              <button className="btn btn-ghost" onClick={() => setPhase("idle")}>
                ABBRECHEN
              </button>
            </div>
          </div>
        )}
        {phase === "running" && (
          <div className="h-mono muted" style={{ fontSize: 12 }}>Wird zurückgesetzt…</div>
        )}
        {phase === "done" && (
          <div className="h-mono" style={{ fontSize: 12, color: "var(--good)" }}>✓ Alle Tipps gelöscht.</div>
        )}
      </div>
    </div>
  );
}

// ---- Saison-Ergebnisse (Admin trägt am Saisonende ein) ------------------
function SeasonResultsSection({ scoring }) {
  const SEED = window.SEED;
  const sr = scoring?.seasonResults || {};

  const setResult = (key, val) => {
    setState(s => ({
      ...s,
      scoring: {
        ...(s.scoring || SEED.scoring),
        seasonResults: { ...((s.scoring || SEED.scoring).seasonResults || {}), [key]: val || null },
      },
    }));
  };

  const cats = [
    { key: "driverChampion",  label: "Fahrer-Weltmeister",   kind: "driver" },
    { key: "constructor",     label: "Constructors Champion", kind: "team"   },
    { key: "destructor",      label: "Destructor",            kind: "driver" },
    { key: "driverKicked",    label: "Fahrer wurde gekickt",  kind: "driver" },
    { key: "teamBossKicked",  label: "Teamchef-Wechsel",      kind: "team"   },
    { key: "surprise",        label: "Biggest Surprise",      kind: "driver" },
  ];

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

  return (
    <div className="card" style={{ padding: 0, overflow: "hidden" }}>
      <div style={{ padding: "14px 16px", background: "var(--bg-2)", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div>
          <div className="h-tag">AM SAISONENDE AUSFÜLLEN · {filled}/6 EINGETRAGEN</div>
          <div style={{ fontFamily: "var(--font-display)", fontSize: 24, marginTop: 2 }}>Saison-Ergebnisse</div>
        </div>
        <span className={`chip ${filled === 6 ? "chip-good" : "chip-warn"}`}>{filled === 6 ? "KOMPLETT" : "OFFEN"}</span>
      </div>
      <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(240px, 1fr))", gap: 0 }}>
        {cats.map(c => (
          <div key={c.key} style={{ padding: "12px 14px", borderTop: "1px solid var(--line)", borderRight: "1px solid var(--line)" }}>
            <div className="h-tag" style={{ marginBottom: 6 }}>{c.label}</div>
            {c.kind === "driver" ? (
              <select className="input" value={sr[c.key] || ""} onChange={e => setResult(c.key, e.target.value)}>
                <option value="">— noch nicht bekannt —</option>
                {SEED.drivers.map(d => (
                  <option key={d.id} value={d.id}>#{d.num} {d.first} {d.last}</option>
                ))}
              </select>
            ) : (
              <select className="input" value={sr[c.key] || ""} onChange={e => setResult(c.key, e.target.value)}>
                <option value="">— noch nicht bekannt —</option>
                {SEED.teams.map(t => (
                  <option key={t.id} value={t.id}>{t.name}</option>
                ))}
              </select>
            )}
          </div>
        ))}
      </div>
      <div className="muted" style={{ padding: "10px 14px", fontSize: 11 }}>
        Sobald ein Ergebnis eingetragen ist, werden die Saison-Punkte aller Spieler sofort berechnet.
      </div>
    </div>
  );
}

// ---- Spielerverwaltung (nur Live-Modus mit Supabase) --------------------
function PlayerManagement() {
  const [players,  setPlayers]  = React.useState([]);
  const [loading,  setLoading]  = React.useState(true);
  const [newEmail, setNewEmail] = React.useState("");
  const [newName,  setNewName]  = React.useState("");
  const [newAdmin, setNewAdmin] = React.useState(false);
  const [saving,   setSaving]   = React.useState(false);
  const [msg,      setMsg]      = React.useState("");

  const sb = window._supabase;

  const load = async () => {
    setLoading(true);
    const { data, error } = await sb.from('players').select('*').order('created_at');
    if (!error) setPlayers(data || []);
    setLoading(false);
  };

  React.useEffect(() => { if (sb) load(); else setLoading(false); }, []);

  const addPlayer = async (e) => {
    e.preventDefault();
    if (!newEmail.trim() || !newName.trim()) return;
    setSaving(true);
    setMsg("");
    const { error } = await sb.from('players').insert({
      email:    newEmail.trim().toLowerCase(),
      name:     newName.trim(),
      avatar:   '🏎',
      is_admin: newAdmin,
    });
    if (error) {
      setMsg("Fehler: " + (error.message.includes('duplicate') ? 'E-Mail bereits vorhanden.' : error.message));
    } else {
      setMsg("✓ " + newName.trim() + " hinzugefügt.");
      setNewEmail(""); setNewName(""); setNewAdmin(false);
      load();
    }
    setSaving(false);
  };

  const removePlayer = async (id, name, userId) => {
    if (!confirm(`"${name}" wirklich entfernen? Alle Tipps dieses Spielers werden ebenfalls gelöscht.`)) return;
    // Picks zuerst löschen (FK referenziert auth.users, nicht players)
    if (userId) {
      await Promise.all([
        sb.from('race_picks').delete().eq('user_id', userId),
        sb.from('season_picks').delete().eq('user_id', userId),
      ]);
    }
    await sb.from('players').delete().eq('id', id);
    // Globalen Store sofort aktualisieren (Tabelle, Leaderboard)
    if (userId) {
      window.SEED.players = (window.SEED.players || []).filter(p => p.id !== userId);
      window.setState(s => {
        const racePicks = {};
        Object.keys(s.racePicks).forEach(raceId => {
          const { [userId]: _removed, ...rest } = s.racePicks[raceId] || {};
          racePicks[raceId] = rest;
        });
        const { [userId]: _removed, ...seasonPicks } = s.seasonPicks;
        return { ...s, racePicks, seasonPicks };
      });
    }
    load();
  };

  const toggleAdmin = async (id, current) => {
    await sb.from('players').update({ is_admin: !current }).eq('id', id);
    load();
  };

  if (!sb) {
    return (
      <div className="card" style={{ padding: 16 }}>
        <div className="h-tag" style={{ marginBottom: 6 }}>SPIELER VERWALTEN</div>
        <div className="muted" style={{ fontSize: 13 }}>
          Nur im Live-Modus verfügbar (Supabase-Config erforderlich).
        </div>
      </div>
    );
  }

  return (
    <div className="card" style={{ padding: 0, overflow: "hidden" }}>
      <div style={{ padding: "14px 16px", background: "var(--bg-2)", borderBottom: "1px solid var(--line)" }}>
        <div className="h-tag">SPIELER VERWALTEN · ZUGANG & EINLADUNGEN</div>
        <div style={{ fontFamily: "var(--font-display)", fontSize: 24, marginTop: 2 }}>
          Teilnehmer
        </div>
      </div>

      {/* Neuen Spieler anlegen */}
      <form onSubmit={addPlayer} style={{
        padding: 14, borderBottom: "1px solid var(--line)",
        display: "flex", gap: 8, flexWrap: "wrap", alignItems: "flex-end",
      }}>
        <div style={{ flex: "1 1 120px" }}>
          <div className="h-tag" style={{ marginBottom: 4 }}>NAME</div>
          <input className="input" placeholder="Max Verstappen" value={newName}
                 onChange={e => setNewName(e.target.value)} disabled={saving} />
        </div>
        <div style={{ flex: "2 1 200px" }}>
          <div className="h-tag" style={{ marginBottom: 4 }}>E-MAIL</div>
          <input className="input" type="email" placeholder="max@redbull.com" value={newEmail}
                 onChange={e => setNewEmail(e.target.value)} disabled={saving} />
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 6, paddingBottom: 2 }}>
          <input type="checkbox" id="newAdminCb" checked={newAdmin}
                 onChange={e => setNewAdmin(e.target.checked)} />
          <label htmlFor="newAdminCb" className="h-tag">ADMIN</label>
        </div>
        <button className="btn btn-primary" type="submit"
                disabled={saving || !newEmail.trim() || !newName.trim()}
                style={{ flexShrink: 0 }}>
          {saving ? "..." : "+ HINZUFÜGEN"}
        </button>
      </form>

      {msg && (
        <div style={{
          padding: "8px 14px", fontSize: 13,
          color: msg.startsWith("✓") ? "var(--good)" : "var(--bad)",
          borderBottom: "1px solid var(--line)",
        }}>{msg}</div>
      )}

      {/* Spieler-Liste */}
      {loading ? (
        <div style={{ padding: 16, color: "var(--ink-2)", fontSize: 13 }}>Lade Spieler…</div>
      ) : players.length === 0 ? (
        <div style={{ padding: 16, color: "var(--ink-2)", fontSize: 13 }}>
          Noch keine Spieler. Füg dich selbst zuerst hinzu!
        </div>
      ) : (
        <div>
          {players.map(p => (
            <div key={p.id} className="spread"
                 style={{ padding: "10px 14px", borderBottom: "1px solid var(--bg-3)" }}>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontWeight: 600 }}>
                  {p.name}
                  {p.is_admin && (
                    <span className="chip chip-cyan" style={{ marginLeft: 8, padding: "1px 6px", fontSize: 9 }}>
                      ADMIN
                    </span>
                  )}
                </div>
                <div className="h-mono muted" style={{ fontSize: 11 }}>
                  {p.email}
                  {" · "}
                  {p.user_id
                    ? <span style={{ color: "var(--good)" }}>✓ eingeloggt</span>
                    : <span style={{ color: "var(--warn)" }}>○ noch nie eingeloggt</span>
                  }
                </div>
              </div>
              <div className="row" style={{ gap: 6, flexShrink: 0 }}>
                <button
                  className={`btn btn-ghost ${p.is_admin ? "active" : ""}`}
                  style={{ padding: "4px 10px", fontSize: 11 }}
                  onClick={() => toggleAdmin(p.id, p.is_admin)}
                  title={p.is_admin ? "Admin-Rechte entziehen" : "Zum Admin machen"}
                >
                  {p.is_admin ? "ADMIN ✓" : "ADMIN"}
                </button>
                <button
                  className="btn btn-ghost"
                  style={{ padding: "4px 8px", fontSize: 11, color: "var(--bad)" }}
                  onClick={() => removePlayer(p.id, p.name, p.user_id)}
                  title="Spieler entfernen"
                >
                  ✕
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      <div style={{ padding: "10px 14px", background: "var(--bg-2)", borderTop: "1px solid var(--line)" }}>
        <div className="muted" style={{ fontSize: 12 }}>
          Spieler, die noch nicht eingeloggt waren, können sich über den Magic-Link-Login anmelden.
          Ihre Tipps werden dem Konto automatisch zugeordnet.
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LeaderboardScreen, AdminScreen, PlayerManagement });
