// App — multi-page WZN Liga site. Top-nav switcher + page rendering.
// URL-routing via history.pushState — sider er delbare og bokmerkerbare.

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#ff6b35"
}/*EDITMODE-END*/;

const ACCENT_OPTIONS = [
  "#ff6b35", // orange (WZN default)
  "#ffb700", // amber
  "#e63946", // rød
  "#22d3ee", // cyan
];

const ADMIN_ROLES = ["admin", "superadmin", "mod"];

// ── URL ↔ Route-mapping ────────────────────────────────────────────────────
// Konverterer mellom URL-sti og intern route-ID + kontekst.

const ROUTE_TO_PATH = {
  landing:     "/",
  turneringer: "/turneringer",
  turnering:   "/turnering",   // + /:id
  pamelding:   "/pamelding",
  liga:        "/liga",
  stats:       "/stats",
  regler:      "/regler",
  om:          "/om-oss",
  spillere:    "/spillere",
  lag:         "/lag",
  hof:         "/hall-of-fame",
  nyheter:     "/nyheter",
  highlights:  "/highlights",
  "min-side":  "/min-side",
  admin:       "/admin",
  kaptein:     "/kaptein",
};

const parseLocationToRoute = () => {
  const path = window.location.pathname.replace(/\/$/, "") || "/";
  const params = new URLSearchParams(window.location.search);

  if (path === "" || path === "/")        return { route: "landing",     ctx: {} };
  if (path === "/turneringer")            return { route: "turneringer",  ctx: {} };
  if (path.startsWith("/turnering"))      return { route: "turnering",    ctx: { tournamentId: path.split("/")[2] || params.get("id") || null } };
  if (path === "/pamelding")              return { route: "pamelding",    ctx: { tournamentId: params.get("id") || null } };
  if (path === "/liga")                   return { route: "liga",         ctx: {} };
  if (path === "/stats")                  return { route: "stats",        ctx: {} };
  if (path === "/regler")                 return { route: "regler",       ctx: {} };
  if (path === "/om-oss")                 return { route: "om",           ctx: {} };
  if (path === "/spillere")               return { route: "spillere",     ctx: {} };
  if (path === "/lag")                    return { route: "lag",          ctx: {} };
  if (path === "/hall-of-fame")           return { route: "hof",          ctx: {} };
  if (path === "/nyheter")               return { route: "nyheter",      ctx: {} };
  if (path === "/highlights")             return { route: "highlights",   ctx: {} };
  if (path === "/min-side")              return { route: "min-side",     ctx: {} };
  if (path === "/admin")                  return { route: "admin",        ctx: {} };
  if (path === "/kaptein")               return { route: "kaptein",      ctx: {} };
  return { route: "landing", ctx: {} };
};

const buildUrl = (id, opts = {}) => {
  const base = ROUTE_TO_PATH[id] || "/";
  if (id === "turnering" && opts.tournamentId) return `/turnering/${opts.tournamentId}`;
  if (id === "pamelding" && opts.tournamentId) return `/pamelding?id=${opts.tournamentId}`;
  return base;
};

// ── 403-side ───────────────────────────────────────────────────────────────

const AdminAccessDenied = ({ accent, isLoggedIn, onNav }) => (
  <>
    <section style={{ padding: "80px 48px", display: "flex", justifyContent: "center", background: "var(--bg-0)" }}>
      <div style={{ maxWidth: 480, width: "100%", textAlign: "center" }}>
        <div style={{ fontFamily: "var(--font-stencil)", fontSize: 120, lineHeight: 1, color: "rgba(255,255,255,0.04)", marginBottom: -20 }}>403</div>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: accent, letterSpacing: "0.25em", marginBottom: 16 }}>TILGANG NEKTET</div>
        <h1 style={{ fontFamily: "var(--font-stencil)", fontSize: 52, lineHeight: 0.95, margin: "0 0 20px" }}>
          IKKE <span style={{ color: accent }}>TILGANG.</span>
        </h1>
        <p style={{ fontFamily: "var(--font-body)", fontSize: 16, color: "var(--text-dim)", lineHeight: 1.6, marginBottom: 32 }}>
          {isLoggedIn
            ? "Du har ikke admin-rettigheter. Kontakt en admin for å få tilgang."
            : "Du må logge inn med en konto som har admin-rolle for å se denne siden."}
        </p>
        <div style={{ display: "flex", gap: 12, justifyContent: "center" }}>
          <button onClick={() => onNav("landing")} style={{
            padding: "12px 22px", background: "transparent", border: "1px solid var(--line)",
            fontFamily: "var(--font-stencil)", fontSize: 13, letterSpacing: "0.06em",
            color: "var(--text-dim)", cursor: "pointer",
          }}>← TILBAKE TIL FORSIDEN</button>
          {!isLoggedIn && (
            <button onClick={() => onNav("min-side")} style={{
              padding: "12px 22px", background: accent, border: `1px solid ${accent}`,
              fontFamily: "var(--font-stencil)", fontSize: 13, letterSpacing: "0.06em",
              color: "var(--bg-0)", cursor: "pointer", fontWeight: 700,
            }}>LOGG INN ↗</button>
          )}
        </div>
      </div>
    </section>
  </>
);

// ── App ────────────────────────────────────────────────────────────────────

const App = () => {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const accent = tweaks.accent;

  // Initialiser route fra URL (støtter direkte navigasjon + refresh)
  const initial = parseLocationToRoute();
  const [route,    setRoute]    = React.useState(initial.route);
  const [anchor,   setAnchor]   = React.useState(null);
  const [routeCtx, setRouteCtx] = React.useState(initial.ctx);
  const [isLoggedIn,  setIsLoggedIn]  = React.useState(false);
  const [discordUser, setDiscordUser] = React.useState(null);
  const [userRole,    setUserRole]    = React.useState(null);

  // Hent rolle fra user_roles
  const fetchUserRole = React.useCallback(async (userId) => {
    if (!userId || !window.WZN_Store) return;
    try {
      const roles = await WZN_Store.getUserRoles();
      const mine = roles.find(r => r.user_id === userId);
      setUserRole(mine?.role || "player");
    } catch { setUserRole("player"); }
  }, []);

  // Auth state
  React.useEffect(() => {
    if (!window.db) return;
    window.db.auth.getSession().then(({ data }) => {
      if (data.session) {
        setIsLoggedIn(true);
        setDiscordUser(data.session.user);
        fetchUserRole(data.session.user.id);
        // Sørg for at user_roles-raden eksisterer (oppretter ved første lasting
        // etter login — onAuthStateChange kjører kun ved nytt login-event)
        if (window.WZN_Store) {
          const u = data.session.user;
          const meta = u.user_metadata || {};
          const discordIdentity = (u.identities || []).find(i => i.provider === "discord");
          WZN_Store.upsertUserRole({
            user_id:      u.id,
            discord_id:   discordIdentity?.id || null,
            discord_name: meta.full_name || meta.name || meta.global_name || null,
            email:        u.email || null,
            display_name: meta.full_name || meta.name || meta.global_name || u.email?.split("@")[0] || null,
          }).catch(() => {});
        }
      }
    });
    const { data: { subscription } } = window.db.auth.onAuthStateChange((event, session) => {
      setIsLoggedIn(!!session);
      setDiscordUser(session?.user || null);
      if (session?.user) {
        fetchUserRole(session.user.id);
        if (window.WZN_Store) {
          const u = session.user;
          const meta = u.user_metadata || {};
          const discordIdentity = (u.identities || []).find(i => i.provider === "discord");
          WZN_Store.upsertUserRole({
            user_id:      u.id,
            discord_id:   discordIdentity?.id || null,
            discord_name: meta.full_name || meta.name || meta.global_name || null,
            email:        u.email || null,
            display_name: meta.full_name || meta.name || meta.global_name || u.email?.split("@")[0] || null,
          }).catch(() => {});
        }
      } else {
        setUserRole(null);
      }
    });
    return () => subscription.unsubscribe();
  }, []);

  // Browser tilbake/fremover-knapper
  React.useEffect(() => {
    const onPop = () => {
      const { route: r, ctx } = parseLocationToRoute();
      setRoute(r);
      setRouteCtx(ctx);
      setAnchor(null);
    };
    window.addEventListener("popstate", onPop);
    return () => window.removeEventListener("popstate", onPop);
  }, []);

  // Scroll-effekt ved route-bytte
  React.useEffect(() => {
    if (anchor) {
      const t = setTimeout(() => {
        const el = document.getElementById(anchor);
        if (el) {
          const top = el.getBoundingClientRect().top + window.scrollY - 80;
          window.scrollTo({ top, behavior: "smooth" });
        }
      }, 80);
      return () => clearTimeout(t);
    }
    window.scrollTo({ top: 0, behavior: "instant" });
  }, [route, anchor, routeCtx]);

  // Oppdater <title> ved route-bytte
  React.useEffect(() => {
    const titles = {
      landing:     "WZN Liga — Norges råeste Warzone-turneringer",
      turneringer: "Turneringer — WZN Liga",
      turnering:   "Turnering — WZN Liga",
      pamelding:   "Påmelding — WZN Liga",
      liga:        "Liga — WZN Liga",
      stats:       "Stats — WZN Liga",
      regler:      "Regler — WZN Liga",
      om:          "Om oss — WZN Liga",
      spillere:    "Spillere — WZN Liga",
      lag:         "Lag — WZN Liga",
      hof:         "Hall of Fame — WZN Liga",
      nyheter:     "Nyheter — WZN Liga",
      highlights:  "Highlights — WZN Liga",
      "min-side":  "Min side — WZN Liga",
      admin:       "Admin — WZN Liga",
      kaptein:     "Kaptein — WZN Liga",
    };
    document.title = titles[route] || "WZN Liga";
  }, [route]);

  const handleNav = (id, opts = {}) => {
    if (id === "__logout__") {
      window.db?.auth.signOut();
      history.pushState({}, "", "/");
      setRoute("landing");
      setRouteCtx({});
      setAnchor(null);
      return;
    }
    const url = buildUrl(id, opts);
    history.pushState({ route: id, ctx: opts }, "", url);
    setRoute(id);
    setAnchor(opts.anchor || null);
    setRouteCtx(opts || {});
  };

  return (
    <>
      <style>{`
        :root { --accent: ${accent}; }
        html, body { background: var(--bg-0); }
      `}</style>

      <TopNav current={route} onNav={handleNav} accent={accent} isLoggedIn={isLoggedIn} discordUser={discordUser} userRole={userRole} />

      {route === "landing"     && <BroadcastLanding accent={accent} onNav={handleNav} />}
      {route === "turneringer" && <TurneringerPage accent={accent} onNav={handleNav} />}
      {route === "turnering"   && <TurneringDetailPage accent={accent} tournamentId={routeCtx.tournamentId} onNav={handleNav} userRole={userRole} />}
      {route === "pamelding"   && <PameldingPage accent={accent} tournamentId={routeCtx.tournamentId} onNav={handleNav} discordUser={discordUser} isLoggedIn={isLoggedIn} />}
      {route === "liga"        && <LigaPage accent={accent} />}
      {route === "stats"       && <StatsPage accent={accent} />}
      {route === "regler"      && <ReglerPage accent={accent} />}
      {route === "om"          && <OmOssPage accent={accent} />}
      {route === "spillere"    && <SpillerePage accent={accent} onNav={handleNav} />}
      {route === "lag"         && <LagPage accent={accent} />}
      {route === "hof"         && <HallOfFamePage accent={accent} onNav={handleNav} />}
      {route === "nyheter"     && <NewsHub tweaks={{ accent }} userRole={userRole} />}
      {route === "highlights"  && <HighlightsScreen tweaks={{ accent }} tab={anchor} />}
      {route === "min-side"    && <MinSidePage accent={accent} onNav={handleNav} isLoggedIn={isLoggedIn} discordUser={discordUser} />}
      {route === "admin"       && (
        ADMIN_ROLES.includes(userRole) ? (
          <AdminDashboard tweaks={{ accent }} role={userRole} />
        ) : (
          <AdminAccessDenied accent={accent} isLoggedIn={isLoggedIn} onNav={handleNav} />
        )
      )}
      {route === "kaptein"     && <CaptainDashboard tweaks={{ accent }} />}

      <SiteFooter accent={accent} onNav={handleNav} />

      <TweaksPanel title="TWEAKS">
        <TweakSection label="Accent" />
        <TweakColor
          label="Aksentfarge"
          value={accent}
          options={ACCENT_OPTIONS}
          onChange={v => setTweak("accent", v)}
        />
      </TweaksPanel>
    </>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
