// Min Side — full spiller-dashboard med profil, lag, turneringer og innstillinger.

const MinSidePage = ({ accent, onNav, isLoggedIn, discordUser }) => {
  const handleLoginDiscord = async () => {
    if (!window.db) { alert("Supabase ikke initialisert"); return; }
    const { error } = await window.db.auth.signInWithOAuth({
      provider: "discord",
      options: { redirectTo: window.location.origin },
    });
    if (error) alert("Login feilet: " + error.message);
  };
  const handleLogout = async () => {
    if (window.db) await window.db.auth.signOut();
  };
  if (!isLoggedIn) return <LoginPrompt accent={accent} onLoginDiscord={handleLoginDiscord} />;
  return <MinSideDashboard accent={accent} discordUser={discordUser} onNav={onNav} onLogout={handleLogout} />;
};

// ───────── Login prompt ─────────
const LoginPrompt = ({ accent, onLoginDiscord }) => {
  const [mode, setMode] = React.useState("main");
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [displayName, setDisplayName] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [err, setErr] = React.useState("");
  const [info, setInfo] = React.useState("");

  const handleEmailLogin = async () => {
    if (!email.trim() || !password.trim()) { setErr("Fyll inn epost og passord"); return; }
    setLoading(true); setErr("");
    const { error } = await window.db.auth.signInWithPassword({ email: email.trim(), password });
    setLoading(false);
    if (error) setErr(error.message === "Invalid login credentials" ? "Feil epost eller passord" : error.message);
  };

  const handleEmailRegister = async () => {
    if (!email.trim() || !password.trim()) { setErr("Fyll inn epost og passord"); return; }
    if (password.length < 6) { setErr("Passord må være minst 6 tegn"); return; }
    setLoading(true); setErr("");
    const { error } = await window.db.auth.signUp({
      email: email.trim(), password,
      options: { data: { full_name: displayName.trim() || email.split("@")[0] } },
    });
    setLoading(false);
    if (error) setErr(error.message);
    else setInfo("Sjekk eposten din og klikk bekreftelseslenken for å aktivere kontoen.");
  };

  const inputStyle = {
    background: "var(--bg-0)", border: "1px solid var(--line)", color: "var(--text)",
    fontFamily: "var(--font-body)", fontSize: 15, padding: "10px 14px",
    width: "100%", boxSizing: "border-box", outline: "none",
  };

  return (
    <>
      <PageHeader eyebrow="MIN SIDE / 10" title={<>MIN <span style={{ color: accent }}>SIDE</span>.</>}
        sub="Logg inn for å se dine påmeldinger, laget ditt, og administrere score-rapportering." accent={accent} />
      <section style={{ padding: "64px 48px", display: "flex", justifyContent: "center" }}>
        <div style={{ maxWidth: 480, width: "100%", background: "var(--bg-1)", border: "1px solid var(--line)", padding: 36, 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", marginBottom: 14 }}>AUTENTISERING / WZN LIGA</div>

          {mode === "main" && <>
            <h2 style={{ fontFamily: "var(--font-stencil)", fontSize: 42, letterSpacing: "0.02em", margin: "0 0 20px", lineHeight: 1 }}>
              LOGG INN / <span style={{ color: accent }}>REGISTRER</span>.
            </h2>
            <button onClick={onLoginDiscord} className="cta" style={{ background: "#5865F2", borderColor: "#5865F2", color: "#fff", fontWeight: 700, padding: "14px 18px", justifyContent: "space-between", width: "100%", cursor: "pointer" }}>
              <span>FORTSETT MED DISCORD</span><span>↗</span>
            </button>
            <div style={{ display: "flex", alignItems: "center", gap: 12, margin: "18px 0", fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.15em" }}>
              <div style={{ flex: 1, height: 1, background: "var(--line)" }} />ELLER BRUK EPOST<div style={{ flex: 1, height: 1, background: "var(--line)" }} />
            </div>
            <div style={{ display: "flex", gap: 8 }}>
              <button onClick={() => setMode("login")} className="cta cta-ghost" style={{ flex: 1, padding: "12px 14px", cursor: "pointer", justifyContent: "center" }}><span>LOGG INN</span></button>
              <button onClick={() => setMode("register")} className="cta" style={{ flex: 1, padding: "12px 14px", cursor: "pointer", justifyContent: "center", background: accent, borderColor: accent, color: "var(--bg-0)", fontWeight: 700 }}><span>OPPRETT KONTO</span></button>
            </div>
          </>}

          {mode === "login" && <>
            <button onClick={() => { setMode("main"); setErr(""); }} style={{ background: "transparent", border: "none", cursor: "pointer", fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-dim)", letterSpacing: "0.18em", padding: 0, marginBottom: 16 }}>← TILBAKE</button>
            <h2 style={{ fontFamily: "var(--font-stencil)", fontSize: 36, letterSpacing: "0.02em", margin: "0 0 22px", lineHeight: 1 }}>LOGG INN MED <span style={{ color: accent }}>EPOST</span>.</h2>
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              <div><div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-dim)", letterSpacing: "0.18em", marginBottom: 6 }}>EPOST</div>
                <input type="email" value={email} onChange={e => setEmail(e.target.value)} style={inputStyle} onFocus={e => e.target.style.borderColor = accent} onBlur={e => e.target.style.borderColor = "var(--line)"} /></div>
              <div><div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-dim)", letterSpacing: "0.18em", marginBottom: 6 }}>PASSORD</div>
                <input type="password" value={password} onChange={e => setPassword(e.target.value)} style={inputStyle} onFocus={e => e.target.style.borderColor = accent} onBlur={e => e.target.style.borderColor = "var(--line)"} onKeyDown={e => e.key === "Enter" && handleEmailLogin()} /></div>
              {err && <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "#e63946" }}>{err}</div>}
              <button onClick={handleEmailLogin} disabled={loading} className="cta" style={{ background: accent, borderColor: accent, color: "var(--bg-0)", fontWeight: 700, padding: "14px 18px", justifyContent: "center", width: "100%", cursor: loading ? "default" : "pointer", opacity: loading ? 0.6 : 1, marginTop: 4 }}>
                <span>{loading ? "LOGGER INN…" : "LOGG INN"}</span>
              </button>
              <div style={{ textAlign: "center", fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.12em" }}>
                Ingen konto? <button onClick={() => { setMode("register"); setErr(""); }} style={{ background: "transparent", border: "none", cursor: "pointer", fontFamily: "inherit", fontSize: "inherit", letterSpacing: "inherit", color: accent, textDecoration: "underline" }}>REGISTRER HER</button>
              </div>
            </div>
          </>}

          {mode === "register" && <>
            <button onClick={() => { setMode("main"); setErr(""); setInfo(""); }} style={{ background: "transparent", border: "none", cursor: "pointer", fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-dim)", letterSpacing: "0.18em", padding: 0, marginBottom: 16 }}>← TILBAKE</button>
            <h2 style={{ fontFamily: "var(--font-stencil)", fontSize: 36, letterSpacing: "0.02em", margin: "0 0 22px", lineHeight: 1 }}>OPPRETT <span style={{ color: accent }}>KONTO</span>.</h2>
            {info ? (
              <div style={{ textAlign: "center", padding: "24px 0" }}>
                <div style={{ fontFamily: "var(--font-stencil)", fontSize: 28, color: accent, marginBottom: 12 }}>SJEKK EPOSTEN!</div>
                <div style={{ fontFamily: "var(--font-body)", fontSize: 15, color: "var(--text-dim)", lineHeight: 1.6 }}>{info}</div>
              </div>
            ) : (
              <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                <div><div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-dim)", letterSpacing: "0.18em", marginBottom: 6 }}>GAMER-NAVN (VALGFRITT)</div>
                  <input type="text" value={displayName} onChange={e => setDisplayName(e.target.value)} placeholder="f.eks. cryptic" style={inputStyle} onFocus={e => e.target.style.borderColor = accent} onBlur={e => e.target.style.borderColor = "var(--line)"} /></div>
                <div><div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-dim)", letterSpacing: "0.18em", marginBottom: 6 }}>EPOST</div>
                  <input type="email" value={email} onChange={e => setEmail(e.target.value)} style={inputStyle} onFocus={e => e.target.style.borderColor = accent} onBlur={e => e.target.style.borderColor = "var(--line)"} /></div>
                <div><div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-dim)", letterSpacing: "0.18em", marginBottom: 6 }}>PASSORD (MIN. 6 TEGN)</div>
                  <input type="password" value={password} onChange={e => setPassword(e.target.value)} style={inputStyle} onFocus={e => e.target.style.borderColor = accent} onBlur={e => e.target.style.borderColor = "var(--line)"} onKeyDown={e => e.key === "Enter" && handleEmailRegister()} /></div>
                {err && <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "#e63946" }}>{err}</div>}
                <button onClick={handleEmailRegister} disabled={loading} className="cta" style={{ background: accent, borderColor: accent, color: "var(--bg-0)", fontWeight: 700, padding: "14px 18px", justifyContent: "center", width: "100%", cursor: loading ? "default" : "pointer", opacity: loading ? 0.6 : 1, marginTop: 4 }}>
                  <span>{loading ? "OPPRETTER…" : "OPPRETT KONTO"}</span>
                </button>
                <div style={{ textAlign: "center", fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.12em" }}>
                  Har du konto? <button onClick={() => { setMode("login"); setErr(""); }} style={{ background: "transparent", border: "none", cursor: "pointer", fontFamily: "inherit", fontSize: "inherit", letterSpacing: "inherit", color: accent, textDecoration: "underline" }}>LOGG INN HER</button>
                </div>
              </div>
            )}
          </>}
        </div>
      </section>
    </>
  );
};

// ───────── Dashboard ─────────
const MinSideDashboard = ({ accent, discordUser, onNav, onLogout }) => {
  const [tab, setTab] = React.useState("oversikt");
  const [userRole, setUserRole] = React.useState(null);
  const [myTeam, setMyTeam] = React.useState(null);
  const [myTournaments, setMyTournaments] = React.useState([]);
  const [stats, setStats] = React.useState(null);
  const [loading, setLoading] = React.useState(true);

  const meta = discordUser?.user_metadata || {};
  const discordIdentity = (discordUser?.identities || []).find(i => i.provider === "discord");
  const displayName = meta.full_name || meta.name || meta.global_name || discordUser?.email?.split("@")[0] || "SPILLER";
  const avatarUrl = meta.avatar_url || null;
  const initials = displayName.slice(0, 2).toUpperCase();

  React.useEffect(() => {
    if (!window.db || !discordUser) return;
    let cancelled = false;

    const load = async () => {
      setLoading(true);

      // Hent bruker-rolle og profil fra user_roles
      const roles = await WZN_Store.getUserRoles();
      const myRole = roles.find(r => r.user_id === discordUser.id);
      if (!cancelled) setUserRole(myRole || null);

      // Hent laget mitt (kapteins registreringer)
      const discordId = discordIdentity?.id || null;
      if (discordId) {
        const { data } = await window.db
          .from("team_registrations")
          .select("*")
          .or(`captain_discord_id.eq.${discordId},captain.ilike.%${meta.full_name || meta.name || ""}%`)
          .order("registered_at", { ascending: false })
          .limit(1);
        if (!cancelled && data?.length) setMyTeam(data[0]);
      }

      // Hent turneringer
      const allT = await WZN_Store.getTournaments();
      if (!cancelled) setMyTournaments(allT.filter(t => ["live","open","locked"].includes(t.status)));

      // Hent stats
      if (discordId) {
        const { data: subs } = await window.db
          .from("submissions")
          .select("kills, placement, points")
          .eq("submitted_by", discordId)
          .eq("status", "verified");
        if (!cancelled && subs?.length) {
          const kills = subs.reduce((s, r) => s + (r.kills || 0), 0);
          const wins = subs.filter(r => r.placement === 1).length;
          const pts = subs.reduce((s, r) => s + (r.points || 0), 0);
          setStats({ kills, wins, games: subs.length, pts, kpg: subs.length ? (kills / subs.length).toFixed(1) : "—" });
        }
      }

      if (!cancelled) setLoading(false);
    };

    load();
    return () => { cancelled = true; };
  }, [discordUser?.id]);

  const tabs = [
    { id: "oversikt",      label: "OVERSIKT" },
    { id: "lag",           label: "MITT LAG" },
    { id: "turneringer",   label: "TURNERINGER" },
    { id: "innstillinger", label: "INNSTILLINGER" },
  ];

  const roleColor = { superadmin: accent, admin: accent, mod: "#ffb700", captain: "var(--text)", player: "var(--text-dim)" };
  const roleName = userRole?.role ? (window.ROLE_LABELS?.[userRole.role] || userRole.role.toUpperCase()) : "SPILLER";

  return (
    <>
      {/* ── Profile header ── */}
      <section style={{ padding: "40px 48px 0", background: "var(--bg-0)", borderBottom: "1px solid var(--line)", position: "relative", overflow: "hidden" }}>
        <div style={{ position: "absolute", right: -10, top: -50, fontFamily: "var(--font-stencil)", fontSize: 240, lineHeight: 0.9, color: "rgba(255,255,255,0.02)", pointerEvents: "none", userSelect: "none" }}>
          {initials}
        </div>
        <div style={{ position: "relative", zIndex: 1, display: "flex", alignItems: "flex-end", justifyContent: "space-between", paddingBottom: 28, gap: 24 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 24 }}>
            {/* Avatar */}
            <div style={{ position: "relative", flexShrink: 0 }}>
              {avatarUrl ? (
                <img src={avatarUrl} alt={displayName} style={{ width: 88, height: 88, border: `3px solid ${accent}`, display: "block", objectFit: "cover" }} />
              ) : (
                <div style={{ width: 88, height: 88, border: `3px solid ${accent}`, display: "flex", alignItems: "center", justifyContent: "center", background: "var(--bg-2)", fontFamily: "var(--font-stencil)", fontSize: 32, color: accent }}>
                  {initials}
                </div>
              )}
              <div style={{ position: "absolute", bottom: -6, right: -6, width: 14, height: 14, background: accent, border: "2px solid var(--bg-0)" }} />
            </div>

            {/* Name + role */}
            <div>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.2em" }}>INNLOGGET</span>
                <span style={{ fontFamily: "var(--font-stencil)", fontSize: 11, padding: "2px 8px", border: `1px solid ${roleColor[userRole?.role] || "var(--line)"}`, color: roleColor[userRole?.role] || "var(--text-dim)", letterSpacing: "0.06em" }}>
                  {roleName}
                </span>
                {discordIdentity && (
                  <span style={{ fontFamily: "var(--font-stencil)", fontSize: 11, padding: "2px 8px", border: "1px solid #5865F2", color: "#5865F2", letterSpacing: "0.06em" }}>DISCORD</span>
                )}
              </div>
              <h1 style={{ fontFamily: "var(--font-stencil)", fontSize: 56, lineHeight: 0.92, margin: 0, letterSpacing: "0.01em" }}>
                {displayName.toUpperCase()}
              </h1>
              <div style={{ display: "flex", gap: 16, marginTop: 10, flexWrap: "wrap" }}>
                {userRole?.activision_id && (
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: accent, letterSpacing: "0.1em" }}>
                    🎮 {userRole.activision_id}
                  </span>
                )}
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-dim)", letterSpacing: "0.08em" }}>
                  {discordUser?.email || "—"}
                </span>
              </div>
            </div>
          </div>

          {/* Stats strip */}
          <div style={{ display: "flex", gap: 0, border: "1px solid var(--line)", flexShrink: 0 }}>
            {[
              { k: "KILLS", v: stats?.kills ?? "—" },
              { k: "WINS",  v: stats?.wins  ?? "—" },
              { k: "GAMES", v: stats?.games ?? "—" },
              { k: "LP",    v: stats?.pts   ?? "—" },
            ].map((s, i) => (
              <div key={s.k} style={{ padding: "14px 20px", borderRight: i < 3 ? "1px solid var(--line)" : "none", textAlign: "center" }}>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, color: "var(--text-faint)", letterSpacing: "0.2em", marginBottom: 4 }}>{s.k}</div>
                <div style={{ fontFamily: "var(--font-stencil)", fontSize: 28, color: i === 3 ? accent : "var(--text)", lineHeight: 1 }}>{s.v}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Tabs */}
        <div style={{ display: "flex" }}>
          {tabs.map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              padding: "14px 22px",
              background: tab === t.id ? "var(--bg-1)" : "transparent",
              border: "1px solid var(--line)",
              borderBottom: tab === t.id ? "1px solid var(--bg-1)" : "1px solid var(--line)",
              fontFamily: "var(--font-stencil)", fontSize: 13, letterSpacing: "0.06em",
              color: tab === t.id ? accent : "var(--text-dim)", cursor: "pointer",
              marginRight: -1, marginBottom: -1,
            }}>{t.label}</button>
          ))}
          <div style={{ flex: 1, borderBottom: "1px solid var(--line)" }} />
          <button onClick={onLogout} style={{ padding: "14px 18px", border: "1px solid var(--line)", borderLeft: "1px solid var(--line)", marginBottom: -1, background: "transparent", fontFamily: "var(--font-stencil)", fontSize: 12, letterSpacing: "0.06em", color: "var(--text-faint)", cursor: "pointer" }}>
            LOGG UT ↩
          </button>
        </div>
      </section>

      {/* ── Tab content ── */}
      <section style={{ padding: "40px 48px 80px", background: "var(--bg-1)", minHeight: 400 }}>

        {/* ── OVERSIKT ── */}
        {tab === "oversikt" && (
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 32 }}>
            {/* Profil-kort */}
            <div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: accent, letterSpacing: "0.25em", marginBottom: 18 }}>PROFIL</div>
              <div style={{ background: "var(--bg-2)", border: "1px solid var(--line)", padding: 24, display: "flex", flexDirection: "column", gap: 16 }}>
                {[
                  { k: "GAMER-NAVN", v: displayName },
                  { k: "ACTIVISION ID", v: userRole?.activision_id || "Ikke satt — legg til under Innstillinger" },
                  { k: "DISCORD", v: meta.full_name || meta.name || "—" },
                  { k: "EPOST", v: discordUser?.email || "—" },
                  { k: "ROLLE", v: roleName },
                ].map(row => (
                  <div key={row.k} style={{ display: "grid", gridTemplateColumns: "140px 1fr", gap: 12, alignItems: "baseline" }}>
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.18em" }}>{row.k}</span>
                    <span style={{ fontFamily: "var(--font-body)", fontSize: 15, color: "var(--text)" }}>{row.v}</span>
                  </div>
                ))}
              </div>
            </div>

            {/* Hurtigvalg */}
            <div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: accent, letterSpacing: "0.25em", marginBottom: 18 }}>HURTIGVALG</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                {[
                  { label: "MELD PÅ TURNERING", sub: `${myTournaments.filter(t => t.status === "open").length} åpne`, action: () => onNav("turneringer") },
                  { label: "MITT LAG", sub: myTeam ? myTeam.name : "Ikke på lag ennå", action: () => setTab("lag") },
                  { label: "LIGA — MELD INTERESSE", sub: "Sesong 01 kommer", action: () => onNav("liga", { anchor: "interesse" }) },
                  { label: "HALL OF FAME", sub: "Toppspillere og rekorder", action: () => onNav("hof") },
                ].map((a, i) => (
                  <button key={i} onClick={a.action} style={{
                    padding: "14px 18px", background: "var(--bg-2)", border: "1px solid var(--line)", cursor: "pointer",
                    display: "flex", justifyContent: "space-between", alignItems: "center",
                    fontFamily: "var(--font-stencil)", letterSpacing: "0.04em",
                    transition: "border-color 0.12s",
                  }}
                    onMouseEnter={e => e.currentTarget.style.borderColor = accent}
                    onMouseLeave={e => e.currentTarget.style.borderColor = "var(--line)"}
                  >
                    <div style={{ textAlign: "left" }}>
                      <div style={{ fontSize: 14, color: "var(--text)" }}>{a.label}</div>
                      <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.15em", marginTop: 3 }}>{a.sub}</div>
                    </div>
                    <span style={{ color: accent, fontSize: 16 }}>→</span>
                  </button>
                ))}
              </div>
            </div>
          </div>
        )}

        {/* ── MITT LAG ── */}
        {tab === "lag" && (
          <MittLagTab accent={accent} myTeam={myTeam} setMyTeam={setMyTeam} discordUser={discordUser} discordIdentity={discordIdentity} displayName={displayName} onNav={onNav} />
        )}

        {/* ── TURNERINGER ── */}
        {tab === "turneringer" && (
          <div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: accent, letterSpacing: "0.25em", marginBottom: 20 }}>TURNERINGER</div>
            {myTournaments.length === 0 ? (
              <EmptyState accent={accent} msg="Ingen åpne turneringer nå" cta="SE ALLE TURNERINGER" onCta={() => onNav("turneringer")} />
            ) : (
              <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                {myTournaments.map(t => {
                  const d = t.start_date ? new Date(t.start_date) : null;
                  const dateStr = d ? d.toLocaleDateString("nb-NO", { day: "numeric", month: "short", year: "numeric" }) : "—";
                  const timeStr = d ? d.toLocaleTimeString("nb-NO", { hour: "2-digit", minute: "2-digit" }) : "";
                  return (
                    <div key={t.id} style={{
                      background: "var(--bg-2)", border: `1px solid ${t.status === "live" ? accent : "var(--line)"}`,
                      padding: "20px 24px", display: "grid", gridTemplateColumns: "1fr auto auto", gap: 24, alignItems: "center",
                    }}>
                      <div>
                        <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: t.status === "live" ? accent : "var(--text-faint)", letterSpacing: "0.18em", marginBottom: 4 }}>
                          {t.status === "live" ? "● LIVE NÅ" : t.status === "open" ? "ÅPEN FOR PÅMELDING" : "LÅST"}
                        </div>
                        <div style={{ fontFamily: "var(--font-stencil)", fontSize: 24, letterSpacing: "0.02em" }}>{t.name}</div>
                        <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-dim)", marginTop: 6, letterSpacing: "0.1em" }}>
                          {dateStr}{timeStr ? ` · ${timeStr}` : ""} · {(t.team_size || "trios").toUpperCase()}
                          {t.prize_pool ? ` · ${t.prize_pool.toLocaleString()} KR` : ""}
                        </div>
                      </div>
                      <div style={{ textAlign: "center" }}>
                        <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, color: "var(--text-faint)", letterSpacing: "0.15em" }}>PLASSER</div>
                        <div style={{ fontFamily: "var(--font-stencil)", fontSize: 22, marginTop: 4 }}>
                          {t.max_teams ? `${t.max_teams - (t.registered || 0)}/${t.max_teams}` : "—"}
                        </div>
                      </div>
                      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                        <button onClick={() => onNav("turnering", { tournamentId: t.id })} style={{ padding: "9px 16px", border: `1px solid ${accent}`, color: accent, background: "transparent", fontFamily: "var(--font-stencil)", fontSize: 12, letterSpacing: "0.06em", cursor: "pointer" }}>
                          SE DETALJER →
                        </button>
                        {t.status === "open" && (
                          <button onClick={() => onNav("pamelding", { tournamentId: t.id })} style={{ padding: "9px 16px", background: accent, border: `1px solid ${accent}`, color: "var(--bg-0)", fontFamily: "var(--font-stencil)", fontSize: 12, letterSpacing: "0.06em", cursor: "pointer", fontWeight: 700 }}>
                            MELD PÅ ▶
                          </button>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        )}

        {/* ── INNSTILLINGER ── */}
        {tab === "innstillinger" && (
          <InnstillingerTab accent={accent} discordUser={discordUser} userRole={userRole} setUserRole={setUserRole} displayName={displayName} />
        )}
      </section>
    </>
  );
};

// ───────── Mitt Lag-tab ─────────
const MittLagTab = ({ accent, myTeam, setMyTeam, discordUser, discordIdentity, displayName, onNav }) => {
  const [showCreate, setShowCreate] = React.useState(false);
  const [teamName, setTeamName] = React.useState("");
  const [teamTag, setTeamTag] = React.useState("");
  const [activisionId, setActivisionId] = React.useState("");
  const [p2Discord, setP2Discord] = React.useState("");
  const [p2Activision, setP2Activision] = React.useState("");
  const [p3Discord, setP3Discord] = React.useState("");
  const [p3Activision, setP3Activision] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [err, setErr] = React.useState("");

  const inputStyle = {
    width: "100%", boxSizing: "border-box",
    background: "var(--bg-0)", border: "1px solid var(--line-2)", padding: "11px 14px",
    fontFamily: "var(--font-body)", fontSize: 15, color: "var(--text)", outline: "none",
  };
  const labelStyle = { fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.2em", display: "block", marginBottom: 6 };

  const handleCreate = async () => {
    if (!teamName.trim()) { setErr("Lagnavn er påkrevd"); return; }
    if (!teamTag.trim()) { setErr("Lagtag er påkrevd"); return; }
    setLoading(true); setErr("");

    const roster = [
      { discord: displayName, activision: activisionId.trim(), role: "kaptein" },
      ...(p2Discord.trim() ? [{ discord: p2Discord.trim(), activision: p2Activision.trim(), role: "spiller" }] : []),
      ...(p3Discord.trim() ? [{ discord: p3Discord.trim(), activision: p3Activision.trim(), role: "spiller" }] : []),
    ];

    const { error } = await WZN_Store.addTeamRegistration({
      id: crypto.randomUUID ? crypto.randomUUID() : Date.now().toString(),
      registeredAt: new Date().toISOString(),
      name: teamName.trim(),
      tag: teamTag.trim().toUpperCase().slice(0, 4),
      captain: displayName,
      captain_discord_id: discordIdentity?.id || null,
      roster,
      tournament_id: null,
    });

    setLoading(false);
    if (error) { setErr("Feil: " + error.message); return; }
    setMyTeam({ name: teamName.trim(), tag: teamTag.trim().toUpperCase(), captain: displayName, roster, status: "pending" });
    setShowCreate(false);
  };

  if (myTeam) {
    const roster = myTeam.roster || [];
    return (
      <div>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: accent, letterSpacing: "0.25em", marginBottom: 20 }}>MITT LAG</div>
        <div style={{ maxWidth: 640 }}>
          {/* Team card */}
          <div style={{ background: "var(--bg-2)", border: `1px solid ${accent}`, padding: 28, marginBottom: 16 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 20 }}>
              <span style={{ fontFamily: "var(--font-stencil)", fontSize: 16, padding: "6px 14px", border: `2px solid ${accent}`, color: accent }}>
                {myTeam.tag || "TAG"}
              </span>
              <h3 style={{ fontFamily: "var(--font-stencil)", fontSize: 36, margin: 0, letterSpacing: "0.02em" }}>
                {myTeam.name || "LAGET MITT"}
              </h3>
              <div style={{ marginLeft: "auto", display: "flex", gap: 8, alignItems: "center" }}>
                <span style={{ fontFamily: "var(--font-stencil)", fontSize: 11, padding: "3px 10px", border: `1px solid ${myTeam.status === "approved" ? "#44d62c" : myTeam.status === "rejected" ? "#e63946" : "var(--line)"}`, color: myTeam.status === "approved" ? "#44d62c" : myTeam.status === "rejected" ? "#e63946" : "var(--text-dim)" }}>
                  {myTeam.status === "approved" ? "✓ GODKJENT" : myTeam.status === "rejected" ? "✗ AVVIST" : "⏳ VENTER"}
                </span>
                {myTeam.roster_locked_at && (
                  <span style={{
                    fontFamily: "var(--font-stencil)", fontSize: 11, padding: "3px 10px",
                    border: "1px solid #f59e0b", color: "#f59e0b",
                    title: `Roster låst ${new Date(myTeam.roster_locked_at).toLocaleString("no-NO")}`,
                  }}>🔒 ROSTER LÅST</span>
                )}
              </div>
            </div>

            {/* Roster */}
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.2em", marginBottom: 12 }}>ROSTER</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {roster.map((p, i) => (
                <div key={i} style={{ display: "grid", gridTemplateColumns: "auto 1fr 1fr", gap: 16, alignItems: "center", padding: "10px 14px", background: "var(--bg-3)", border: "1px solid var(--line)" }}>
                  <span style={{ fontFamily: "var(--font-stencil)", fontSize: 11, padding: "2px 8px", border: `1px solid ${p.role === "kaptein" ? accent : "var(--line-2)"}`, color: p.role === "kaptein" ? accent : "var(--text-dim)" }}>
                    {p.role === "kaptein" ? "KAPTEIN" : `SPILLER ${i}`}
                  </span>
                  <span style={{ fontFamily: "var(--font-body)", fontSize: 14, color: "var(--text)" }}>{p.discord || "—"}</span>
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-dim)" }}>{p.activision || "—"}</span>
                </div>
              ))}
            </div>
          </div>

          {myTeam.status === "pending" && (
            <div style={{ padding: "14px 18px", background: "var(--bg-0)", border: "1px solid var(--line)", fontFamily: "var(--font-body)", fontSize: 14, color: "var(--text-dim)", lineHeight: 1.6 }}>
              <span style={{ color: accent }}>▸</span> Søknaden er sendt. Admin verifiserer og sender bekreftelse på Discord innen 24t.
            </div>
          )}
        </div>
      </div>
    );
  }

  return (
    <div>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: accent, letterSpacing: "0.25em", marginBottom: 20 }}>MITT LAG</div>
      {!showCreate ? (
        <div style={{ maxWidth: 560 }}>
          <EmptyState accent={accent} msg="Du er ikke registrert på et lag ennå" cta={null} />
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginTop: 20 }}>
            <button onClick={() => setShowCreate(true)} className="cta" style={{ background: accent, color: "var(--bg-0)", borderColor: accent, fontWeight: 700, padding: "16px 20px", justifyContent: "space-between", cursor: "pointer" }}>
              <span>OPPRETT LAG</span><span>+</span>
            </button>
            <button onClick={() => onNav("turneringer")} className="cta cta-ghost" style={{ padding: "16px 20px", justifyContent: "space-between", cursor: "pointer" }}>
              <span>MELD PÅ TURNERING</span><span>→</span>
            </button>
          </div>
        </div>
      ) : (
        <div style={{ maxWidth: 680 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 16, marginBottom: 24 }}>
            <button onClick={() => setShowCreate(false)} style={{ background: "transparent", border: "none", cursor: "pointer", fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-dim)", letterSpacing: "0.18em", padding: 0 }}>← TILBAKE</button>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: accent, letterSpacing: "0.25em" }}>OPPRETT LAG</div>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
              <div><label style={labelStyle}>LAGNAVN</label><input value={teamName} onChange={e => setTeamName(e.target.value)} placeholder="f.eks. Arctic Storm" style={inputStyle} /></div>
              <div><label style={labelStyle}>LAGTAG (3-4 BOKSTAVER)</label><input value={teamTag} onChange={e => setTeamTag(e.target.value.toUpperCase().slice(0,4))} placeholder="ARS" style={inputStyle} /></div>
            </div>
            <div><label style={labelStyle}>DIN ACTIVISION-ID</label><input value={activisionId} onChange={e => setActivisionId(e.target.value)} placeholder="bruker#5678" style={inputStyle} /></div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.2em" }}>SPILLERE (VALGFRITT)</div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
              <div><label style={labelStyle}>SPILLER 2 — DISCORD</label><input value={p2Discord} onChange={e => setP2Discord(e.target.value)} placeholder="bruker#1234" style={inputStyle} /></div>
              <div><label style={labelStyle}>SPILLER 2 — ACTIVISION</label><input value={p2Activision} onChange={e => setP2Activision(e.target.value)} placeholder="bruker#5678" style={inputStyle} /></div>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
              <div><label style={labelStyle}>SPILLER 3 — DISCORD</label><input value={p3Discord} onChange={e => setP3Discord(e.target.value)} placeholder="bruker#1234" style={inputStyle} /></div>
              <div><label style={labelStyle}>SPILLER 3 — ACTIVISION</label><input value={p3Activision} onChange={e => setP3Activision(e.target.value)} placeholder="bruker#5678" style={inputStyle} /></div>
            </div>
            {err && <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "#e63946" }}>{err}</div>}
            <button onClick={handleCreate} disabled={loading} className="cta" style={{ background: accent, color: "var(--bg-0)", borderColor: accent, fontWeight: 700, padding: "16px 22px", justifyContent: "space-between", width: "100%", cursor: loading ? "default" : "pointer", opacity: loading ? 0.6 : 1 }}>
              <span>{loading ? "SENDER…" : "SEND LAG-SØKNAD"}</span><span>▶</span>
            </button>
            <div style={{ padding: "12px 16px", background: "var(--bg-0)", border: "1px solid var(--line)", fontFamily: "var(--font-body)", fontSize: 13, color: "var(--text-dim)", lineHeight: 1.6 }}>
              <span style={{ color: accent }}>▸</span> Admin verifiserer innen 24t. Du mottar Discord DM ved godkjenning og får KAPTEIN-rollen.
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// ───────── Innstillinger-tab ─────────
const InnstillingerTab = ({ accent, discordUser, userRole, setUserRole, displayName }) => {
  const [activisionId, setActivisionId] = React.useState(userRole?.activision_id || "");
  const [region, setRegion] = React.useState(userRole?.region || "");
  const [loading, setLoading] = React.useState(false);
  const [saved, setSaved] = React.useState(false);
  const [err, setErr] = React.useState("");

  React.useEffect(() => {
    setActivisionId(userRole?.activision_id || "");
    setRegion(userRole?.region || "");
  }, [userRole?.activision_id, userRole?.region]);

  const handleSave = async () => {
    if (!window.db || !discordUser) return;
    setLoading(true); setErr(""); setSaved(false);
    const { error } = await window.db
      .from("user_roles")
      .update({ activision_id: activisionId.trim() || null, updated_at: new Date().toISOString() })
      .eq("user_id", discordUser.id);
    setLoading(false);
    if (error) setErr("Feil ved lagring: " + error.message);
    else {
      setSaved(true);
      setUserRole(prev => prev ? { ...prev, activision_id: activisionId.trim() || null } : prev);
      setTimeout(() => setSaved(false), 3000);
    }
  };

  const inputStyle = {
    width: "100%", boxSizing: "border-box",
    background: "var(--bg-0)", border: "1px solid var(--line-2)", padding: "12px 14px",
    fontFamily: "var(--font-body)", fontSize: 15, color: "var(--text)", outline: "none",
  };
  const labelStyle = { fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.2em", display: "block", marginBottom: 6 };

  return (
    <div style={{ maxWidth: 520 }}>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: accent, letterSpacing: "0.25em", marginBottom: 24 }}>INNSTILLINGER</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
        <div>
          <label style={labelStyle}>GAMER-NAVN</label>
          <input value={displayName} disabled style={{ ...inputStyle, background: "var(--bg-2)", color: "var(--text-faint)", cursor: "not-allowed" }} />
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.12em", marginTop: 4 }}>Hentes fra Discord — endres i Discord-appen</div>
        </div>
        <div>
          <label style={labelStyle}>ACTIVISION-ID</label>
          <input value={activisionId} onChange={e => setActivisionId(e.target.value)} placeholder="bruker#5678" style={inputStyle}
            onFocus={e => e.target.style.borderColor = accent} onBlur={e => e.target.style.borderColor = "var(--line-2)"} />
        </div>
        <div>
          <label style={labelStyle}>EPOST</label>
          <input value={discordUser?.email || "—"} disabled style={{ ...inputStyle, background: "var(--bg-2)", color: "var(--text-faint)", cursor: "not-allowed" }} />
        </div>

        <div style={{ borderTop: "1px solid var(--line)", paddingTop: 20 }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.2em", marginBottom: 12 }}>KONTO-INFO</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {[
              { k: "BRUKER-ID", v: discordUser?.id?.slice(0, 16) + "…" },
              { k: "PÅLOGGINGS-METODE", v: discordUser?.app_metadata?.provider?.toUpperCase() || "—" },
              { k: "ROLLE", v: userRole?.role ? (window.ROLE_LABELS?.[userRole.role] || userRole.role.toUpperCase()) : "SPILLER" },
            ].map(row => (
              <div key={row.k} style={{ display: "grid", gridTemplateColumns: "160px 1fr", padding: "8px 14px", background: "var(--bg-2)", border: "1px solid var(--line)" }}>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.15em" }}>{row.k}</span>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text)" }}>{row.v}</span>
              </div>
            ))}
          </div>
        </div>

        {err && <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "#e63946" }}>{err}</div>}
        {saved && <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "#44d62c", letterSpacing: "0.12em" }}>✓ LAGRET</div>}

        <button onClick={handleSave} disabled={loading} className="cta" style={{ background: accent, color: "var(--bg-0)", borderColor: accent, fontWeight: 700, padding: "14px 20px", justifyContent: "space-between", width: "100%", cursor: loading ? "default" : "pointer", opacity: loading ? 0.6 : 1 }}>
          <span>{loading ? "LAGRER…" : "LAGRE ENDRINGER"}</span><span>▶</span>
        </button>
      </div>
    </div>
  );
};

// ───────── Hjelpkomponent ─────────
const EmptyState = ({ accent, msg, cta, onCta }) => (
  <div style={{ border: "1px dashed var(--line-2)", padding: "40px 32px", textAlign: "center" }}>
    <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-faint)", letterSpacing: "0.18em", marginBottom: cta ? 16 : 0 }}>{msg}</div>
    {cta && <button onClick={onCta} className="cta cta-ghost" style={{ padding: "10px 18px", cursor: "pointer", margin: "0 auto" }}><span>{cta}</span><span>→</span></button>}
  </div>
);

Object.assign(window, { MinSidePage });
