// Turnering-detalj — full side for én turnering.
// Brukes via onNav("turnering", { tournamentId: "t3" })

// ─── Hjelpe-funksjoner ───────────────────────────────────────────────────────

const formatTrnDate = (s) => {
  if (!s) return null;
  const d = new Date(s);
  const days = ["SØN","MAN","TIR","ONS","TOR","FRE","LØR"];
  const day  = days[d.getDay()];
  const date = String(d.getDate()).padStart(2,"0") + "." + String(d.getMonth()+1).padStart(2,"0");
  const time = String(d.getHours()).padStart(2,"0") + ":" + String(d.getMinutes()).padStart(2,"0");
  return { day, date, time };
};

// Aggreger verified submissions → per-lag leaderboard-rader
const buildLeaderboard = (submissions, teams) => {
  const map = {};
  // Seed fra teams
  (teams || []).forEach(t => {
    const key = t.id || t.team_name;
    map[key] = {
      id:   t.id,
      tag:  t.team_tag  || t.tag  || "—",
      name: t.team_name || t.name || "—",
      kills: 0, points: 0, games: 0,
      perGame: [],
    };
  });
  submissions.forEach(s => {
    const key = s.team_id || s.submitted_by_tag;
    if (!key) return;
    if (!map[key]) {
      map[key] = {
        id: key,
        tag: s.submitted_by_tag || "—",
        name: s.submitted_by_tag || "—",
        kills: 0, points: 0, games: 0,
        perGame: [],
      };
    }
    map[key].kills  += (s.kills   || 0);
    map[key].points += (s.points  || 0);
    map[key].games  += 1;
    map[key].perGame.push({ game: s.game || map[key].games, kills: s.kills || 0, points: s.points || 0, placement: s.placement || null });
  });
  return Object.values(map).sort((a, b) => b.points - a.points || b.kills - a.kills);
};

// ─── Live Leaderboard ────────────────────────────────────────────────────────

const LiveLeaderboard = ({ tournamentId, teams, accent, isLive }) => {
  const [subs, setSubs] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [lastUpdated, setLastUpdated] = React.useState(null);

  const reload = React.useCallback(() => {
    WZN_Store.getVerifiedSubmissions(tournamentId).then(data => {
      setSubs(data || []);
      setLoading(false);
      setLastUpdated(new Date());
    });
  }, [tournamentId]);

  React.useEffect(() => {
    reload();
    if (!isLive) return;
    // Realtime-oppdatering
    const unsub = WZN_Store.subscribeTournamentSubmissions(tournamentId, () => reload());
    return unsub;
  }, [tournamentId, isLive, reload]);

  const rows = React.useMemo(() => buildLeaderboard(subs, teams), [subs, teams]);

  if (loading) return (
    <div style={{ padding: "48px 0", textAlign: "center", fontFamily: "var(--font-mono)", color: "var(--text-faint)", letterSpacing: "0.18em" }}>
      LASTER LEADERBOARD…
    </div>
  );

  if (rows.length === 0) return (
    <div style={{ padding: "48px 0", textAlign: "center" }}>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-faint)", letterSpacing: "0.18em" }}>
        INGEN GODKJENTE INNSENDINGER ENNÅ
      </div>
      {isLive && (
        <div style={{ fontFamily: "var(--font-body)", fontSize: 14, color: "var(--text-faint)", marginTop: 8 }}>
          Kapteiner sender inn score etter hvert game — da vises de her.
        </div>
      )}
    </div>
  );

  const maxGames = Math.max(...rows.map(r => r.perGame.length), 0);

  return (
    <div>
      {/* Podium top-3 */}
      {rows.length >= 3 && (
        <div style={{ display: "flex", gap: 12, marginBottom: 32, justifyContent: "center" }}>
          {[rows[1], rows[0], rows[2]].map((r, i) => {
            const place = i === 0 ? 2 : i === 1 ? 1 : 3;
            const isFirst = place === 1;
            return (
              <div key={r.id} style={{
                flex: 1, maxWidth: 240,
                background: "var(--bg-1)", border: `1px solid ${isFirst ? accent : "var(--line)"}`,
                padding: 20, textAlign: "center", position: "relative",
                marginTop: isFirst ? 0 : 20,
              }}>
                {isFirst && <div style={{ position: "absolute", top: -1, left: 0, right: 0, height: 2, background: accent }} />}
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: isFirst ? accent : "var(--text-faint)", letterSpacing: "0.25em", marginBottom: 10 }}>
                  {place === 1 ? "1ST" : place === 2 ? "2ND" : "3RD"}
                </div>
                <div style={{
                  fontFamily: "var(--font-stencil)", fontSize: 14, padding: "4px 10px",
                  border: `1px solid ${isFirst ? accent : "var(--line-2)"}`, color: isFirst ? accent : "var(--text)",
                  letterSpacing: "0.04em", display: "inline-block", marginBottom: 8,
                }}>{r.tag}</div>
                <div style={{ fontFamily: "var(--font-stencil)", fontSize: 18, letterSpacing: "0.03em" }}>{r.name}</div>
                <div style={{ marginTop: 12, fontFamily: "var(--font-stencil)", fontSize: 36, color: isFirst ? accent : "var(--text)", lineHeight: 1 }}>{r.points}</div>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.18em", marginTop: 4 }}>POENG</div>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-dim)", marginTop: 8 }}>{r.kills} KILLS · {r.games}G</div>
              </div>
            );
          })}
        </div>
      )}

      {/* Tabell */}
      <div style={{ background: "var(--bg-0)", border: "1px solid var(--line)", overflowX: "auto" }}>
        <table style={{ width: "100%", borderCollapse: "collapse", fontFamily: "var(--font-body)" }}>
          <thead>
            <tr style={{ background: "var(--bg-1)" }}>
              {["#", "TAG", "LAG", "KILLS", "POENG", "GAMES",
                ...Array.from({ length: maxGames }, (_, i) => `G${i+1}`),
              ].map((h, i) => (
                <th key={i} style={{
                  textAlign: i <= 2 ? "left" : "right",
                  padding: "10px 14px", borderBottom: "1px solid var(--line)",
                  fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)",
                  letterSpacing: "0.18em", whiteSpace: "nowrap",
                }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map((r, i) => (
              <tr key={r.id} style={{ borderBottom: "1px solid var(--line)", background: i === 0 ? `rgba(255,107,53,0.04)` : "transparent" }}>
                <td style={{ padding: "12px 14px", fontFamily: "var(--font-stencil)", fontSize: 20, color: i < 3 ? accent : "var(--text-dim)", width: 48 }}>
                  {String(i+1).padStart(2,"0")}
                </td>
                <td style={{ padding: "12px 14px" }}>
                  <span style={{
                    fontFamily: "var(--font-stencil)", fontSize: 12, padding: "3px 7px",
                    border: `1px solid ${i < 3 ? accent : "var(--line-2)"}`,
                    color: i < 3 ? accent : "var(--text)", letterSpacing: "0.04em",
                  }}>{r.tag}</span>
                </td>
                <td style={{ padding: "12px 14px", fontFamily: "var(--font-stencil)", fontSize: 14, letterSpacing: "0.04em" }}>{r.name}</td>
                <td style={{ padding: "12px 14px", fontFamily: "var(--font-mono)", fontSize: 13, textAlign: "right", color: "var(--text-dim)" }}>{r.kills}</td>
                <td style={{ padding: "12px 14px", fontFamily: "var(--font-stencil)", fontSize: 18, textAlign: "right", color: i < 3 ? accent : "var(--text)", fontWeight: 700 }}>{r.points}</td>
                <td style={{ padding: "12px 14px", fontFamily: "var(--font-mono)", fontSize: 12, textAlign: "right", color: "var(--text-faint)" }}>{r.games}</td>
                {Array.from({ length: maxGames }, (_, gi) => {
                  const g = r.perGame[gi];
                  return (
                    <td key={gi} style={{ padding: "12px 14px", fontFamily: "var(--font-mono)", fontSize: 12, textAlign: "right", color: "var(--text-dim)", borderLeft: "1px dashed var(--line-2)" }}>
                      {g ? <span title={`Placement: ${g.placement || "—"}`}>{g.kills}k</span> : <span style={{ color: "var(--text-faint)" }}>—</span>}
                    </td>
                  );
                })}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {lastUpdated && isLive && (
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.18em", marginTop: 10, textAlign: "right" }}>
          SIST OPPDATERT {lastUpdated.toLocaleTimeString("no-NO", { hour: "2-digit", minute: "2-digit", second: "2-digit" })}
        </div>
      )}
    </div>
  );
};

// ─── Admin: Match Result Modal ───────────────────────────────────────────────

const MatchResultModal = ({ m, teams, accent, onClose, onSave }) => {
  const findTeam = (id) => (teams || []).find(t => t.id === id);
  const t1 = findTeam(m.team1_id);
  const t2 = findTeam(m.team2_id);
  const [saving, setSaving] = React.useState(null); // team-id som lagres

  const pickWinner = async (winnerId, loserId) => {
    setSaving(winnerId);
    const { error } = await WZN_Store.recordMatchResult(m.id, winnerId, loserId, {});
    if (error) {
      alert("Feil: " + (error.message || error));
      setSaving(null);
      return;
    }
    onSave(); // refresh bracket
    onClose();
  };

  const resetMatch = async () => {
    if (!confirm("Nullstille denne kampen? Vinner fjernes.")) return;
    setSaving("reset");
    await window.db.from("bracket_matches").update({
      winner_id: null, status: "pending", played_at: null,
    }).eq("id", m.id);
    onSave();
    onClose();
  };

  const TeamBtn = ({ team, teamId, isOpponent }) => {
    if (!team && !teamId) return null;
    const name = team?.team_name || team?.name || "TBD";
    const tag  = team?.team_tag  || team?.tag  || "—";
    const oppId = isOpponent ? m.team1_id : m.team2_id;
    return (
      <button
        disabled={!!saving}
        onClick={() => pickWinner(teamId, oppId)}
        style={{
          flex: 1, padding: "20px 16px", cursor: saving ? "not-allowed" : "pointer",
          background: saving === teamId ? `rgba(255,107,53,0.15)` : "var(--bg-1)",
          border: `2px solid ${saving === teamId ? accent : "var(--line)"}`,
          display: "flex", flexDirection: "column", alignItems: "center", gap: 8,
          transition: "border-color 0.12s, background 0.12s",
        }}
        onMouseEnter={e => { if (!saving) { e.currentTarget.style.borderColor = accent; e.currentTarget.style.background = "rgba(255,107,53,0.06)"; } }}
        onMouseLeave={e => { if (!saving) { e.currentTarget.style.borderColor = "var(--line)"; e.currentTarget.style.background = "var(--bg-1)"; } }}
      >
        <span style={{ fontFamily: "var(--font-stencil)", fontSize: 13, padding: "4px 10px", border: `1px solid ${accent}`, color: accent, letterSpacing: "0.04em" }}>{tag}</span>
        <span style={{ fontFamily: "var(--font-stencil)", fontSize: 18, letterSpacing: "0.04em", color: "var(--text)" }}>{name}</span>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.18em", marginTop: 4 }}>
          {saving === teamId ? "LAGRER…" : "SETT SOM VINNER"}
        </span>
      </button>
    );
  };

  return (
    <div style={{
      position: "fixed", inset: 0, zIndex: 1000,
      background: "rgba(0,0,0,0.75)",
      display: "flex", alignItems: "center", justifyContent: "center",
    }} onClick={onClose}>
      <div style={{
        background: "var(--bg-1)", border: `1px solid ${accent}`,
        width: "100%", maxWidth: 500, padding: 0, position: "relative",
      }} onClick={e => e.stopPropagation()}>
        {/* Header */}
        <div style={{
          display: "flex", justifyContent: "space-between", alignItems: "center",
          padding: "14px 20px", borderBottom: "1px solid var(--line)",
          background: "var(--bg-2)",
        }}>
          <div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: accent, letterSpacing: "0.2em" }}>ADMIN · REGISTRER RESULTAT</div>
            <div style={{ fontFamily: "var(--font-stencil)", fontSize: 16, letterSpacing: "0.04em", marginTop: 2 }}>
              {m.side === "grand_final" ? "GRAND FINAL" : `${(m.side||"WB").toUpperCase().replace("WINNERS","WINNERS BRACKET").replace("LOSERS","LOSERS BRACKET")} — RUNDE ${m.round}`}
            </div>
          </div>
          <button onClick={onClose} style={{ background: "transparent", border: "1px solid var(--line)", color: "var(--text-dim)", width: 32, height: 32, cursor: "pointer", fontFamily: "var(--font-mono)", fontSize: 14 }}>✕</button>
        </div>

        {/* Team buttons */}
        <div style={{ display: "flex", gap: 12, padding: 20 }}>
          <TeamBtn team={t1} teamId={m.team1_id} isOpponent={false} />
          <div style={{ display: "flex", alignItems: "center", fontFamily: "var(--font-stencil)", fontSize: 20, color: "var(--text-faint)" }}>VS</div>
          <TeamBtn team={t2} teamId={m.team2_id} isOpponent={true} />
        </div>

        {/* Footer */}
        <div style={{
          display: "flex", justifyContent: "space-between", alignItems: "center",
          padding: "12px 20px", borderTop: "1px solid var(--line)", background: "var(--bg-2)",
        }}>
          {m.status === "completed" ? (
            <button onClick={resetMatch} disabled={!!saving} style={{
              background: "transparent", border: "1px solid var(--line-2)",
              fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.15em",
              color: "var(--text-faint)", padding: "8px 14px", cursor: "pointer",
            }}>NULLSTILL RESULTAT</button>
          ) : <div />}
          <button onClick={onClose} style={{
            background: "transparent", border: "1px solid var(--line)",
            fontFamily: "var(--font-stencil)", fontSize: 12, letterSpacing: "0.06em",
            color: "var(--text-dim)", padding: "8px 16px", cursor: "pointer",
          }}>AVBRYT</button>
        </div>
      </div>
    </div>
  );
};

// ─── Live Bracket ────────────────────────────────────────────────────────────

const MatchCard = ({ m, teams, accent, isAdmin, onAdminClick }) => {
  const findTeam = (id) => (teams || []).find(t => t.id === id);
  const t1 = findTeam(m.team1_id);
  const t2 = findTeam(m.team2_id);
  const winner = m.winner_id;
  const isLive = m.status === "live";
  const isDone = m.status === "completed";
  const isBye  = m.status === "bye";
  const canEdit = isAdmin && !isBye;

  const TeamSlot = ({ team, teamId, isWin }) => {
    if (!team && !teamId) return (
      <div style={{ padding: "8px 12px", fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-faint)", letterSpacing: "0.12em" }}>
        TBD
      </div>
    );
    const name = team?.team_name || team?.name || "—";
    const tag  = team?.team_tag  || team?.tag  || "—";
    return (
      <div style={{
        display: "flex", alignItems: "center", gap: 10, padding: "8px 12px",
        background: isWin ? `rgba(255,107,53,0.08)` : "transparent",
        borderLeft: isWin ? `2px solid ${accent}` : "2px solid transparent",
      }}>
        <span style={{
          fontFamily: "var(--font-stencil)", fontSize: 11, padding: "2px 6px",
          border: `1px solid ${isWin ? accent : "var(--line-2)"}`,
          color: isWin ? accent : "var(--text-dim)", letterSpacing: "0.04em", flexShrink: 0,
        }}>{tag}</span>
        <span style={{ fontFamily: "var(--font-stencil)", fontSize: 13, letterSpacing: "0.03em", flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", color: isWin ? "var(--text)" : isDone ? "var(--text-faint)" : "var(--text)" }}>{name}</span>
        {isWin && <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: accent }}>✓</span>}
      </div>
    );
  };

  return (
    <div
      onClick={canEdit ? () => onAdminClick(m) : undefined}
      style={{
        border: `1px solid ${isLive ? accent : isDone ? "var(--line-2)" : "var(--line)"}`,
        background: "var(--bg-0)", marginBottom: 8, minWidth: 200, maxWidth: 260,
        position: "relative", overflow: "hidden",
        cursor: canEdit ? "pointer" : "default",
        transition: "border-color 0.12s",
      }}
      onMouseEnter={e => { if (canEdit) e.currentTarget.style.borderColor = accent; }}
      onMouseLeave={e => { if (canEdit) e.currentTarget.style.borderColor = isLive ? accent : isDone ? "var(--line-2)" : "var(--line)"; }}
    >
      {isLive && <div style={{ position: "absolute", top: 0, left: 0, right: 0, height: 1, background: accent }} />}
      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "center",
        padding: "4px 10px", borderBottom: "1px solid var(--line)",
        background: "var(--bg-2)",
      }}>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 9, color: "var(--text-faint)", letterSpacing: "0.18em" }}>
          {m.side === "grand_final" ? "GRAND FINAL" : `${(m.side||"wb").toUpperCase().replace("WINNERS","WB").replace("LOSERS","LB")} R${m.round}`}
        </span>
        <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
          {isLive && <span style={{ fontFamily: "var(--font-mono)", fontSize: 9, color: accent, letterSpacing: "0.15em" }}>● LIVE</span>}
          {isDone && <span style={{ fontFamily: "var(--font-mono)", fontSize: 9, color: "var(--text-faint)", letterSpacing: "0.15em" }}>✓</span>}
          {isBye  && <span style={{ fontFamily: "var(--font-mono)", fontSize: 9, color: "var(--text-faint)", letterSpacing: "0.15em" }}>BYE</span>}
          {canEdit && <span style={{ fontFamily: "var(--font-mono)", fontSize: 9, color: accent, letterSpacing: "0.12em", opacity: 0.7 }}>✎</span>}
        </div>
      </div>
      {isBye ? (
        <div style={{ padding: "8px 12px", fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-faint)" }}>
          {t1 ? (t1.team_name || t1.team_tag) : "—"} · BYE
        </div>
      ) : (
        <>
          <TeamSlot team={t1} teamId={m.team1_id} isWin={isDone && winner === m.team1_id} />
          <div style={{ height: 1, background: "var(--line)" }} />
          <TeamSlot team={t2} teamId={m.team2_id} isWin={isDone && winner === m.team2_id} />
        </>
      )}
    </div>
  );
};

const LiveBracket = ({ tournamentId, teams, accent, isLive, isAdmin }) => {
  const [matches, setMatches] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [editMatch, setEditMatch] = React.useState(null);

  const reload = React.useCallback(() => {
    WZN_Store.getBracketMatches(tournamentId).then(data => {
      setMatches(data || []);
      setLoading(false);
    });
  }, [tournamentId]);

  React.useEffect(() => {
    reload();
    const unsub = WZN_Store.subscribeBracketMatches(tournamentId, () => reload());
    return unsub;
  }, [tournamentId, reload]);

  if (loading) return (
    <div style={{ padding: "48px 0", textAlign: "center", fontFamily: "var(--font-mono)", color: "var(--text-faint)", letterSpacing: "0.18em" }}>
      LASTER BRACKET…
    </div>
  );

  if (matches.length === 0) return (
    <div style={{ padding: "48px 0", textAlign: "center" }}>
      <div style={{ fontFamily: "var(--font-stencil)", fontSize: 48, color: "rgba(255,255,255,0.04)", marginBottom: 8 }}>⊞</div>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-faint)", letterSpacing: "0.18em" }}>
        BRACKET IKKE GENERERT ENNÅ
      </div>
      <div style={{ fontFamily: "var(--font-body)", fontSize: 14, color: "var(--text-faint)", marginTop: 8 }}>
        Admin genererer bracketen når alle lag er godkjent.
      </div>
    </div>
  );

  const wb = matches.filter(m => m.side === "winners").sort((a,b) => a.round - b.round || (a.match_number||0) - (b.match_number||0));
  const lb = matches.filter(m => m.side === "losers").sort((a,b) => a.round - b.round || (a.match_number||0) - (b.match_number||0));
  const gf = matches.filter(m => m.side === "grand_final");

  const groupByRound = (arr) => {
    const rounds = {};
    arr.forEach(m => { (rounds[m.round] = rounds[m.round] || []).push(m); });
    return Object.entries(rounds).sort((a,b) => Number(a[0]) - Number(b[0]));
  };

  const wbRounds = groupByRound(wb);
  const lbRounds = groupByRound(lb);

  const completed = matches.filter(m => m.status === "completed").length;
  const bracketSize = Math.pow(2, Math.ceil(Math.log2(Math.max(teams.length, 2))));

  const SectionLabel = ({ tag, title, sub, color }) => (
    <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16 }}>
      <span style={{
        fontFamily: "var(--font-stencil)", fontSize: 14, padding: "4px 10px",
        border: `2px solid ${color || accent}`, color: color || accent, letterSpacing: "0.06em",
      }}>{tag}</span>
      <div>
        <div style={{ fontFamily: "var(--font-stencil)", fontSize: 18, letterSpacing: "0.04em" }}>{title}</div>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.15em", marginTop: 2 }}>{sub}</div>
      </div>
    </div>
  );

  return (
    <div>
      {/* Admin-banner */}
      {isAdmin && matches.length > 0 && (
        <div style={{
          display: "flex", alignItems: "center", gap: 10, marginBottom: 20,
          padding: "10px 16px", background: "rgba(255,107,53,0.06)", border: `1px solid rgba(255,107,53,0.3)`,
          fontFamily: "var(--font-mono)", fontSize: 11, color: accent, letterSpacing: "0.15em",
        }}>
          <span>✎</span>
          <span>ADMIN-MODUS: Klikk på et match-kort for å registrere vinner</span>
        </div>
      )}

      {/* Modal */}
      {editMatch && (
        <MatchResultModal
          m={editMatch}
          teams={teams}
          accent={accent}
          onClose={() => setEditMatch(null)}
          onSave={reload}
        />
      )}

      {/* Winners Bracket */}
      <div style={{ marginBottom: 32 }}>
        <SectionLabel tag="W" title="WINNERS BRACKET" sub="Tap én gang → drop til Losers Bracket" />
        <div style={{ display: "flex", gap: 16, overflowX: "auto", paddingBottom: 8 }}>
          {wbRounds.map(([round, roundMatches]) => (
            <div key={`wb-${round}`} style={{ flexShrink: 0 }}>
              <div style={{
                fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)",
                letterSpacing: "0.18em", marginBottom: 10, paddingBottom: 6,
                borderBottom: "1px solid var(--line)",
              }}>WB RUNDE {round}</div>
              {roundMatches.map(m => <MatchCard key={m.id} m={m} teams={teams} accent={accent} isAdmin={isAdmin} onAdminClick={setEditMatch} />)}
            </div>
          ))}
          {gf.length > 0 && (
            <div style={{ flexShrink: 0 }}>
              <div style={{
                fontFamily: "var(--font-mono)", fontSize: 10, color: accent,
                letterSpacing: "0.18em", marginBottom: 10, paddingBottom: 6,
                borderBottom: `1px solid ${accent}`,
              }}>GRAND FINAL</div>
              {gf.map(m => <MatchCard key={m.id} m={m} teams={teams} accent={accent} isAdmin={isAdmin} onAdminClick={setEditMatch} />)}
            </div>
          )}
        </div>
      </div>

      {/* Losers Bracket */}
      {lbRounds.length > 0 && (
        <div style={{ marginBottom: 24 }}>
          <SectionLabel tag="L" title="LOSERS BRACKET" sub="Andre sjanse — tap én gang til = ute" color="var(--text-dim)" />
          <div style={{ display: "flex", gap: 16, overflowX: "auto", paddingBottom: 8 }}>
            {lbRounds.map(([round, roundMatches]) => (
              <div key={`lb-${round}`} style={{ flexShrink: 0 }}>
                <div style={{
                  fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)",
                  letterSpacing: "0.18em", marginBottom: 10, paddingBottom: 6,
                  borderBottom: "1px solid var(--line)",
                }}>LB RUNDE {round}</div>
                {roundMatches.map(m => <MatchCard key={m.id} m={m} teams={teams} accent={accent} isAdmin={isAdmin} onAdminClick={setEditMatch} />)}
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Footer stats */}
      <div style={{
        display: "flex", gap: 0, border: "1px solid var(--line)", background: "var(--bg-1)",
        marginTop: 8, flexWrap: "wrap",
      }}>
        {[
          { l: "BRACKET STR.", v: `${bracketSize} LAG` },
          { l: "PÅMELDTE", v: teams.length },
          { l: "BYE-PLASSER", v: bracketSize - teams.length },
          { l: "MATCHER SPILT", v: `${completed}/${matches.length}` },
          { l: "FORMAT", v: "DOUBLE ELIM" },
        ].map((s, i, arr) => (
          <div key={i} style={{
            flex: 1, minWidth: 100,
            padding: "14px 18px",
            borderRight: i < arr.length - 1 ? "1px solid var(--line)" : "none",
          }}>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.18em", marginBottom: 4 }}>{s.l}</div>
            <div style={{ fontFamily: "var(--font-stencil)", fontSize: 20, letterSpacing: "0.04em" }}>{s.v}</div>
          </div>
        ))}
      </div>
    </div>
  );
};

// ─── How-it-works per turnerings-type ────────────────────────────────────────

const HOW_IT_WORKS = {
  switcharoo: {
    title: "2V2 SWITCHAROO",
    ruleTab: "switcharoo",
    steps: [
      "Meld deg på solo — ingen partner nødvendig.",
      "Admin spinner hjulet og parer deg tilfeldig med en annen deltaker.",
      "Dere spiller 2v2 BR Kill Race i 3 games (BO3).",
      "Respinn er tilgjengelig — ta kontakt med admin via Discord.",
      "Mest kills totalt vinner og deler premiepotten.",
    ],
    info: [
      "Logg inn med Discord for å melde deg på.",
      "Du trenger ingen partner — hjulet parer deg.",
      "Første seeding er gratis. Respinn koster fra 100 kr.",
      "Betal respinn via Discord til admin, som bekrefter og registrerer.",
      "Påmelding stenger ved turnerings-start.",
    ],
  },
  bracket: {
    title: "DOUBLE ELIMINATION BRACKET",
    ruleTab: "liga-bigmap",
    steps: [
      "Meld på laget ditt og vent på admin-godkjenning.",
      "Admin genererer double elimination bracket.",
      "Vinn kampen → gå videre i Winners Bracket.",
      "Tap én gang → andre sjanse i Losers Bracket.",
      "Tap i Losers Bracket = ute av turneringen.",
    ],
    info: [
      "Logg inn med Discord for å melde på laget.",
      "Screenshot av scoreboard kreves etter hvert game.",
      "AI hjelper med avlesning — admin verifiserer.",
      "Påmelding stenger 1 time før start eller ved full liste.",
    ],
  },
  "2v2": {
    title: "2V2 BRACKET (CMG)",
    ruleTab: "switcharoo",
    steps: [
      "Meld på ditt 2v2-lag.",
      "Double elimination bracket genereres av admin.",
      "CMG-scoring: mest kills vinner — damage som tiebreaker.",
      "BO3 Winners / BO2 Losers / BO5 Grand Final.",
      "Vinnerlaget tar hjem premiepotten.",
    ],
    info: [
      "Logg inn med Discord for å melde på laget.",
      "Begge spillere sender inn scorecard etter hvert game.",
      "AI leser scores — admin verifiserer.",
      "Kontakt admin via Discord ved spørsmål.",
    ],
  },
  killrace: {
    title: "KILLRACE",
    ruleTab: "killrace",
    steps: [
      "Meld deg på og vent på turnerings-start.",
      "Spill Warzone-games i tidsvinduet.",
      "Send inn screenshot av scoreboard etter hvert game.",
      "AI leser resultater — admin verifiserer.",
      "Flest kills totalt vinner. Tiebreaker: høyeste single-game killcount.",
    ],
    info: [
      "Solo / duo / trio / quads avhengig av format.",
      "Alle games i tidsvinduet teller.",
      "Send screenshots raskt — forsinkede innsendinger kan avvises.",
      "Kontakt admin via Discord ved tekniske problemer.",
    ],
  },
};

// ─── Respin-tracker (Switcharoo) ─────────────────────────────────────────────

const RespinTracker = ({ t, accent, isAdmin, onReload }) => {
  const respinCount = t?.respin_count || 0;
  const [adding, setAdding] = React.useState(false);

  const nextCost  = Math.round(100 * Math.pow(2, respinCount));
  const totalRev  = respinCount > 0 ? Math.round(100 * (Math.pow(2, respinCount) - 1)) : 0;
  const history   = Array.from({ length: respinCount }, (_, i) => ({ n: i + 1, cost: Math.round(100 * Math.pow(2, i)) }));

  const addRespin = async () => {
    if (!confirm(`Registrer betalt respinn (${nextCost} kr)?`)) return;
    setAdding(true);
    await window.db.from("tournaments").update({ respin_count: respinCount + 1 }).eq("id", t.id);
    setAdding(false);
    onReload();
  };

  return (
    <div style={{ border: "1px solid var(--line)", background: "var(--bg-1)", marginTop: 28 }}>
      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "center",
        padding: "12px 20px", borderBottom: "1px solid var(--line)", background: "var(--bg-2)",
      }}>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.2em", color: accent }}>
          RESPIN-TRACKER
        </div>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: totalRev > 0 ? accent : "var(--text-faint)", letterSpacing: "0.12em" }}>
          {totalRev > 0 ? `+${totalRev.toLocaleString()} KR FRA RESPINS` : "INGEN RESPINS ENNÅ"}
        </div>
      </div>
      <div style={{ padding: "18px 20px" }}>
        {history.length > 0 && (
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 16 }}>
            {history.map(s => (
              <div key={s.n} style={{
                fontFamily: "var(--font-mono)", fontSize: 10, padding: "4px 10px",
                border: `1px solid ${accent}`, color: accent, letterSpacing: "0.12em",
              }}>RESPIN #{s.n} · {s.cost} KR</div>
            ))}
          </div>
        )}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end" }}>
          <div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.18em" }}>NESTE RESPIN KOSTER</div>
            <div style={{ fontFamily: "var(--font-stencil)", fontSize: 36, color: accent, lineHeight: 1, marginTop: 4 }}>
              {nextCost.toLocaleString()} KR
            </div>
          </div>
          <div style={{ textAlign: "right" }}>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.15em", marginBottom: 4 }}>BETALING</div>
            <div style={{ fontFamily: "var(--font-stencil)", fontSize: 14, color: "var(--text-dim)", letterSpacing: "0.04em" }}>KONTAKT ADMIN PÅ DISCORD</div>
          </div>
        </div>
        {isAdmin && (
          <button onClick={addRespin} disabled={adding} style={{
            marginTop: 16, padding: "11px 20px", width: "100%",
            background: adding ? "var(--bg-3)" : accent,
            color: "var(--bg-0)", border: `1px solid ${accent}`,
            fontFamily: "var(--font-stencil)", fontSize: 13, letterSpacing: "0.06em",
            cursor: adding ? "not-allowed" : "pointer",
          }}>
            {adding ? "REGISTRERER…" : `✓ REGISTRER BETALT RESPIN (${nextCost.toLocaleString()} KR)`}
          </button>
        )}
      </div>
    </div>
  );
};

// ─── Hoved-komponent ─────────────────────────────────────────────────────────

const TurneringDetailPage = ({ accent, tournamentId, onNav, userRole }) => {
  const isAdmin = userRole && ["admin", "superadmin", "mod"].includes(userRole);
  const [t, setT] = React.useState(null);
  const [teams, setTeams] = React.useState([]);
  const [soloPlayers, setSoloPlayers] = React.useState([]);
  const [loadingT, setLoadingT] = React.useState(true);
  const [tab, setTab] = React.useState("oversikt");
  const [reloadKey, setReloadKey] = React.useState(0);

  const loadTournament = React.useCallback(() => {
    setLoadingT(true);
    window.db.from("tournaments").select("*").eq("id", tournamentId).single()
      .then(({ data }) => {
        setT(data || null);
        setLoadingT(false);
      });
  }, [tournamentId]);

  React.useEffect(() => { loadTournament(); }, [loadTournament, reloadKey]);

  React.useEffect(() => {
    if (!t) return;
    WZN_Store.getTournamentTeams(tournamentId).then(data => setTeams(data || []));
    if (t.type === "switcharoo") {
      window.db.from("player_registrations")
        .select("id, display_name, discord_name, gamertag, status, created_at")
        .eq("tournament_id", tournamentId)
        .order("created_at")
        .then(({ data }) => setSoloPlayers(data || []));
    }
  }, [t, tournamentId]);

  // Compute tabs here (before early returns) to satisfy Rules of Hooks
  const tabs = React.useMemo(() => {
    if (!t) return [];
    const type_       = t.type || "";
    const isBracket_  = type_ === "bracket" || type_ === "2v2" || type_ === "switcharoo";
    const isSwitch_   = type_ === "switcharoo";
    const isLive_     = t.status === "live";
    const isPast_     = t.status === "completed";
    const list = [
      { id: "oversikt",   label: "OVERSIKT" },
      { id: "deltakere",  label: "DELTAKERE" },
      { id: "premie",     label: "PREMIE" },
    ];
    if (isBracket_) list.push({ id: "bracket",     label: "BRACKET",     dot: isLive_ });
    if (isLive_ || isPast_) list.push({ id: "leaderboard", label: "LEADERBOARD", dot: isLive_ && !isBracket_ });
    if (isSwitch_)  list.push({ id: "hjul",        label: "HJUL" });
    return list;
  }, [t]);

  if (loadingT) {
    return (
      <div style={{ padding: "120px 48px", textAlign: "center", fontFamily: "var(--font-mono)", color: "var(--text-faint)" }}>
        LASTER…
      </div>
    );
  }

  if (!t) {
    return (
      <section style={{ padding: "120px 48px", textAlign: "center" }}>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: accent, letterSpacing: "0.25em", marginBottom: 16 }}>ERROR / 404</div>
        <h1 style={{ fontFamily: "var(--font-stencil)", fontSize: 56, margin: 0 }}>TURNERING IKKE FUNNET</h1>
        <button onClick={() => onNav("turneringer")} style={{
          marginTop: 28, padding: "14px 22px", cursor: "pointer",
          background: "transparent", border: "1px solid var(--line)",
          fontFamily: "var(--font-stencil)", fontSize: 13, letterSpacing: "0.06em", color: "var(--text-dim)",
        }}>← TILBAKE TIL ALLE TURNERINGER</button>
      </section>
    );
  }

  const isPast     = t.status === "completed";
  const isLive     = t.status === "live";
  const isOpen     = !isPast && !isLive;
  const isSwitcharoo = t.type === "switcharoo";
  const isBracket  = t.type === "bracket" || t.type === "2v2" || isSwitcharoo;
  const dt         = t.start_date ? formatTrnDate(t.start_date) : null;
  const registered = t.registered || 0;
  const maxSlots   = t.max_teams || 1;
  const pct        = !isPast ? (registered / maxSlots) * 100 : 100;

  // Live prize pool
  const entryFee    = t.entry_fee || 0;
  const cashInj     = t.cash_injection || 0;
  const respinCount = t.respin_count || 0;
  const respinRev   = respinCount > 0 ? Math.round(100 * (Math.pow(2, respinCount) - 1)) : 0;
  const livePrizePool = entryFee * registered + cashInj + (isSwitcharoo ? respinRev : 0);

  // Prize split: array of 6 percentages, or fallback
  const prizeSplit = Array.isArray(t.prize_split) ? t.prize_split : [50, 25, 10, 5, 5, 5];
  const splitLabels = ["1. PLASS", "2. PLASS", "3. PLASS", "4. PLASS", "5. PLASS", "6. PLASS"];

  const howIt = HOW_IT_WORKS[t.type] || HOW_IT_WORKS["bracket"];

  return (
    <>
      {/* Breadcrumb */}
      <section style={{
        padding: "20px 48px", background: "var(--bg-1)", borderBottom: "1px solid var(--line)",
        display: "flex", alignItems: "center", gap: 18,
        fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.18em",
      }}>
        <button onClick={() => onNav("turneringer")} style={{
          background: "transparent", border: "none", cursor: "pointer", padding: 0,
          color: "var(--text-dim)", fontFamily: "inherit", fontSize: 11, letterSpacing: "0.18em",
        }}>← TURNERINGER</button>
        <span style={{ color: "var(--text-faint)" }}>/</span>
        <span style={{ color: accent }}>{(t.name || "").toUpperCase()}</span>
      </section>

      {/* Hero */}
      <section style={{
        padding: "56px 48px 48px", borderBottom: "1px solid var(--line)",
        position: "relative", overflow: "hidden", background: "var(--bg-0)",
      }}>
        <div style={{
          position: "absolute", right: -40, top: -100,
          fontFamily: "var(--font-stencil)", fontSize: 400, lineHeight: 0.9,
          color: "rgba(255,255,255,0.022)", pointerEvents: "none", letterSpacing: "-0.02em",
        }}>{isLive ? "LIVE" : isPast ? "DONE" : (t.type || "bracket").toUpperCase()}</div>

        <div style={{ position: "relative", zIndex: 1, display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 48, alignItems: "center" }}>
          <div>
            <div style={{
              display: "inline-flex", alignItems: "center", gap: 10,
              border: `1px solid ${isPast ? "var(--line-2)" : accent}`,
              padding: "5px 12px",
              fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.2em",
              color: isPast ? "var(--text-dim)" : accent, marginBottom: 20,
            }}>
              {isLive && <span style={{ width: 8, height: 8, background: accent, borderRadius: "50%" }} />}
              {isLive ? "LIVE NÅ · " : isPast ? "AVSLUTTET · " : "PÅMELDING ÅPEN · "}
              {(t.type || "bracket").toUpperCase()}
            </div>
            <h1 style={{
              fontFamily: "var(--font-stencil)", fontSize: 96, letterSpacing: "0.01em", lineHeight: 0.95, margin: 0,
            }}>{(t.name || "").toUpperCase()}</h1>
            <div style={{
              fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--text-dim)",
              letterSpacing: "0.12em", marginTop: 14,
            }}>
              {(t.team_size || "solos").toUpperCase()}
              {t.games && ` · ${t.games} GAMES`}
              {t.maps && t.maps.length ? ` · ${t.maps.join(" · ").toUpperCase()}` : ""}
            </div>

            {/* Stat strip */}
            <div style={{
              display: "grid", gridTemplateColumns: "repeat(4, 1fr)",
              border: "1px solid var(--line)", marginTop: 28, background: "var(--bg-1)",
            }}>
              {[
                { n: dt ? dt.date : "—", l: dt ? dt.day.toUpperCase() : "DATO" },
                { n: dt ? dt.time : "—", l: "STARTER" },
                { n: `${registered}/${maxSlots}`, l: isSwitcharoo ? "SPILLERE" : "LAG" },
                { n: livePrizePool >= 1000 ? `${(livePrizePool/1000).toFixed(1)}K kr` : `${livePrizePool} kr`, l: "PREMIEPOTT", accent: true },
              ].map((s, i) => (
                <div key={i} style={{ padding: "16px 18px", borderRight: i < 3 ? "1px solid var(--line)" : "none" }}>
                  <div style={{ fontFamily: "var(--font-stencil)", fontSize: 30, lineHeight: 1, color: s.accent ? accent : "var(--text)" }}>{s.n}</div>
                  <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.18em", marginTop: 6 }}>{s.l}</div>
                </div>
              ))}
            </div>
          </div>

          {/* Action card */}
          <div style={{ background: "var(--bg-2)", border: `1px solid ${accent}`, padding: 28, position: "relative" }}>
            <span className="hcard-corners"><span /><span /><span /><span /></span>
            <div style={{
              fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)",
              letterSpacing: "0.2em", paddingBottom: 12, borderBottom: "1px solid var(--line)",
            }}>
              {isPast ? "RESULTAT" : isLive ? "FØLG LIVE" : "PÅMELDING"}
            </div>
            {!isPast && (
              <div style={{ marginTop: 16 }}>
                <div style={{ position: "relative", height: 6, background: "var(--bg-3)", border: "1px solid var(--line-2)" }}>
                  <div style={{ position: "absolute", inset: 0, width: `${Math.min(pct,100)}%`, background: accent }} />
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-faint)", letterSpacing: "0.15em" }}>
                  <span>{registered}/{maxSlots} {isSwitcharoo ? "SPILLERE" : "LAG"}</span>
                  <span>{maxSlots - registered} LEDIGE</span>
                </div>
              </div>
            )}
            {isPast && t.winner && (
              <div style={{ marginTop: 18, marginBottom: 18 }}>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.18em" }}>VINNER</div>
                <div style={{ display: "flex", alignItems: "center", gap: 14, marginTop: 10 }}>
                  <span style={{ fontFamily: "var(--font-stencil)", fontSize: 18, padding: "6px 12px", border: `2px solid ${accent}`, color: accent, letterSpacing: "0.04em" }}>{t.winner.tag || "—"}</span>
                  <span style={{ fontFamily: "var(--font-stencil)", fontSize: 26, letterSpacing: "0.04em" }}>{t.winner.name || "—"}</span>
                </div>
              </div>
            )}
            {isOpen && (
              <button onClick={() => onNav("pamelding", { tournamentId })} style={{
                marginTop: 18, padding: "14px 18px", width: "100%", cursor: "pointer",
                display: "flex", alignItems: "center", justifyContent: "space-between",
                background: accent, border: `1px solid ${accent}`,
                fontFamily: "var(--font-stencil)", fontSize: 13, fontWeight: 700, letterSpacing: "0.06em", color: "var(--bg-0)",
              }}>
                <span>{isSwitcharoo ? "MELD DEG PÅ SOLO" : "PÅMELD LAGET DITT"}</span><span>▶</span>
              </button>
            )}
            {isLive && (
              <a href="https://www.twitch.tv/magicsidd" target="_blank" rel="noopener" style={{
                marginTop: 18, display: "flex", alignItems: "center", justifyContent: "space-between",
                background: accent, color: "var(--bg-0)", fontFamily: "var(--font-stencil)", fontSize: 13, fontWeight: 700, letterSpacing: "0.06em",
                padding: "14px 18px", textDecoration: "none", border: `1px solid ${accent}`,
              }}>
                <span>FØLG LIVE PÅ TWITCH</span><span>▶</span>
              </a>
            )}
          </div>
        </div>
      </section>

      {/* ── Tab-bar ──────────────────────────────────────── */}
      <section style={{ background: "var(--bg-1)", borderBottom: "1px solid var(--line)", position: "sticky", top: 58, zIndex: 10 }}>
        <div style={{ display: "flex", alignItems: "stretch", padding: "0 48px", height: 52 }}>
          {isLive && (
            <div style={{ display: "flex", alignItems: "center", gap: 8, paddingRight: 24, borderRight: "1px solid var(--line)", marginRight: 16, fontFamily: "var(--font-mono)", fontSize: 11, color: accent, letterSpacing: "0.18em" }}>
              <span style={{ width: 8, height: 8, background: accent, borderRadius: "50%", animation: "pulse 1.5s infinite" }} />
              LIVE NÅ
            </div>
          )}
          {tabs.map(t_ => (
            <button key={t_.id} onClick={() => setTab(t_.id)} style={{
              padding: "0 18px", height: "100%",
              background: tab === t_.id ? "var(--bg-2)" : "transparent",
              border: "none",
              borderBottom: tab === t_.id ? `2px solid ${accent}` : "2px solid transparent",
              fontFamily: "var(--font-stencil)", fontSize: 12, letterSpacing: "0.06em",
              color: tab === t_.id ? "var(--text)" : "var(--text-dim)",
              cursor: "pointer", display: "flex", alignItems: "center", gap: 8,
            }}>
              {t_.dot && <span style={{ width: 6, height: 6, background: accent, borderRadius: "50%" }} />}
              {t_.label}
            </button>
          ))}
        </div>
      </section>

      {/* ── Tab-innhold ──────────────────────────────────── */}
      <section style={{ padding: "40px 48px", borderBottom: "1px solid var(--line)" }}>

        {/* OVERSIKT */}
        {tab === "oversikt" && (
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 40 }}>
            <div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: accent, letterSpacing: "0.25em", marginBottom: 10 }}>HVORDAN FUNGERER DET</div>
              <h2 style={{ fontFamily: "var(--font-stencil)", fontSize: 36, margin: "0 0 24px" }}>{howIt.title}</h2>
              <ol style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 14 }}>
                {howIt.steps.map((step, i) => (
                  <li key={i} style={{ display: "grid", gridTemplateColumns: "32px 1fr", gap: 12, alignItems: "baseline" }}>
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: accent, letterSpacing: "0.15em" }}>0{i+1}</span>
                    <span style={{ fontFamily: "var(--font-body)", fontSize: 15, color: "var(--text-dim)", lineHeight: 1.6 }}>{step}</span>
                  </li>
                ))}
              </ol>
              <button onClick={() => onNav("regler")} style={{ marginTop: 28, padding: "12px 18px", border: `1px solid ${accent}`, color: accent, background: "transparent", fontFamily: "var(--font-stencil)", fontSize: 12, letterSpacing: "0.06em", cursor: "pointer" }}>
                LES FULLT REGELSETT →
              </button>
            </div>
            <div style={{ background: "var(--bg-2)", border: "1px solid var(--line)", padding: 24 }}>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.2em", paddingBottom: 12, borderBottom: "1px solid var(--line)", marginBottom: 18 }}>
                VIKTIG Å VITE
              </div>
              <ul style={{ listStyle: "none", padding: 0, margin: "0 0 24px", display: "flex", flexDirection: "column", gap: 12 }}>
                {howIt.info.map((line, i) => (
                  <li key={i} style={{ display: "grid", gridTemplateColumns: "20px 1fr", gap: 10, alignItems: "baseline", fontFamily: "var(--font-body)", fontSize: 14, color: "var(--text-dim)", lineHeight: 1.6 }}>
                    <span style={{ color: accent, fontWeight: 700 }}>▸</span>
                    <span>{line}</span>
                  </li>
                ))}
              </ul>
              <div style={{ borderTop: "1px solid var(--line)", paddingTop: 18 }}>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.18em", marginBottom: 12 }}>FORMAT</div>
                {[
                  { k: "GAMEMODE", v: t.type === "killrace" ? "KILLRACE" : "BR " + (t.team_size || "solos").toUpperCase() },
                  { k: "GAMES", v: `${t.games || 3}` },
                  { k: "MAPS", v: t.maps && t.maps.length ? t.maps.join(", ") : "TBD" },
                  { k: "STARTER", v: dt ? `${dt.day} ${dt.date} · ${dt.time}` : (t.date || "—") },
                ].map(r => (
                  <div key={r.k} style={{ display: "grid", gridTemplateColumns: "100px 1fr", gap: 8, paddingBottom: 8, borderBottom: "1px dashed var(--line-2)", marginBottom: 8 }}>
                    <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.15em" }}>{r.k}</div>
                    <div style={{ fontFamily: "var(--font-stencil)", fontSize: 13, letterSpacing: "0.04em" }}>{r.v}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}

        {/* DELTAKERE */}
        {tab === "deltakere" && (
          <>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: accent, letterSpacing: "0.25em", marginBottom: 10 }}>
              {isSwitcharoo ? "SOLO-DELTAKERE" : "PÅMELDTE LAG"}
            </div>
            <h2 style={{ fontFamily: "var(--font-stencil)", fontSize: 36, margin: "0 0 28px" }}>
              {isSwitcharoo ? `${soloPlayers.length} SPILLERE PÅMELDT` : `${teams.length} LAG PÅMELDT`}
            </h2>
            {isSwitcharoo ? (
              soloPlayers.length === 0 ? (
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-faint)", letterSpacing: "0.18em" }}>INGEN PÅMELDT ENNÅ</div>
              ) : (
                <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 10 }}>
                  {soloPlayers.map((p, i) => (
                    <div key={p.id} style={{ background: "var(--bg-1)", border: "1px solid var(--line)", padding: "14px 16px", display: "flex", alignItems: "center", gap: 12 }}>
                      <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.18em", minWidth: 24 }}>#{String(i+1).padStart(2,"0")}</span>
                      <div>
                        <div style={{ fontFamily: "var(--font-stencil)", fontSize: 14, letterSpacing: "0.04em" }}>{p.display_name || p.discord_name || "—"}</div>
                        {p.gamertag && <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.12em", marginTop: 3 }}>{p.gamertag}</div>}
                      </div>
                      {p.status === "in_team" && (
                        <span style={{ marginLeft: "auto", fontFamily: "var(--font-mono)", fontSize: 9, color: accent, letterSpacing: "0.15em", border: `1px solid ${accent}`, padding: "2px 6px" }}>PARET</span>
                      )}
                    </div>
                  ))}
                </div>
              )
            ) : (
              teams.length === 0 ? (
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-faint)", letterSpacing: "0.18em" }}>INGEN LAG REGISTRERT</div>
              ) : (
                <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10 }}>
                  {teams.map((team, i) => (
                    <div key={team.id || i} style={{ background: "var(--bg-1)", border: "1px solid var(--line)", padding: "14px 16px", display: "flex", alignItems: "center", gap: 12 }}>
                      <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.18em", minWidth: 24 }}>#{String(i+1).padStart(2,"0")}</span>
                      <span style={{ fontFamily: "var(--font-stencil)", fontSize: 12, padding: "3px 7px", border: "1px solid var(--line-2)", color: "var(--text)", letterSpacing: "0.04em" }}>{team.team_tag || "—"}</span>
                      <span style={{ fontFamily: "var(--font-stencil)", fontSize: 14, letterSpacing: "0.04em", flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{team.team_name || "—"}</span>
                    </div>
                  ))}
                </div>
              )
            )}
          </>
        )}

        {/* PREMIE */}
        {tab === "premie" && (
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 40 }}>
            <div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: accent, letterSpacing: "0.25em", marginBottom: 10 }}>PREMIEPOTT</div>
              <h2 style={{ fontFamily: "var(--font-stencil)", fontSize: 56, margin: "0 0 4px", color: accent }}>
                {livePrizePool >= 1000 ? `${(livePrizePool/1000).toFixed(1)}K` : livePrizePool} KR
              </h2>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-faint)", letterSpacing: "0.18em", marginBottom: 28 }}>
                TOTAL POTT (OPPDATERES AUTOMATISK)
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 28 }}>
                {[
                  { l: "PÅMELDINGSAVGIFT", v: `${registered} × ${entryFee} kr = ${registered * entryFee} kr` },
                  cashInj > 0 && { l: "CASH INJECTION", v: `+${cashInj} kr` },
                  isSwitcharoo && respinRev > 0 && { l: "RESPINN-INNTEKT", v: `+${respinRev} kr (${respinCount} respinn)` },
                ].filter(Boolean).map(r => (
                  <div key={r.l} style={{ display: "grid", gridTemplateColumns: "160px 1fr", gap: 8, paddingBottom: 8, borderBottom: "1px dashed var(--line-2)" }}>
                    <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.15em" }}>{r.l}</div>
                    <div style={{ fontFamily: "var(--font-body)", fontSize: 13, color: "var(--text-dim)" }}>{r.v}</div>
                  </div>
                ))}
              </div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.2em", paddingBottom: 12, borderBottom: "1px solid var(--line)", marginBottom: 16 }}>
                FORDELING
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                {prizeSplit.map((pct_, i) => {
                  if (pct_ === 0) return null;
                  const kr = Math.round(livePrizePool * pct_ / 100);
                  return (
                    <div key={i} style={{ display: "grid", gridTemplateColumns: "100px 1fr auto", gap: 12, alignItems: "center" }}>
                      <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-faint)", letterSpacing: "0.15em" }}>{splitLabels[i]}</div>
                      <div style={{ height: 6, background: "var(--bg-3)", border: "1px solid var(--line-2)", position: "relative" }}>
                        <div style={{ position: "absolute", inset: 0, width: `${pct_}%`, background: i === 0 ? accent : "var(--text-dim)" }} />
                      </div>
                      <div style={{ fontFamily: "var(--font-stencil)", fontSize: 14, color: i === 0 ? accent : "var(--text)", letterSpacing: "0.04em", textAlign: "right", minWidth: 80 }}>
                        {kr} kr <span style={{ fontSize: 10, color: "var(--text-faint)" }}>({pct_}%)</span>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
            {isSwitcharoo && (
              <RespinTracker t={t} accent={accent} isAdmin={isAdmin} onReload={() => setReloadKey(k => k + 1)} />
            )}
          </div>
        )}

        {/* BRACKET */}
        {tab === "bracket" && (
          <>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: accent, letterSpacing: "0.25em", marginBottom: 10 }}>
              {isLive ? "● LIVE" : "ARKIV"} / BRACKET
            </div>
            <h2 style={{ fontFamily: "var(--font-stencil)", fontSize: 36, margin: "0 0 28px" }}>
              {isLive ? "LIVE BRACKET" : "BRACKET-RESULTAT"}
            </h2>
            <LiveBracket tournamentId={tournamentId} teams={teams} accent={accent} isLive={isLive} isAdmin={isAdmin} />
          </>
        )}

        {/* LEADERBOARD */}
        {tab === "leaderboard" && (
          <>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: accent, letterSpacing: "0.25em", marginBottom: 10 }}>
              {isLive ? "● LIVE" : "RESULTATER"} / LEADERBOARD
            </div>
            <h2 style={{ fontFamily: "var(--font-stencil)", fontSize: 36, margin: "0 0 28px" }}>
              {isLive ? "LIVE LEADERBOARD" : "SLUTTRESULTAT"}
            </h2>
            <LiveLeaderboard tournamentId={tournamentId} teams={teams} accent={accent} isLive={isLive} />
          </>
        )}

        {/* HJUL */}
        {tab === "hjul" && (
          <>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: accent, letterSpacing: "0.25em", marginBottom: 10 }}>SWITCHAROO / HJUL</div>
            <h2 style={{ fontFamily: "var(--font-stencil)", fontSize: 36, margin: "0 0 28px" }}>SPIN THE WHEEL</h2>
            {isAdmin ? (
              typeof SwitcharooWheel !== "undefined" ? (
                <SwitcharooWheel tournamentId={tournamentId} accent={accent} />
              ) : (
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-faint)", letterSpacing: "0.18em" }}>LASTER HJUL-KOMPONENT…</div>
              )
            ) : (
              <div style={{ background: "var(--bg-2)", border: "1px solid var(--line)", padding: 28, maxWidth: 480 }}>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: accent, letterSpacing: "0.2em", marginBottom: 12 }}>SEEDING</div>
                <div style={{ fontFamily: "var(--font-body)", fontSize: 15, color: "var(--text-dim)", lineHeight: 1.7 }}>
                  Admin spinner hjulet og parer spillere tilfeldig. Du vil se hvem som er partneren din her etter seeding er kjørt.
                </div>
                <div style={{ marginTop: 18, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-faint)", letterSpacing: "0.15em" }}>
                  Ønsker du et nytt par? Kontakt admin via Discord. Respinn koster fra 100 kr.
                </div>
              </div>
            )}
          </>
        )}

      </section>
    </>
  );
};

Object.assign(window, { TurneringDetailPage });
