"use client";

import { SessionProvider as NextAuthSessionProvider, useSession } from "next-auth/react";
import { useEffect, useRef } from "react";
import { HeaderProvider } from "./header-provider";

const LOGOUT_BROADCAST_KEY = "re-quest-logout-broadcast";

// Listens for logout broadcasts from OTHER tabs and forces this tab to reload.
// When the logout page clears auth, it writes a timestamp to LOGOUT_BROADCAST_KEY;
// every other open tab receives a `storage` event and reloads into an unauthed state.
function CrossTabLogoutListener() {
  useEffect(() => {
    const onStorage = (e: StorageEvent) => {
      if (e.key !== LOGOUT_BROADCAST_KEY || !e.newValue) return;
      // Skip auth pages — they're already unauthed.
      const path = window.location.pathname;
      const onAuthPage =
        path === "/login" ||
        path === "/signup" ||
        path === "/logout" ||
        path === "/" ||
        path.startsWith("/forgot-password") ||
        path.startsWith("/reset-password");
      if (onAuthPage) return;
      // Clear local auth and hard-redirect to /logout so this tab runs the full cleanup too.
      localStorage.removeItem("accessToken");
      localStorage.removeItem("refreshToken");
      localStorage.removeItem("user");
      window.location.replace("/logout");
    };
    window.addEventListener("storage", onStorage);
    return () => window.removeEventListener("storage", onStorage);
  }, []);
  return null;
}

// Component that syncs tokens from NextAuth session to localStorage
function TokenSync() {
  const { data: session, status } = useSession();
  const hasInitialized = useRef(false);

  useEffect(() => {
    // Never restore tokens if a logout is in progress or we're on auth/logout pages
    const loggingOut = localStorage.getItem("isLoggingOut") === "true";
    const path = window.location.pathname;
    const onAuthPage = path === "/login" || path === "/signup" || path === "/logout"
      || path.startsWith("/forgot-password") || path.startsWith("/reset-password");

    if (status === "authenticated" && session?.user && !loggingOut && !onAuthPage) {
      const user = session.user as { accessToken?: string; refreshToken?: string };

      // Only sync tokens from NextAuth to localStorage if:
      // 1. This is the first time we're initializing (fresh login)
      // 2. OR localStorage doesn't have tokens yet
      // This prevents overwriting tokens that were refreshed by the API interceptor
      const existingAccessToken = localStorage.getItem("accessToken");
      const existingRefreshToken = localStorage.getItem("refreshToken");

      // If localStorage is empty, this is likely a fresh login - sync tokens
      if (!existingAccessToken && !existingRefreshToken) {
        if (user.accessToken) {
          localStorage.setItem("accessToken", user.accessToken);
        }
        if (user.refreshToken) {
          localStorage.setItem("refreshToken", user.refreshToken);
        }
        hasInitialized.current = true;
      }
      // If we have tokens in localStorage but haven't initialized yet,
      // it means the API interceptor has refreshed tokens - don't overwrite
      else if (!hasInitialized.current) {
        hasInitialized.current = true;
      }
    } else if (status === "unauthenticated") {
      // Only clear tokens if a logout is explicitly in progress.
      // Don't clear during normal page loads or brief unauthenticated flickers,
      // as the login page saves tokens to localStorage before signIn completes.
      const loggingOut = localStorage.getItem("isLoggingOut") === "true";
      if (loggingOut) {
        localStorage.removeItem("accessToken");
        localStorage.removeItem("refreshToken");
        // Logout is complete - clear the flag so API calls aren't blocked on public pages
        localStorage.removeItem("isLoggingOut");
      }
      hasInitialized.current = false;
    }
  }, [session, status]);

  return null;
}

export function SessionProvider({ children }: { children: React.ReactNode }) {
  return (
    <NextAuthSessionProvider>
      <TokenSync />
      <CrossTabLogoutListener />
      <HeaderProvider>
        {children}
      </HeaderProvider>
    </NextAuthSessionProvider>
  );
}
