// Top-nav + side shell. Brukes på alle sider.
// Redesignet for alle sider: to grupper + Min side / Login til høyre.

// ROLE_LABELS — eksponert globalt for Admin.jsx, Captain.jsx osv.
const ROLE_LABELS = {
  player:     "SPILLER",
  captain:    "KAPTEIN",
  mod:        "MOD",
  admin:      "ADMIN",
  superadmin: "SUPER ADMIN",
};
window.ROLE_LABELS = ROLE_LABELS;

const NAV_GROUPS = [
  {
    items: [
      { id: "landing",     label: "FORSIDE" },
      { id: "turneringer", label: "TURNERINGER" },
      { id: "liga",        label: "LIGA" },
    ],
  },
  {
    items: [
      { id: "spillere",    label: "SPILLERE" },
      { id: "lag",         label: "LAG" },
      { id: "hof",         label: "HALL OF FAME" },
    ],
  },
  {
    items: [
      { id: "regler",      label: "REGLER" },
      { id: "om",          label: "OM OSS" },
    ],
  },
];

const NAV_ITEMS = NAV_GROUPS.flatMap(g => g.items);

const TopNav = ({ current, onNav, accent, isLoggedIn, discordUser, userRole }) => {
  const isAdminUser = userRole && ["admin", "superadmin", "mod"].includes(userRole);
  const meta = discordUser?.user_metadata || {};
  const avatarUrl = meta.avatar_url || null;
  const displayName = meta.full_name || meta.name || meta.global_name || discordUser?.email?.split("@")[0] || "MIN SIDE";
  const initials = displayName.slice(0, 2).toUpperCase();
  const roleLabel = ROLE_LABELS[userRole] || null;

  const [dropOpen, setDropOpen] = React.useState(false);
  const dropRef = React.useRef(null);

  // Lukk dropdown ved klikk utenfor
  React.useEffect(() => {
    if (!dropOpen) return;
    const handler = (e) => {
      if (dropRef.current && !dropRef.current.contains(e.target)) setDropOpen(false);
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [dropOpen]);

  const go = (id) => { setDropOpen(false); onNav(id); };

  return (
  <div style={{
    display: "flex", alignItems: "center", justifyContent: "space-between",
    padding: "0 32px",
    borderBottom: "1px solid var(--line)",
    background: "var(--bg-1)",
    position: "sticky", top: 0, zIndex: 200,
    height: 58,
  }}>
    {/* Logo */}
    <button onClick={() => onNav("landing")} style={{
      display: "flex", alignItems: "center", gap: 10, flexShrink: 0,
      background: "transparent", border: "none", cursor: "pointer", padding: "0 12px 0 0",
      borderRight: "1px solid var(--line)",
    }}>
      <span style={{ width: 12, height: 12, background: accent, display: "inline-block" }} />
      <span style={{ fontFamily: "var(--font-stencil)", fontSize: 20, letterSpacing: "0.04em", color: "var(--text)" }}>
        WZN <span style={{ color: accent }}>LIGA</span>
      </span>
    </button>

    {/* Nav groups */}
    <div style={{ display: "flex", alignItems: "stretch", flex: 1, marginLeft: 0, height: "100%" }}>
      {NAV_GROUPS.map((group, gi) => (
        <React.Fragment key={gi}>
          {gi > 0 && (
            <div style={{ width: 1, background: "var(--line)", margin: "12px 6px", flexShrink: 0 }} />
          )}
          {group.items.map(it => {
            const active = current === it.id;
            return (
              <button key={it.id} onClick={() => onNav(it.id)} style={{
                padding: "0 14px",
                background: active ? "var(--bg-2)" : "transparent",
                border: "none",
                fontFamily: "var(--font-stencil)", fontSize: 12, letterSpacing: "0.06em",
                color: active ? "var(--text)" : "var(--text-dim)",
                cursor: "pointer", position: "relative",
                borderBottom: active ? `2px solid ${accent}` : "2px solid transparent",
                transition: "color 0.12s, background 0.12s",
                height: "100%", whiteSpace: "nowrap",
              }}
                onMouseEnter={e => { if (!active) e.currentTarget.style.color = "var(--text)"; }}
                onMouseLeave={e => { if (!active) e.currentTarget.style.color = "var(--text-dim)"; }}
              >
                {it.label}
              </button>
            );
          })}
        </React.Fragment>
      ))}
    </div>

    {/* Right: avatar dropdown / login */}
    <div ref={dropRef} style={{ display: "flex", alignItems: "center", gap: 8, flexShrink: 0, borderLeft: "1px solid var(--line)", paddingLeft: 16, position: "relative" }}>
      {isLoggedIn ? (
        <>
          {/* Avatar trigger */}
          <button
            onClick={() => setDropOpen(o => !o)}
            style={{
              display: "flex", alignItems: "center", gap: 10,
              padding: "5px 10px 5px 6px",
              background: dropOpen ? "var(--bg-2)" : "transparent",
              border: `1px solid ${dropOpen ? accent : "var(--line-2)"}`,
              cursor: "pointer", transition: "border-color 0.12s",
            }}
            onMouseEnter={e => e.currentTarget.style.borderColor = accent}
            onMouseLeave={e => e.currentTarget.style.borderColor = dropOpen ? accent : "var(--line-2)"}
          >
            {avatarUrl ? (
              <img src={avatarUrl} alt={displayName} style={{ width: 28, height: 28, display: "block", objectFit: "cover", borderRadius: 0 }} />
            ) : (
              <div style={{ width: 28, height: 28, background: accent, display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--font-stencil)", fontSize: 12, color: "var(--bg-0)", fontWeight: 700 }}>{initials}</div>
            )}
            <span style={{ fontFamily: "var(--font-stencil)", fontSize: 12, letterSpacing: "0.06em", color: "var(--text)", whiteSpace: "nowrap", maxWidth: 110, overflow: "hidden", textOverflow: "ellipsis" }}>
              {displayName.toUpperCase()}
            </span>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-faint)", marginLeft: 2 }}>{dropOpen ? "▲" : "▼"}</span>
          </button>

          {/* Dropdown */}
          {dropOpen && (
            <div style={{
              position: "absolute", top: "calc(100% + 8px)", right: 0,
              width: 240,
              background: "var(--bg-1)", border: `1px solid var(--line)`,
              boxShadow: "0 8px 32px rgba(0,0,0,0.5)",
              zIndex: 300,
            }}>
              {/* Profile header */}
              <div style={{ padding: "16px 18px", borderBottom: "1px solid var(--line)", background: "var(--bg-2)" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                  {avatarUrl ? (
                    <img src={avatarUrl} alt={displayName} style={{ width: 40, height: 40, display: "block", objectFit: "cover" }} />
                  ) : (
                    <div style={{ width: 40, height: 40, background: accent, display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--font-stencil)", fontSize: 16, color: "var(--bg-0)", fontWeight: 700 }}>{initials}</div>
                  )}
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontFamily: "var(--font-stencil)", fontSize: 14, letterSpacing: "0.04em", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                      {displayName.toUpperCase()}
                    </div>
                    {roleLabel && (
                      <div style={{
                        display: "inline-block", marginTop: 4,
                        fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.2em",
                        padding: "2px 7px", border: `1px solid ${accent}`, color: accent,
                      }}>{roleLabel}</div>
                    )}
                  </div>
                </div>
              </div>

              {/* Menu items */}
              <div style={{ padding: "6px 0" }}>
                {[
                  { id: "min-side",  label: "MIN SIDE",     icon: "◈", sub: "Oversikt og statistikk" },
                  { id: "min-side",  label: "MITT LAG",     icon: "⊞", sub: "Lag og roster", anchor: "lag" },
                  { id: "turneringer", label: "TURNERINGER", icon: "▰", sub: "Se alle turneringer" },
                  { id: "min-side",  label: "INNSTILLINGER", icon: "⚙", sub: "Konto og Activision ID", anchor: "innstillinger" },
                ].map((item, i) => (
                  <button key={i} onClick={() => { setDropOpen(false); onNav(item.id, item.anchor ? { anchor: item.anchor } : {}); }} style={{
                    width: "100%", display: "flex", alignItems: "center", gap: 12,
                    padding: "10px 18px", background: "transparent", border: "none",
                    cursor: "pointer", textAlign: "left",
                    transition: "background 0.1s",
                  }}
                    onMouseEnter={e => e.currentTarget.style.background = "var(--bg-2)"}
                    onMouseLeave={e => e.currentTarget.style.background = "transparent"}
                  >
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: 14, color: accent, width: 20, textAlign: "center", flexShrink: 0 }}>{item.icon}</span>
                    <div>
                      <div style={{ fontFamily: "var(--font-stencil)", fontSize: 12, letterSpacing: "0.06em", color: "var(--text)" }}>{item.label}</div>
                      <div style={{ fontFamily: "var(--font-body)", fontSize: 11, color: "var(--text-faint)", marginTop: 1 }}>{item.sub}</div>
                    </div>
                  </button>
                ))}

                {/* Admin-seksjonen */}
                {isAdminUser && (
                  <>
                    <div style={{ margin: "6px 18px", height: 1, background: "var(--line)" }} />
                    <button onClick={() => go("admin")} style={{
                      width: "100%", display: "flex", alignItems: "center", gap: 12,
                      padding: "10px 18px", background: "transparent", border: "none",
                      cursor: "pointer", textAlign: "left",
                      transition: "background 0.1s",
                    }}
                      onMouseEnter={e => e.currentTarget.style.background = `rgba(255,107,53,0.08)`}
                      onMouseLeave={e => e.currentTarget.style.background = "transparent"}
                    >
                      <span style={{ fontFamily: "var(--font-mono)", fontSize: 14, color: accent, width: 20, textAlign: "center", flexShrink: 0 }}>⬡</span>
                      <div>
                        <div style={{ fontFamily: "var(--font-stencil)", fontSize: 12, letterSpacing: "0.06em", color: accent }}>ADMIN PANEL</div>
                        <div style={{ fontFamily: "var(--font-body)", fontSize: 11, color: "var(--text-faint)", marginTop: 1 }}>Turneringer, lag og score</div>
                      </div>
                    </button>
                  </>
                )}

                {/* Logg ut */}
                <div style={{ margin: "6px 18px", height: 1, background: "var(--line)" }} />
                <button onClick={() => { setDropOpen(false); onNav("__logout__"); }} style={{
                  width: "100%", display: "flex", alignItems: "center", gap: 12,
                  padding: "10px 18px", background: "transparent", border: "none",
                  cursor: "pointer", textAlign: "left",
                  transition: "background 0.1s",
                }}
                  onMouseEnter={e => e.currentTarget.style.background = "var(--bg-2)"}
                  onMouseLeave={e => e.currentTarget.style.background = "transparent"}
                >
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 14, color: "var(--text-faint)", width: 20, textAlign: "center", flexShrink: 0 }}>↩</span>
                  <div>
                    <div style={{ fontFamily: "var(--font-stencil)", fontSize: 12, letterSpacing: "0.06em", color: "var(--text-dim)" }}>LOGG UT</div>
                    <div style={{ fontFamily: "var(--font-body)", fontSize: 11, color: "var(--text-faint)", marginTop: 1 }}>{discordUser?.email || ""}</div>
                  </div>
                </button>
              </div>
            </div>
          )}
        </>
      ) : (
        <>
          <button onClick={() => onNav("min-side")} style={{
            padding: "8px 14px",
            background: "transparent", border: "1px solid var(--line-2)",
            fontFamily: "var(--font-stencil)", fontSize: 12, letterSpacing: "0.06em",
            color: "var(--text-dim)", cursor: "pointer",
          }}>MIN SIDE</button>
          <button onClick={() => onNav("min-side")} style={{
            padding: "8px 16px",
            background: accent, border: `1px solid ${accent}`,
            fontFamily: "var(--font-stencil)", fontSize: 12, letterSpacing: "0.06em",
            color: "var(--bg-0)", cursor: "pointer", fontWeight: 700,
          }}>LOGG INN ↗</button>
        </>
      )}
    </div>
  </div>
  );
};

// ───────── Footer ─────────
const SiteFooter = ({ accent, onNav }) => (
  <footer style={{
    padding: "48px 48px 36px",
    borderTop: "1px solid var(--line)",
    background: "var(--bg-1)",
  }}>
    <div style={{
      display: "grid", gridTemplateColumns: "2fr 1fr 1fr 1fr", gap: 48,
      paddingBottom: 32, borderBottom: "1px solid var(--line)", marginBottom: 24,
    }}>
      <div>
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 12 }}>
          <span style={{ width: 14, height: 14, background: accent, display: "inline-block" }} />
          <span style={{
            fontFamily: "var(--font-stencil)", fontSize: 22, letterSpacing: "0.04em", color: "var(--text)",
          }}>WZN <span style={{ color: accent }}>LIGA</span></span>
        </div>
        <p style={{
          fontFamily: "var(--font-body)", fontSize: 14, color: "var(--text-dim)",
          maxWidth: 360, lineHeight: 1.55,
        }}>
          Vi prøver å samle Warzone Norge gjennom ukentlige turneringer og en sesonglang liga på vei.
          Åpent for alle — bronze eller iridescent.
        </p>
      </div>
      {[
        { h: "SPILL",  links: [["Åpne turneringer","turneringer"],["Meld interesse for liga","liga"],["Regler","regler"],["Påmelding","turneringer"]] },
        { h: "SCENE",  links: [["Spillere","spillere"],["Lag","lag"],["Hall of Fame","hof"],["Highlights","highlights"]] },
        { h: "INFO",   links: [["Nyheter","nyheter"],["Hvem er vi","om"],["Min side","min-side"],["Discord",""]] },
      ].map(col => (
        <div key={col.h}>
          <div style={{
            fontFamily: "var(--font-mono)", fontSize: 10, color: accent,
            letterSpacing: "0.25em", marginBottom: 14,
          }}>{col.h}</div>
          <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 10 }}>
            {col.links.map(([label, route]) => (
              <li key={label}>
                <button onClick={() => route && onNav && onNav(route)} style={{
                  fontFamily: "var(--font-body)", fontSize: 14, color: "var(--text-dim)",
                  background: "none", border: "none", padding: 0, cursor: route ? "pointer" : "default",
                  textAlign: "left",
                }}>{label}</button>
              </li>
            ))}
          </ul>
        </div>
      ))}
    </div>
    <div style={{
      display: "flex", justifyContent: "space-between",
      fontFamily: "var(--font-mono)", fontSize: 11,
      color: "var(--text-faint)", letterSpacing: "0.18em",
    }}>
      <span>WZN LIGA NORGE · 2026</span>
      <span>SECTOR-NO · 60°23′N 5°19′E</span>
      <span>v2026.05.19</span>
    </div>
  </footer>
);

// ───────── Generic page header ─────────
const PageHeader = ({ eyebrow, title, sub, accent, right }) => (
  <section style={{
    padding: "56px 48px 36px",
    borderBottom: "1px solid var(--line)",
    background: "var(--bg-0)",
    position: "relative", overflow: "hidden",
  }}>
    <div style={{
      position: "absolute", inset: 0,
      backgroundImage: `repeating-linear-gradient(115deg, transparent 0 120px, rgba(255,255,255,0.015) 120px 121px)`,
      pointerEvents: "none",
    }} />
    <div style={{ position: "relative", zIndex: 1, display: "flex", justifyContent: "space-between", alignItems: "flex-end" }}>
      <div>
        <div style={{
          fontFamily: "var(--font-mono)", fontSize: 11, color: accent, letterSpacing: "0.25em", marginBottom: 10,
        }}>{eyebrow}</div>
        <h1 style={{
          fontFamily: "var(--font-stencil)", fontSize: 80, letterSpacing: "0.01em", margin: 0, lineHeight: 0.95,
        }}>{title}</h1>
        {sub && (
          <p style={{
            fontSize: 17, color: "var(--text-dim)", maxWidth: 680, marginTop: 14, lineHeight: 1.55,
          }}>{sub}</p>
        )}
      </div>
      {right}
    </div>
  </section>
);

Object.assign(window, { TopNav, SiteFooter, PageHeader, NAV_ITEMS, NAV_GROUPS });
