// Auth + Dashboard screens
const { useState: useStateA, useEffect: useEffectA } = React;

// ---- AuthScreen ---------------------------------------------------------
function AuthScreen() {
  const [mode, setMode]         = useStateA("magic"); // "magic" | "password"
  const [email, setEmail]       = useStateA("");
  const [password, setPassword] = useStateA("");
  const [showPw, setShowPw]     = useStateA(false);
  const [status, setStatus]     = useStateA("idle"); // idle | loading | sent | error
  const [errorMsg, setErrorMsg] = useStateA("");
  const authError = useStore(s => s.authError);

  useEffectA(() => {
    if (authError === 'not_registered') {
      setStatus("error");
      setErrorMsg("Diese E-Mail ist nicht für das Tippspiel registriert. Frag den Admin.");
      setState({ authError: null });
    } else if (authError === 'sign_in_failed') {
      setStatus("error");
      setErrorMsg("Login fehlgeschlagen. Bitte erneut versuchen.");
      setState({ authError: null });
    }
  }, [authError]);

  const switchMode = (m) => { setMode(m); setStatus("idle"); setErrorMsg(""); setPassword(""); };

  const sendMagicLink = async (e) => {
    e.preventDefault();
    const trimmed = email.trim();
    if (!trimmed) return;
    setStatus("loading"); setErrorMsg("");
    const redirectTo = window.location.href.split('#')[0].split('?')[0];
    const { error } = await window._supabase.auth.signInWithOtp({
      email: trimmed, options: { emailRedirectTo: redirectTo },
    });
    if (error) { setStatus("error"); setErrorMsg(error.message); }
    else        setStatus("sent");
  };

  const signInWithPassword = async (e) => {
    e.preventDefault();
    const trimmed = email.trim();
    if (!trimmed || !password) return;
    setStatus("loading"); setErrorMsg("");
    const withTimeout = (p, ms) => Promise.race([
      p,
      new Promise((_, rej) => setTimeout(() => rej(new Error('__timeout__')), ms)),
    ]);
    const onErr = (err) => {
      setStatus("error");
      setErrorMsg(err?.message === '__timeout__'
        ? 'Zeitüberschreitung. Bitte erneut versuchen.'
        : (err?.message || 'Login fehlgeschlagen. Bitte erneut versuchen.'));
    };
    try {
      const { data, error } = await withTimeout(
        window._supabase.auth.signInWithPassword({ email: trimmed, password }),
        15000
      );
      if (error) { onErr(error); return; }
      await withTimeout(window.processSignIn(data.session), 15000);
    } catch (err) { onErr(err); }
  };

  const resend = async () => {
    setStatus("loading");
    const redirectTo = window.location.href.split('#')[0].split('?')[0];
    const { error } = await window._supabase.auth.signInWithOtp({
      email: email.trim(), options: { emailRedirectTo: redirectTo },
    });
    if (error) { setStatus("error"); setErrorMsg(error.message); }
    else        setStatus("sent");
  };

  return (
    <div style={{
      minHeight: "100vh", display: "grid", placeItems: "center",
      padding: 20, position: "relative", overflow: "hidden",
      background: "var(--bg-0)",
    }}>
      {/* Hintergrund-Streifen */}
      <div className="speedlines" style={{ position: "absolute", inset: 0, opacity: 0.3, pointerEvents: "none" }} />
      {/* Roter Glow-Kreis */}
      <div style={{
        position: "absolute", top: "30%", left: "50%",
        transform: "translate(-50%, -50%)", width: 600, height: 600,
        background: "radial-gradient(circle, rgba(225,6,0,0.08) 0%, transparent 70%)",
        pointerEvents: "none",
      }} />

      <div style={{ width: "100%", maxWidth: 400, position: "relative", zIndex: 1 }}>
        {/* Logo */}
        <div style={{ display: "flex", justifyContent: "center", marginBottom: 32 }}>
          <Logo size={280} />
        </div>

        <div className="card carbon" style={{ padding: 0, overflow: "hidden" }}>
          {/* Roter Top-Stripe */}
          <div style={{ height: 3, background: "var(--accent)" }} />
          <div style={{ padding: 28 }}>

          {status === "sent" ? (
            <div style={{ textAlign: "center" }}>
              <div style={{ fontSize: 48, marginBottom: 16 }}>📬</div>
              <div className="h-tag" style={{ marginBottom: 6 }}>LOGIN LINK GESENDET</div>
              <h1 className="h-display" style={{ fontSize: 32, margin: "0 0 12px" }}>Check dein Postfach</h1>
              <div className="muted" style={{ fontSize: 13, marginBottom: 8 }}>Wir haben einen Login-Link an</div>
              <div style={{ fontWeight: 700, marginBottom: 16, wordBreak: "break-all" }}>{email}</div>
              <div className="muted" style={{ fontSize: 13, marginBottom: 24 }}>
                geschickt. Klick auf den Link – kein Passwort nötig.
              </div>
              <div className="muted" style={{ fontSize: 12, marginBottom: 14, color: "var(--ink-3)" }}>
                Kein Link da? Prüf den Spam-Ordner oder:
              </div>
              <button className="btn btn-ghost" onClick={resend} style={{ width: "100%", justifyContent: "center" }}>
                Link nochmal senden
              </button>
              <button className="tab" onClick={() => { setStatus("idle"); setEmail(""); }}
                style={{ marginTop: 12, display: "block", width: "100%", textAlign: "center" }}>
                Andere E-Mail verwenden
              </button>
            </div>
          ) : (
            <>
              <h1 className="h-display" style={{ fontSize: 38, margin: "0 0 16px" }}>Login</h1>

              <div style={{ display: "flex", gap: 0, marginBottom: 20,
                              border: "1px solid var(--border)", borderRadius: 6, overflow: "hidden" }}>
                  {[["magic", "Login Link"], ["password", "Passwort"]].map(([m, label]) => (
                    <button key={m} onClick={() => switchMode(m)} style={{
                      flex: 1, padding: "8px 0", fontSize: 12, fontWeight: 700, letterSpacing: "0.08em",
                      border: "none", cursor: "pointer", transition: "background 0.15s",
                      background: mode === m ? "var(--accent)" : "transparent",
                      color:      mode === m ? "#fff" : "var(--ink-2)",
                    }}>
                      {label.toUpperCase()}
                    </button>
                  ))}
                </div>

              {status === "error" && (
                <div style={{
                  background: "rgba(255,60,60,0.1)", border: "1px solid rgba(255,60,60,0.3)",
                  padding: "10px 14px", marginBottom: 14, fontSize: 13, color: "var(--bad)",
                }}>
                  {errorMsg}
                </div>
              )}

              <form onSubmit={mode === "password" ? signInWithPassword : sendMagicLink}
                    className="col" style={{ gap: 14 }}>
                <div>
                  <label className="h-tag" style={{ display: "block", marginBottom: 6 }}>E-Mail-Adresse</label>
                  <input className="input" type="email" value={email}
                    onChange={e => setEmail(e.target.value)}
                    placeholder="du@example.com" disabled={status === "loading"} required autoFocus />
                </div>

                {mode === "password" && (
                  <div>
                    <label className="h-tag" style={{ display: "block", marginBottom: 6 }}>Passwort</label>
                    <div style={{ position: "relative" }}>
                      <input className="input" type={showPw ? "text" : "password"} value={password}
                        onChange={e => setPassword(e.target.value)}
                        placeholder="••••••••" disabled={status === "loading"} required
                        style={{ paddingRight: 40 }} />
                      <button type="button" onClick={() => setShowPw(v => !v)}
                        style={{ position: "absolute", right: 10, top: "50%", transform: "translateY(-50%)",
                                 background: "none", border: "none", cursor: "pointer",
                                 color: "var(--ink-2)", fontSize: 16, lineHeight: 1, padding: 2 }}>
                        {showPw ? "🙈" : "👁"}
                      </button>
                    </div>
                  </div>
                )}

                {mode === "magic" && (
                  <div className="muted" style={{ fontSize: 12 }}>
                    Du erhältst einen einmaligen Login-Link per E-Mail.
                  </div>
                )}

                <button className="btn btn-primary" type="submit"
                  disabled={status === "loading" || !email.trim() || (mode === "password" && !password)}
                  style={{ marginTop: 4, justifyContent: "center" }}>
                  {status === "loading" ? "⏳  LADEN..." :
                   mode === "password"  ? "▶  EINLOGGEN" : "▶  LOGIN LINK SENDEN"}
                </button>
              </form>
            </>
          )}
          </div>{/* end padding-wrapper */}
        </div>{/* end card */}

        <div style={{ textAlign: "center", marginTop: 24 }}>
          <div className="h-mono" style={{ fontSize: 10, color: "var(--ink-3)", letterSpacing: "0.18em" }}>
            PRIVATE · SEASON {window.SEED?.season || 2026} · INVITE ONLY
          </div>
        </div>
      </div>
    </div>
  );
}

// ---- LoadingScreen ------------------------------------------------------
function LoadingScreen() {
  return (
    <div style={{
      minHeight: "100vh", display: "grid", placeItems: "center",
      background: "var(--bg-1)", position: "relative", overflow: "hidden",
    }}>
      <div className="speedlines" style={{ position: "absolute", inset: 0, opacity: 0.2, pointerEvents: "none" }} />
      <div style={{ textAlign: "center", position: "relative", zIndex: 1 }}>
        <Logo size={240} />
        <div style={{ marginTop: 24, display: "flex", alignItems: "center", gap: 10, justifyContent: "center" }}>
          <span className="pulse" style={{ color: "var(--accent)" }} />
          <span className="muted" style={{ fontSize: 13, letterSpacing: "0.1em" }}>VERBINDE...</span>
        </div>
      </div>
    </div>
  );
}

// ---- Dashboard ----------------------------------------------------------
function Dashboard() {
  const { raceState, racePicks, user, scoring } = useStore();
  const announcement = scoring?.announcement || null;
  const isDismissed = React.useMemo(() => {
    try { return localStorage.getItem('f1_dismissed_msg') === announcement?.id; } catch { return false; }
  }, [announcement?.id]);
  const [dismissed, setDismissed] = React.useState(isDismissed);
  const dismiss = () => {
    try { localStorage.setItem('f1_dismissed_msg', announcement.id); } catch {}
    setDismissed(true);
  };
  const SEED = window.SEED;
  const nextRaceId = SEED.calendar.find(r => raceState[r.id] !== 'finished')?.id || SEED.calendar[SEED.calendar.length - 1]?.id;
  const race = getRace(nextRaceId);
  const dl = race ? getDeadlines(race) : null;
  const myPicks = race && racePicks[nextRaceId]?.[user.id];
  const seasonPicks = useStore(s => s.seasonPicks[user.id]);
  const seasonComplete = seasonPicks && Object.values(seasonPicks).filter(Boolean).length >= 6;

  const { totals } = computeScores();
  const ranked = SEED.players.map(p => ({ p, ...totals[p.id] })).sort((a,b) => b.total - a.total);
  const myRank = ranked.findIndex(r => r.p.id === user.id) + 1;
  const myPts = totals[user.id]?.total || 0;
  const leaderPts = ranked[0]?.total || 0;

  const lastFinished = [...SEED.calendar].reverse().find(r => raceState[r.id] === "finished");
  const goRace = () => setState({ view: "race", currentRaceId: nextRaceId });

  // Race-Week ab Montag: Rennen liegt in den nächsten 6 Tagen (und ist noch nicht vorbei)
  const raceTs = race ? new Date(race.date + "T15:00:00Z").getTime() : null;
  const msUntilRace = raceTs ? raceTs - Date.now() : null;
  const isRaceWeek = msUntilRace !== null && msUntilRace > 0 && msUntilRace <= 6 * 24 * 3600 * 1000;

  if (!race) return (
    <div className="container col" style={{ gap: 20, paddingBottom: 40 }}>
      <div className="muted" style={{ marginTop: 40, textAlign: "center" }}>Kalender wird geladen…</div>
    </div>
  );

  const rdNum   = String(SEED.calendar.indexOf(race) + 1).padStart(2, "0");
  const rdTotal = SEED.calendar.length;

  return (
    <div className="container col" style={{ gap: 16, paddingTop: 24, paddingBottom: 60 }}>

      {/* ── Greeting ─────────────────────────────────────────────────── */}
      <div style={{ marginBottom: 4 }}>
        <div className="h-tag" style={{ marginBottom: 6 }}>
          PIT WALL · SAISON {SEED.season || 2026}
          {isRaceWeek && <span className="chip chip-cyan" style={{ marginLeft: 10, fontSize: 9, verticalAlign: "middle" }}><span className="pulse" />RACE WEEK</span>}
        </div>
        <h1 className="h-display" style={{ fontSize: 40, lineHeight: 1 }}>
          Hallo, {user.name}.
        </h1>
      </div>

      {/* ── Announcement Banner ─────────────────────────────────────── */}
      {announcement && !dismissed && (
        <div style={{
          display: "flex", alignItems: "flex-start", gap: 12,
          padding: "14px 16px",
          background: "rgba(0,210,190,0.07)",
          border: "1px solid rgba(0,210,190,0.25)",
          borderLeft: "3px solid var(--good)",
        }}>
          <span style={{ fontSize: 18, flexShrink: 0, marginTop: 1 }}>📢</span>
          <div style={{ flex: 1, fontSize: 14, lineHeight: 1.5, color: "var(--ink-1)" }}>
            {announcement.text}
          </div>
          <button onClick={dismiss} style={{
            background: "none", border: "none", cursor: "pointer",
            color: "var(--ink-3)", fontSize: 18, lineHeight: 1,
            padding: "0 0 0 8px", flexShrink: 0,
          }}>×</button>
        </div>
      )}

      {/* ── Hero-Card: Nächstes Rennen ───────────────────────────────── */}
      <div className="card accent-top" style={{ padding: 0, overflow: "hidden" }}>
        {/* Oberer Bereich: Renninfo */}
        <div style={{ padding: "28px 28px 24px", position: "relative", overflow: "hidden" }}>
          {/* Dekorativer Kreis rechts */}
          <div style={{
            position: "absolute", right: -80, top: -80,
            width: 320, height: 320, borderRadius: "50%",
            background: "var(--accent)", opacity: 0.05, pointerEvents: "none",
          }} />

          <div className="h-tag" style={{ marginBottom: 10 }}>
            NÄCHSTES RENNEN · RD {rdNum} / {rdTotal}
            {race.sprint && <span style={{ marginLeft: 10, color: "var(--warn)" }}>· SPRINT</span>}
          </div>

          <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 16 }}>
            <div>
              <h2 className="h-display" style={{ fontSize: "clamp(40px, 6vw, 72px)", lineHeight: 0.95, marginBottom: 12 }}>
                {race.name}
              </h2>
              <div style={{ display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
                <FlagDot country={race.country} />
                <span style={{ color: "var(--ink-2)", fontSize: 13 }}>{race.circuit}</span>
                <span style={{ color: "var(--ink-1)", fontWeight: 700, fontSize: 13, fontFamily: "var(--font-mono)" }}>
                  {formatDate(race.date)}
                </span>
              </div>
            </div>
            <button className="btn btn-primary desktop-only" onClick={goRace} style={{ flexShrink: 0, marginTop: 4 }}>
              Tipp abgeben →
            </button>
          </div>
        </div>

        {/* Trennlinie + Countdown */}
        <div style={{ padding: "20px 28px", borderTop: "1px solid rgba(255,255,255,0.07)" }}>
          <div className="h-tag" style={{ marginBottom: 10 }}>⏱ DEADLINE · FP1</div>
          <Countdown ts={dl.fp1} />
        </div>

        {/* Pick-Status-Leiste */}
        <div style={{
          padding: "14px 28px",
          background: "rgba(0,0,0,0.2)",
          borderTop: "1px solid rgba(255,255,255,0.06)",
          display: "flex", alignItems: "center", justifyContent: "space-between",
          gap: 12, flexWrap: "wrap",
        }}>
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
            {[
              { label: "Pole",    done: !!myPicks?.pole },
              { label: "Sieger",  done: !!myPicks?.winner },
              ...(race.sprint ? [{ label: "S-Pole", done: !!myPicks?.sprintPole }] : []),
              ...(race.sprint ? [{ label: "Sprint", done: !!myPicks?.sprintWinner }] : []),
              { label: "Finisher", done: myPicks?.finishers != null },
            ].map(({ label, done }) => (
              <span key={label} className={`chip ${done ? "chip-good" : "chip-warn"}`}>
                {done ? `✓ ${label}` : `○ ${label}`}
              </span>
            ))}
          </div>
          <button className="btn btn-primary mobile-only" onClick={goRace}
                  style={{ width: "100%", justifyContent: "center" }}>
            Tipp abgeben →
          </button>
        </div>
      </div>

      {/* ── Zwei Kacheln: Championship + Saison ─────────────────────── */}
      <div className="two-col-cards">

        {/* Championship */}
        <div className="card" style={{ padding: "24px 24px 20px" }}>
          <div className="h-tag" style={{ marginBottom: 16 }}>Championship</div>
          <div style={{ display: "flex", alignItems: "flex-end", gap: 14 }}>
            <span className="h-display" style={{ fontSize: 80, color: "var(--accent)", lineHeight: 1 }}>
              {myRank > 0 ? `P${myRank}` : "—"}
            </span>
            <div style={{ paddingBottom: 8 }}>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 22, fontWeight: 600 }}>
                {myPts}<span style={{ fontSize: 12, color: "var(--ink-2)", marginLeft: 4 }}>PKT</span>
              </div>
              <div className="h-tag" style={{ marginTop: 3 }}>
                {myPts > 0 && myPts >= leaderPts ? "🏆 Führung" : `–${Math.max(0, leaderPts - myPts)} zur Spitze`}
              </div>
            </div>
          </div>
          {/* Progress bar */}
          <div style={{ height: 3, background: "rgba(255,255,255,0.08)", borderRadius: 2, marginTop: 16, position: "relative" }}>
            <div style={{
              position: "absolute", left: 0, top: 0, bottom: 0, borderRadius: 2,
              width: `${leaderPts ? Math.round((myPts / leaderPts) * 100) : 0}%`,
              background: "var(--accent)", transition: "width 0.6s ease",
            }} />
          </div>
          <button className="btn btn-ghost" onClick={() => setState({ view: "leaderboard" })}
                  style={{ marginTop: 16, fontSize: 10, padding: "8px 14px" }}>
            Volle Tabelle →
          </button>
        </div>

        {/* Saison-Tipps */}
        <div className="card" style={{ padding: "24px 24px 20px" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 16 }}>
            <div className="h-tag">Saison-Tipps</div>
            <span className={`chip ${seasonComplete ? "chip-good" : "chip-warn"}`} style={{ fontSize: 9 }}>
              {seasonComplete ? "✓ Komplett" : "Offen"}
            </span>
          </div>
          {seasonComplete ? (
            <div style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: "8px 12px", alignItems: "center" }}>
              {[
                { key: "WDC",        val: driverName(seasonPicks.driverChampion) },
                { key: "WCC",        val: teamName(seasonPicks.constructor) },
                { key: "Destructor", val: driverName(seasonPicks.destructor) },
              ].map(({ key, val }) => (
                <React.Fragment key={key}>
                  <span className="h-tag">{key}</span>
                  <span style={{ fontWeight: 600, fontSize: 13, color: "var(--ink-0)" }}>{val}</span>
                </React.Fragment>
              ))}
            </div>
          ) : (
            <div style={{ color: "var(--ink-2)", fontSize: 13, lineHeight: 1.6 }}>
              6 Tipps · bis zu{" "}
              <span style={{ color: "var(--ink-0)", fontWeight: 700 }}>
                {['seasonChampion','seasonConstructor','seasonDestructor','seasonDriverKicked','seasonTeamBossKicked','seasonSurprise'].reduce((sum, k) => sum + ((scoring || SEED.scoring)[k] || 0), 0)}
              </span>{" "}
              Punkte möglich.
            </div>
          )}
          <button className="btn btn-ghost" onClick={() => setState({ view: "season" })}
                  style={{ marginTop: 16, fontSize: 10, padding: "8px 14px" }}>
            {seasonComplete ? "Ansehen →" : "Jetzt tippen →"}
          </button>
        </div>
      </div>

      {/* ── Letztes Rennen ───────────────────────────────────────────── */}
      {lastFinished && (
        <div>
          <SectionH title="Letztes Rennen" sub="AUSWERTUNG" right={
            <button className="tab" style={{ padding: "0 0 2px 0", fontSize: 11 }}
                    onClick={() => setState({ view: "race", currentRaceId: lastFinished.id })}>
              Detail →
            </button>
          } />
          <LastRaceSummary raceId={lastFinished.id} />
        </div>
      )}

      {/* ── Form-Kurve ───────────────────────────────────────────────── */}
      <div>
        <SectionH title="Form-Kurve" sub="PUNKTE PRO RENNEN" />
        <FormSpark />
      </div>

    </div>
  );
}

function LastRaceSummary({ raceId }) {
  const race = getRace(raceId);
  const res = useStore(s => s.results[raceId]);
  const { totals } = computeScores();
  const me = totals[getState().user.id];
  const myPts = me?.byRace[raceId] || 0;

  return (
    <div className="card" style={{ padding: 0, overflow: "hidden" }}>
      {/* Header-Zeile */}
      <div style={{
        display: "grid", gridTemplateColumns: "auto 1fr auto",
        alignItems: "center", gap: 16,
        padding: "14px 20px",
        background: "var(--bg-2)",
        borderBottom: "1px solid var(--line)",
      }}>
        <span className="h-display" style={{ fontSize: 28, color: "var(--accent)", lineHeight: 1 }}>
          R{window.SEED.calendar.indexOf(race) + 1}
        </span>
        <div>
          <div style={{ fontWeight: 700, fontSize: 15 }}>{race.name}</div>
          <div className="h-tag" style={{ marginTop: 2 }}>{formatDate(race.date)} · {race.circuit}</div>
        </div>
        <div style={{ textAlign: "right" }}>
          <div style={{
            fontFamily: "var(--font-display)", fontSize: 32, lineHeight: 1,
            color: myPts > 0 ? "var(--good)" : "var(--ink-3)",
          }}>+{myPts}</div>
          <div className="h-tag">Punkte</div>
        </div>
      </div>

      {/* Ergebnis-Grid */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr" }}>
        <ResultCell label="POLE"     driverId={res?.pole} />
        <ResultCell label="SIEGER"   driverId={res?.winner} />
        {race.sprint && <ResultCell label="SPRINT"   driverId={res?.sprintWinner} />}
        <ResultCell label="FINISHER" value={res?.finishers != null ? `${res.finishers}/22` : "—"} />
      </div>
    </div>
  );
}

function ResultCell({ label, driverId, value }) {
  const d = driverId ? getDriver(driverId) : null;
  const t = d ? getTeam(d.team) : null;
  return (
    <div style={{
      padding: "16px 20px",
      borderTop: "1px solid var(--line)",
      borderRight: "1px solid var(--line)",
    }}>
      <div className="h-tag" style={{ marginBottom: 8 }}>{label}</div>
      {d ? (
        <div className="row" style={{ gap: 10 }}>
          <DriverNum num={d.num} teamId={d.team} size={32} />
          <div>
            <div style={{ fontWeight: 700, fontSize: 14 }}>{d.last}</div>
            <div className="h-tag" style={{ marginTop: 1 }}>{t?.short}</div>
          </div>
        </div>
      ) : (
        <div style={{
          fontFamily: "var(--font-display)", fontSize: 28, lineHeight: 1,
          color: "var(--ink-3)",
        }}>{value || "—"}</div>
      )}
    </div>
  );
}

function FormSpark() {
  const SEED = window.SEED;
  const { totals } = computeScores();
  const me = totals[getState().user.id];
  const finished = SEED.calendar.filter(r => getState().raceState[r.id] === "finished");
  const points = finished.map(r => me?.byRace[r.id] || 0);
  const maxP = Math.max(1, ...points);
  const totalPts = points.reduce((a, b) => a + b, 0);
  const avgPts = finished.length ? (totalPts / finished.length).toFixed(1) : "—";

  return (
    <div className="card" style={{ padding: 0, overflow: "hidden" }}>
      {/* Stats-Header */}
      <div style={{
        display: "grid", gridTemplateColumns: "1fr 1fr 1fr",
        borderBottom: "1px solid var(--line)",
      }}>
        {[
          { label: "RENNEN", value: finished.length },
          { label: "GESAMT", value: totalPts + " PKT" },
          { label: "Ø PRO RENNEN", value: avgPts },
        ].map(({ label, value }) => (
          <div key={label} style={{
            padding: "14px 16px",
            borderRight: "1px solid var(--line)",
          }}>
            <div className="h-tag" style={{ marginBottom: 4 }}>{label}</div>
            <div style={{
              fontFamily: "var(--font-display)", fontSize: 26, lineHeight: 1,
              color: "var(--ink-0)",
            }}>{value}</div>
          </div>
        ))}
      </div>

      {/* Balken-Chart */}
      <div style={{ padding: "20px 20px 16px" }}>
        {finished.length === 0 ? (
          <div className="muted" style={{ fontSize: 13 }}>Noch keine abgeschlossenen Rennen.</div>
        ) : (
          <div style={{ display: "flex", gap: 6, alignItems: "flex-end", height: 80 }}>
            {finished.map((r, i) => (
              <div key={r.id} style={{
                flex: 1, display: "flex", flexDirection: "column",
                alignItems: "center", gap: 6,
              }}>
                {points[i] > 0 && (
                  <div style={{
                    fontFamily: "var(--font-mono)", fontSize: 10,
                    color: "var(--ink-2)",
                  }}>{points[i]}</div>
                )}
                <div style={{
                  width: "100%",
                  height: `${(points[i] / maxP) * 56 + 4}px`,
                  background: points[i] > 0 ? "var(--accent)" : "var(--bg-3)",
                  opacity: points[i] > 0 ? 1 : 0.4,
                  transition: "height 0.3s ease",
                  minHeight: 4,
                }} />
                <div style={{
                  fontFamily: "var(--font-mono)", fontSize: 9,
                  color: "var(--ink-3)", letterSpacing: "0.08em",
                }}>{r.country?.slice(0, 3).toUpperCase()}</div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

// ---- ProfileScreen -------------------------------------------------------
const AVATAR_OPTIONS = [
  '🏎','🏁','🔴','⚡','🦁','🐺','🦊','🐯','🦅','🐉',
  '🌶','🔥','💎','⭐','🌙','🎯','🏆','👑','🎸','🤖',
];

function ProfileScreen() {
  const { user } = useStore();
  const sb = window._supabase;

  const [name,        setName]        = useStateA(user?.name        || "");
  const [avatar,      setAvatar]      = useStateA(user?.avatar      || '🏎');
  const [notifyEmail, setNotifyEmail] = useStateA(user?.notifyEmail || false);
  const [pw,          setPw]          = useStateA("");
  const [pw2,         setPw2]         = useStateA("");
  const [saving,      setSaving]      = useStateA(false);
  const [msg,         setMsg]         = useStateA(null); // { type: 'ok'|'err', text }

  const save = async (e) => {
    e.preventDefault();
    if (!name.trim()) return;
    if (pw && pw !== pw2) { setMsg({ type: 'err', text: 'Passwörter stimmen nicht überein.' }); return; }
    setSaving(true); setMsg(null);

    if (sb) {
      const { error: playerErr } = await sb
        .from('players')
        .update({ name: name.trim(), avatar, notify_email: notifyEmail })
        .eq('user_id', user.id);
      if (playerErr) { setMsg({ type: 'err', text: 'Fehler beim Speichern: ' + playerErr.message }); setSaving(false); return; }

      if (pw) {
        const { error: pwErr } = await sb.auth.updateUser({ password: pw });
        if (pwErr) { setMsg({ type: 'err', text: 'Passwort-Fehler: ' + pwErr.message }); setSaving(false); return; }
      }
    }

    setState(s => ({ ...s, user: { ...s.user, name: name.trim(), avatar, notifyEmail } }));
    setPw(""); setPw2("");
    setMsg({ type: 'ok', text: pw ? 'Profil + Passwort gespeichert.' : 'Profil gespeichert.' });
    setSaving(false);
  };

  return (
    <div className="container col" style={{ gap: 16, paddingBottom: 60 }}>
      <SectionH title="Profil" sub="DEIN ACCOUNT" />

      {/* Profile hero — current avatar + name */}
      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <div style={{
          background: "linear-gradient(135deg, #1a1528 0%, #15151e 100%)",
          padding: "24px 24px 20px",
          display: "flex", alignItems: "center", gap: 20,
        }}>
          <div style={{
            width: 72, height: 72, borderRadius: "50%",
            background: "var(--bg-3)", border: "3px solid var(--accent)",
            display: "flex", alignItems: "center", justifyContent: "center",
            fontSize: 36, flexShrink: 0,
          }}>{avatar}</div>
          <div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 32, lineHeight: 1 }}>
              {name || user?.name || "—"}
            </div>
            <div className="h-tag" style={{ marginTop: 6 }}>{user?.email}</div>
          </div>
        </div>
      </div>

      <form onSubmit={save} className="col" style={{ gap: 12 }}>

        {/* Avatar picker */}
        <div className="card" style={{ padding: 20 }}>
          <div className="h-tag" style={{ marginBottom: 14 }}>AVATAR WÄHLEN</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(48px, 1fr))', gap: 8 }}>
            {AVATAR_OPTIONS.map(em => (
              <button key={em} type="button"
                onClick={() => setAvatar(em)}
                style={{
                  width: '100%', aspectRatio: '1', fontSize: 22,
                  background: avatar === em ? 'rgba(225,6,0,0.12)' : 'var(--bg-3)',
                  border: `2px solid ${avatar === em ? 'var(--accent)' : 'transparent'}`,
                  borderRadius: 10,
                  cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
                  transition: 'all 0.15s ease',
                }}>
                {em}
              </button>
            ))}
          </div>
        </div>

        {/* Name */}
        <div className="card" style={{ padding: 20 }}>
          <div className="h-tag" style={{ marginBottom: 8 }}>ANZEIGENAME</div>
          <input className="input" value={name} onChange={e => setName(e.target.value)}
                 placeholder="Dein Name" maxLength={30} />
        </div>

        {/* Passwort */}
        <div className="card" style={{ padding: 20 }}>
          <div className="h-tag" style={{ marginBottom: 4 }}>PASSWORT ÄNDERN</div>
          <div className="muted" style={{ fontSize: 12, marginBottom: 12 }}>
            {sb ? 'Leer lassen, um das Passwort nicht zu ändern.' : 'Nur im Live-Modus verfügbar.'}
          </div>
          <div className="col" style={{ gap: 8 }}>
            <input className="input" type="password" value={pw} onChange={e => setPw(e.target.value)}
                   placeholder="Neues Passwort" disabled={!sb} />
            <input className="input" type="password" value={pw2} onChange={e => setPw2(e.target.value)}
                   placeholder="Passwort wiederholen" disabled={!sb} />
          </div>
        </div>

        {/* E-Mail-Benachrichtigungen */}
        <div className="card" style={{ padding: 20 }}>
          <div className="spread" style={{ alignItems: 'center' }}>
            <div>
              <div className="h-tag" style={{ marginBottom: 4 }}>RENN-ERINNERUNGEN</div>
              <div style={{ color: 'var(--ink-2)', fontSize: 13 }}>
                E-Mail 3 Tage vor jedem Rennwochenende
              </div>
            </div>
            <button
              type="button"
              onClick={() => setNotifyEmail(v => !v)}
              style={{
                width: 48, height: 26, borderRadius: 13, border: 'none', cursor: 'pointer',
                background: notifyEmail ? 'var(--accent)' : 'var(--bg-3)',
                position: 'relative', transition: 'background 0.2s', flexShrink: 0,
              }}
            >
              <span style={{
                position: 'absolute', top: 3, left: notifyEmail ? 25 : 3,
                width: 20, height: 20, borderRadius: '50%', background: '#fff',
                transition: 'left 0.2s', boxShadow: '0 1px 3px rgba(0,0,0,0.4)',
              }} />
            </button>
          </div>
          {!sb && (
            <div className="muted" style={{ fontSize: 11, marginTop: 8 }}>
              Nur im Live-Modus verfügbar.
            </div>
          )}
        </div>

        {msg && (
          <div style={{
            padding: '12px 16px', borderRadius: 8, fontSize: 13,
            background: msg.type === 'ok' ? 'rgba(0,210,190,0.1)' : 'rgba(255,70,70,0.1)',
            border: `1px solid ${msg.type === 'ok' ? 'var(--good)' : 'var(--bad)'}`,
            color: msg.type === 'ok' ? 'var(--good)' : 'var(--bad)',
          }}>
            {msg.text}
          </div>
        )}

        <div className="row" style={{ gap: 10 }}>
          <button type="button" className="btn btn-ghost" style={{ flex: 1 }}
                  onClick={() => setState({ view: 'dashboard' })}>
            ← ZURÜCK
          </button>
          <button type="submit" className="btn btn-primary" style={{ flex: 2 }}
                  disabled={saving || !name.trim()}>
            {saving ? 'SPEICHERN…' : '✓ SPEICHERN'}
          </button>
        </div>
      </form>
    </div>
  );
}

Object.assign(window, { AuthScreen, LoadingScreen, Dashboard, ProfileScreen });
