// Turneringer — oversikt over alle åpne, live og avsluttede turneringer.

const TurneringerPage = ({ accent, onNav }) => {
  const [filter, setFilter] = React.useState("alle");
  const [tournaments, setTournaments] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    WZN_Store.getTournaments().then(data => {
      setTournaments(data || []);
      setLoading(false);
    });
  }, []);

  const STATUS_ORDER = { live: 0, open: 1, locked: 2, draft: 3, completed: 4, cancelled: 5 };

  const filtered = tournaments.filter(t => {
    if (filter === "live") return t.status === "live";
    if (filter === "open") return t.status === "open";
    return true;
  });
  const sorted = [...filtered].sort((a,b) => (STATUS_ORDER[a.status]??3) - (STATUS_ORDER[b.status]??3));

  const featured = sorted[0];
  const liveCount = tournaments.filter(t => t.status === "live").length;
  const openCount = tournaments.filter(t => t.status === "open").length;

  const nextOpen = tournaments.find(t => t.status === "open");
  const nesteStarterText = nextOpen && nextOpen.start_date
    ? (() => { const dt = formatTrnDate(nextOpen.start_date); return `NESTE STARTER ${dt.date} KL ${dt.time}`; })()
    : "INGEN PLANLAGTE";

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

  return (
    <>
      <PageHeader
        eyebrow="PLAY / 02"
        title={<>TUR<span style={{ color: accent }}>NERINGER</span>.</>}
        sub="Ukentlige norske Warzone-turneringer. Verifiserte resultater, premier i pott. Meld lag eller hopp inn som solo-spiller — alle nivåer er velkommen."
        accent={accent}
        right={
          <div style={{
            display: "flex", flexDirection: "column", gap: 6, paddingBottom: 12,
            fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-faint)", letterSpacing: "0.15em",
            textAlign: "right",
          }}>
            <span>{liveCount} LIVE · {openCount} ÅPNE</span>
            <span>{nesteStarterText}</span>
          </div>
        }
      />

      {sorted.length === 0 ? (
        <section style={{ padding: "120px 48px", textAlign: "center", borderBottom: "1px solid var(--line)" }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-faint)", letterSpacing: "0.25em", marginBottom: 16 }}>
            INGEN TURNERINGER
          </div>
          <h2 style={{ fontFamily: "var(--font-stencil)", fontSize: 36, margin: 0, color: "var(--text-dim)" }}>
            {filter === "alle" ? "INGEN TURNERINGER ENNÅ" : `INGEN ${filter.toUpperCase()}-TURNERINGER`}
          </h2>
        </section>
      ) : (
        <>
          {/* Featured / next-up — full-bredde card */}
          <FeaturedTournament t={featured} accent={accent} onNav={onNav} />

          {/* Filter strip */}
          <section style={{
            padding: "32px 48px 16px",
            display: "flex", justifyContent: "space-between", alignItems: "center",
            borderBottom: "1px solid var(--line)",
          }}>
            <div style={{ display: "flex", gap: 6 }}>
              {[
                { id: "alle", label: "ALLE" },
                { id: "open", label: "PÅMELDING ÅPEN" },
                { id: "live", label: "LIVE NÅ" },
              ].map(f => {
                const active = filter === f.id;
                return (
                  <button key={f.id} onClick={() => setFilter(f.id)} style={{
                    padding: "8px 16px",
                    background: active ? "var(--bg-3)" : "transparent",
                    border: `1px solid ${active ? accent : "var(--line-2)"}`,
                    fontFamily: "var(--font-stencil)", fontSize: 12, letterSpacing: "0.06em",
                    color: active ? accent : "var(--text-dim)",
                    cursor: "pointer",
                  }}>{f.label}</button>
                );
              })}
            </div>
            <div style={{
              fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-faint)", letterSpacing: "0.15em",
            }}>VISER {sorted.length} TURNERINGER</div>
          </section>

          {/* Grid of tournaments */}
          <section style={{ padding: "32px 48px 56px" }}>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16 }}>
              {sorted.map(t => <TournamentCard key={t.id} t={t} accent={accent} onNav={onNav} />)}
            </div>
          </section>
        </>
      )}

      {/* Past tournaments */}
      {(() => {
        const past = tournaments.filter(t => t.status === "completed");
        if (past.length === 0) return null;
        return (
          <section style={{
            padding: "56px 48px",
            background: "var(--bg-1)",
            borderTop: "1px solid var(--line)",
            borderBottom: "1px solid var(--line)",
          }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 28 }}>
              <div>
                <div style={{
                  fontFamily: "var(--font-mono)", fontSize: 11, color: accent, letterSpacing: "0.25em", marginBottom: 8,
                }}>RESULTS / 02.B</div>
                <h2 style={{ fontFamily: "var(--font-stencil)", fontSize: 44, letterSpacing: "0.02em", margin: 0 }}>
                  SISTE RESULTATER
                </h2>
              </div>
              <button style={{
                padding: "10px 16px", background: "transparent", border: "1px solid var(--line-2)",
                fontFamily: "var(--font-stencil)", fontSize: 12, letterSpacing: "0.06em", color: "var(--text-dim)",
                cursor: "pointer",
              }}>SE ALLE TIDLIGERE →</button>
            </div>

            <table style={{
              width: "100%", borderCollapse: "collapse", fontFamily: "var(--font-body)",
            }}>
              <thead>
                <tr>
                  {["TURNERING", "DATO", "FORMAT", "LAG", "VINNER", "PREMIE"].map(h => (
                    <th key={h} style={{
                      textAlign: "left", fontFamily: "var(--font-mono)", fontSize: 10,
                      color: "var(--text-faint)", letterSpacing: "0.2em",
                      padding: "12px 14px", borderBottom: "1px solid var(--line)",
                    }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {past.map(p => (
                  <tr key={p.id} onClick={() => onNav && onNav("turnering", { tournamentId: p.id })} style={{
                    borderBottom: "1px solid var(--line)", cursor: "pointer", transition: "background 0.12s",
                  }}
                    onMouseEnter={(e) => { e.currentTarget.style.background = "var(--bg-2)"; }}
                    onMouseLeave={(e) => { e.currentTarget.style.background = "transparent"; }}
                  >
                    <td style={{ padding: "16px 14px", fontFamily: "var(--font-stencil)", fontSize: 15, letterSpacing: "0.04em" }}>{p.name || "—"}</td>
                    <td style={{ padding: "16px 14px", fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-dim)", letterSpacing: "0.1em" }}>
                      {p.start_date ? formatTrnDate(p.start_date).date : (p.date || "—")}
                    </td>
                    <td style={{ padding: "16px 14px", fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-dim)", letterSpacing: "0.15em" }}>
                      {(p.team_size || "trios").toUpperCase()}
                    </td>
                    <td style={{ padding: "16px 14px", fontFamily: "var(--font-mono)", fontSize: 13 }}>{p.max_teams || "—"}</td>
                    <td style={{ padding: "16px 14px" }}>
                      {p.winner ? (
                        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                          <span style={{
                            fontFamily: "var(--font-stencil)", fontSize: 12, padding: "3px 7px",
                            border: `1px solid ${accent}`, color: accent, letterSpacing: "0.04em",
                          }}>{p.winner.tag || "—"}</span>
                          <span style={{ fontFamily: "var(--font-stencil)", fontSize: 14, letterSpacing: "0.04em" }}>{p.winner.name || "—"}</span>
                        </div>
                      ) : <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-faint)" }}>—</span>}
                    </td>
                    <td style={{ padding: "16px 14px", fontFamily: "var(--font-stencil)", fontSize: 14, color: accent, letterSpacing: "0.04em" }}>
                      {p.prize_pool != null ? `${p.prize_pool.toLocaleString()} kr` : (p.prize ? `${p.prize.toLocaleString()} kr` : "—")}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </section>
        );
      })()}
    </>
  );
};

// ───────── Featured tournament — big card ─────────
const FeaturedTournament = ({ t, accent, onNav }) => {
  if (!t || !t.start_date) {
    return (
      <section style={{
        padding: "40px 48px",
        background: "var(--bg-1)",
        borderBottom: "1px solid var(--line)",
      }}>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-faint)", letterSpacing: "0.2em" }}>
          LASTER TURNERING…
        </div>
      </section>
    );
  }
  const dt = formatTrnDate(t.start_date);
  const isLive = t.status === "live";
  const registered = t.registered || 0;
  const maxTeams = t.max_teams || 1;
  const pct = (registered / maxTeams) * 100;
  return (
    <section style={{
      padding: "40px 48px",
      background: "var(--bg-1)",
      borderBottom: "1px solid var(--line)",
      position: "relative", overflow: "hidden",
    }}>
      {/* Big background watermark */}
      <div style={{
        position: "absolute", right: -40, top: -80,
        fontFamily: "var(--font-stencil)", fontSize: 320, lineHeight: 0.9,
        color: "rgba(255,255,255,0.02)", pointerEvents: "none", letterSpacing: "-0.02em",
      }}>{isLive ? "LIVE" : "NESTE"}</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 ${accent}`, padding: "5px 12px",
            fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.2em", color: accent,
            marginBottom: 18,
          }}>
            {isLive ? (
              <>
                <span style={{ width: 8, height: 8, background: accent, borderRadius: "50%" }} />
                LIVE NÅ · {(t.type || "bracket").toUpperCase()}
              </>
            ) : (
              <>★ NESTE OPP · {(t.type || "bracket").toUpperCase()}</>
            )}
          </div>
          <h2 style={{
            fontFamily: "var(--font-stencil)", fontSize: 72, letterSpacing: "0.01em", lineHeight: 0.95, margin: 0,
          }}>{(t.name || "").toUpperCase()}</h2>
          <div style={{
            fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--text-dim)",
            letterSpacing: "0.12em", marginTop: 12,
          }}>
            {(t.team_size || "trios").toUpperCase()} · {t.games || 5} 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-0)",
          }}>
            {[
              { n: dt.date, l: dt.day.toUpperCase() + " · MAI" },
              { n: dt.time, l: "STARTER" },
              { n: `${registered}/${maxTeams}`, l: "LAG" },
              { n: `${(t.prize_pool || 0) >= 1000 ? `${(t.prize_pool||0)/1000}K` : (t.prize_pool||0)} kr`, l: "POTT", 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: 28, 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>

        <div style={{
          background: "var(--bg-2)", border: `1px solid ${accent}`,
          padding: 24, position: "relative", overflow: "hidden",
        }}>
          <div style={{
            fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)",
            letterSpacing: "0.2em", marginBottom: 14,
          }}>{isLive ? "FØLG LIVE" : "PÅMELDING"}</div>

          <div style={{ marginBottom: 16 }}>
            <div style={{
              position: "relative", height: 6, background: "var(--bg-3)", border: "1px solid var(--line-2)",
            }}>
              <div style={{ position: "absolute", inset: 0, width: `${pct}%`, 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}/{maxTeams} LAG PÅMELDT</span>
              <span>{maxTeams - registered} LEDIGE</span>
            </div>
          </div>

          <button onClick={() => onNav && onNav("turnering", { tournamentId: t.id })} className="cta" style={{
            background: accent, color: "var(--bg-0)", borderColor: accent,
            fontWeight: 700, padding: "14px 18px", justifyContent: "space-between",
            width: "100%", marginBottom: 8, cursor: "pointer",
          }}>
            <span>{isLive ? "FØLG LIVE" : "PÅMELD LAGET DITT"}</span> <span>▶</span>
          </button>
          <button onClick={() => onNav && onNav("turnering", { tournamentId: t.id })} className="cta cta-ghost" style={{
            padding: "14px 18px", justifyContent: "space-between", width: "100%", cursor: "pointer",
          }}>
            <span>SE DETALJER</span> <span>↗</span>
          </button>
        </div>
      </div>
    </section>
  );
};

// ───────── Tournament card (kompakt, brukes i grid) ─────────
const TournamentCard = ({ t, accent, onNav }) => {
  if (!t || !t.start_date) {
    return (
      <div style={{
        background: "var(--bg-1)", border: "1px solid var(--line)",
        padding: 22, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-faint)",
      }}>LASTER…</div>
    );
  }
  const dt = formatTrnDate(t.start_date);
  const isLive = t.status === "live";
  const registered = t.registered || 0;
  const maxTeams = t.max_teams || 1;
  const pct = (registered / maxTeams) * 100;
  return (
    <div onClick={() => onNav && onNav("turnering", { tournamentId: t.id })} style={{
      background: "var(--bg-1)", border: `1px solid ${isLive ? accent : "var(--line)"}`,
      padding: 22, position: "relative", overflow: "hidden", cursor: "pointer",
      transition: "border-color 0.15s, transform 0.15s",
    }}
      onMouseEnter={(e) => { e.currentTarget.style.borderColor = accent; e.currentTarget.style.transform = "translateY(-2px)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.borderColor = isLive ? accent : "var(--line)"; e.currentTarget.style.transform = "translateY(0)"; }}
    >
      <span className="hcard-corners">
        <span /><span /><span /><span />
      </span>
      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "center",
        paddingBottom: 12, borderBottom: "1px solid var(--line)",
        fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.2em",
      }}>
        <span style={{ color: isLive ? accent : "var(--text-faint)" }}>
          {isLive ? "● LIVE NÅ" : "PÅMELDING ÅPEN"}
        </span>
        <span style={{
          border: `1px solid ${accent}`, color: accent, padding: "2px 8px",
        }}>
          {t.type === "killrace" ? "▰ KILLRACE" : "▰ BRACKET"}
        </span>
      </div>

      <h3 style={{
        fontFamily: "var(--font-stencil)", fontSize: 26, letterSpacing: "0.02em",
        lineHeight: 1.1, marginTop: 16,
      }}>{t.name || ""}</h3>
      <div style={{
        fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-dim)",
        letterSpacing: "0.12em", marginTop: 6,
      }}>
        {(t.team_size || "trios").toUpperCase()} · {t.games || 5} GAMES{t.maps && t.maps.length ? " · " + t.maps.join(", ") : ""}
      </div>

      <div style={{
        display: "grid", gridTemplateColumns: "repeat(3,1fr)",
        marginTop: 18, border: "1px solid var(--line)",
      }}>
        <div style={{ padding: "12px 14px", borderRight: "1px solid var(--line)" }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.18em" }}>START</div>
          <div style={{ fontFamily: "var(--font-stencil)", fontSize: 14, marginTop: 4 }}>{dt.day} {dt.date}</div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-dim)" }}>{dt.time}</div>
        </div>
        <div style={{ padding: "12px 14px", borderRight: "1px solid var(--line)" }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.18em" }}>LAG</div>
          <div style={{ fontFamily: "var(--font-stencil)", fontSize: 14, marginTop: 4 }}>{registered}/{maxTeams}</div>
        </div>
        <div style={{ padding: "12px 14px" }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", letterSpacing: "0.18em" }}>PREMIE</div>
          <div style={{ fontFamily: "var(--font-stencil)", fontSize: 14, marginTop: 4, color: accent }}>{(t.prize_pool || 0).toLocaleString()} kr</div>
        </div>
      </div>

      <div style={{ marginTop: 14 }}>
        <div style={{
          position: "relative", height: 4, background: "var(--bg-3)", border: "1px solid var(--line-2)",
        }}>
          <div style={{ position: "absolute", inset: 0, width: `${pct}%`, background: accent }} />
        </div>
        <div style={{
          fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)",
          letterSpacing: "0.15em", marginTop: 6,
        }}>{maxTeams - registered} LEDIGE PLASSER</div>
      </div>

      <button onClick={(e) => { e.stopPropagation(); onNav && onNav("turnering", { tournamentId: t.id }); }} className="cta" style={{
        marginTop: 18, width: "100%", justifyContent: "space-between",
        background: accent, color: "var(--bg-0)", fontWeight: 700, padding: "12px 16px", borderColor: accent,
        cursor: "pointer",
      }}>
        <span>{isLive ? "FØLG LIVE" : "PÅMELD LAG"}</span> <span>▶</span>
      </button>
    </div>
  );
};

Object.assign(window, { TurneringerPage });
