// Spillere — liste over alle spillere + profil-visning for én spiller.

const SpillerePage = ({ accent, onNav }) => {
  const [selected, setSelected] = React.useState(null);
  const [sortBy, setSortBy] = React.useState("kd");
  const [players, setPlayers] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  React.useEffect(() => {
    WZN_Store.getTopPlayers(50).then(data => { setPlayers(data); setLoading(false); });
  }, []);
  const all = React.useMemo(() => {
    return [...players].sort((a, b) => {
      if (sortBy === "kd") return (b.kd || 0) - (a.kd || 0);
      if (sortBy === "kills_md") return (b.kills || 0) - (a.kills || 0);
      if (sortBy === "wins") return (b.wins || 0) - (a.wins || 0);
      return 0;
    });
  }, [players, sortBy]);
  if (selected) return <SpiIlerProfil p={selected} accent={accent} onBack={() => setSelected(null)} onNav={onNav} />;
  return (
    <>
      <PageHeader
        eyebrow="SPILLERE / 07"
        title={<>SPILLER<span style={{ color: accent }}>PROFILER</span>.</>}
        sub="Alle registrerte spillere sortert etter stats fra siste warm-up turneringer. Klikk en spiller for full profil."
        accent={accent}
      />
      <section style={{ padding: "32px 48px 64px" }}>
        {/* Sort strip */}
        <div style={{
          display: "flex", gap: 6, marginBottom: 24, alignItems: "center",
          fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-faint)", letterSpacing: "0.18em",
        }}>
          <span>SORTER ETTER:</span>
          {[
            { id: "kd", label: "K/D" },
            { id: "kills_md", label: "KILLS/MD" },
            { id: "wins", label: "WINS" },
            { id: "gulag", label: "GULAG%" },
          ].map(s => (
            <button key={s.id} onClick={() => setSortBy(s.id)} style={{
              padding: "6px 14px",
              background: sortBy === s.id ? "var(--bg-3)" : "transparent",
              border: `1px solid ${sortBy === s.id ? accent : "var(--line-2)"}`,
              fontFamily: "var(--font-stencil)", fontSize: 12, letterSpacing: "0.06em",
              color: sortBy === s.id ? accent : "var(--text-dim)", cursor: "pointer",
            }}>{s.label}</button>
          ))}
        </div>

        {/* Player table */}
        {loading ? (
          <div style={{ padding: 32, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-faint)", letterSpacing: "0.18em" }}>LASTER...</div>
        ) : all.length === 0 ? (
          <div style={{ padding: "48px 0", fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-faint)", letterSpacing: "0.15em" }}>
            INGEN SPILLERE REGISTRERT ENNÅ — STATISTIKK BYGGES OPP ETTER FØRSTE TURNERING.
          </div>
        ) : (
          <div style={{ background: "var(--bg-1)", border: "1px solid var(--line)", overflow: "hidden" }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontFamily: "var(--font-body)" }}>
              <thead>
                <tr>
                  {["#", "SPILLER/LAG", "KILLS", "SPILL", "WINS", "K/D"].map(h => (
                    <th key={h} style={{
                      textAlign: "left", padding: "12px 14px", borderBottom: "1px solid var(--line)",
                      fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.18em",
                    }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {all.map((p, i) => (
                  <tr key={p.team_name} onClick={() => setSelected(p)} style={{
                    borderBottom: "1px solid var(--line)", cursor: "pointer", transition: "background 0.1s",
                  }}
                    onMouseEnter={e => e.currentTarget.style.background = "var(--bg-2)"}
                    onMouseLeave={e => e.currentTarget.style.background = "transparent"}
                  >
                    <td style={{ padding: "14px" }}>
                      <span style={{ fontFamily: "var(--font-stencil)", fontSize: 20, color: i < 3 ? accent : "var(--text-dim)" }}>
                        {String(i+1).padStart(2,"0")}
                      </span>
                    </td>
                    <td style={{ padding: "14px" }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                        <div style={{
                          width: 36, height: 36, border: `1px solid ${i < 3 ? accent : "var(--line-2)"}`,
                          display: "flex", alignItems: "center", justifyContent: "center",
                          fontFamily: "var(--font-stencil)", fontSize: 12, color: i < 3 ? accent : "var(--text-dim)",
                          background: "var(--bg-3)",
                        }}>{(p.team_name || "?").slice(0,2).toUpperCase()}</div>
                        <span style={{ fontFamily: "var(--font-stencil)", fontSize: 16, letterSpacing: "0.02em" }}>{p.team_name}</span>
                      </div>
                    </td>
                    <td style={{ padding: "14px", fontFamily: "var(--font-mono)", fontSize: 13 }}>{p.kills ?? "—"}</td>
                    <td style={{ padding: "14px", fontFamily: "var(--font-mono)", fontSize: 13 }}>{p.games ?? "—"}</td>
                    <td style={{ padding: "14px", fontFamily: "var(--font-mono)", fontSize: 13 }}>{p.wins ?? "—"}</td>
                    <td style={{ padding: "14px", fontFamily: "var(--font-mono)", fontSize: 14, fontWeight: 700, color: i < 3 ? accent : "var(--text)" }}>
                      {p.kd?.toFixed ? p.kd.toFixed(2) : "—"}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>
    </>
  );
};

// ───────── Spiller profil ─────────
const SpiIlerProfil = ({ p, accent, onBack }) => {
  const name = p.team_name || p.gamer || "UKJENT";
  return (
    <>
      <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={onBack} style={{
          background: "transparent", border: "none", cursor: "pointer",
          color: "var(--text-dim)", fontFamily: "inherit", fontSize: 11, letterSpacing: "0.18em",
        }}>← SPILLERE</button>
        <span style={{ color: "var(--text-faint)" }}>/</span>
        <span style={{ color: accent }}>{name.toUpperCase()}</span>
      </section>

      <section style={{
        padding: "56px 48px", background: "var(--bg-0)", borderBottom: "1px solid var(--line)",
        position: "relative", overflow: "hidden",
      }}>
        <div style={{
          position: "absolute", right: -40, top: -80,
          fontFamily: "var(--font-stencil)", fontSize: 320, lineHeight: 0.9,
          color: "rgba(255,255,255,0.022)", pointerEvents: "none", letterSpacing: "-0.02em",
        }}>{name.slice(0,3).toUpperCase()}</div>

        <div style={{ position: "relative", zIndex: 1, display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 36, alignItems: "center" }}>
          <div style={{
            width: 96, height: 96, border: `3px solid ${accent}`,
            display: "flex", alignItems: "center", justifyContent: "center",
            fontFamily: "var(--font-stencil)", fontSize: 32, color: accent, background: "var(--bg-2)",
          }}>{name.slice(0,2).toUpperCase()}</div>

          <div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-dim)", letterSpacing: "0.2em", marginBottom: 6 }}>
              SPILLERPROFIL · WZN LIGA
            </div>
            <h1 style={{ fontFamily: "var(--font-stencil)", fontSize: 72, lineHeight: 0.95, margin: 0, letterSpacing: "0.01em" }}>
              {name.toUpperCase()}
            </h1>
          </div>

          <div style={{ textAlign: "right" }}>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.18em" }}>K/D RATIO</div>
            <div style={{ fontFamily: "var(--font-stencil)", fontSize: 80, color: accent, lineHeight: 1, marginTop: 4 }}>
              {p.kd?.toFixed ? p.kd.toFixed(2) : "—"}
            </div>
          </div>
        </div>

        <div style={{
          display: "grid", gridTemplateColumns: "repeat(4, 1fr)",
          border: "1px solid var(--line)", marginTop: 32, background: "var(--bg-1)",
        }}>
          {[
            { k: "TOTAL KILLS", v: p.kills ?? "—" },
            { k: "SPILL TOTALT", v: p.games ?? "—" },
            { k: "WINS", v: p.wins ?? "—" },
            { k: "RANK", v: p.rank ? `#${p.rank}` : "—" },
          ].map((s, i) => (
            <div key={s.k} style={{ padding: "18px 20px", borderRight: i < 3 ? "1px solid var(--line)" : "none" }}>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.18em" }}>{s.k}</div>
              <div style={{ fontFamily: "var(--font-stencil)", fontSize: 32, lineHeight: 1, marginTop: 6 }}>{s.v}</div>
            </div>
          ))}
        </div>
      </section>
    </>
  );
};

Object.assign(window, { SpillerePage });
