"use client";

import { useEffect } from "react";
import { usePathname, useRouter } from "next/navigation";

import { useAuthState } from "@/stores/auth/auth-context";

import { resolveRouteGuardRedirect } from "./navigation-resolver";

export function AppNavigationGuard() {
  const authState = useAuthState();
  const pathname = usePathname();
  const router = useRouter();

  useEffect(() => {
    if (!authState.hasInitialized || authState.isLoading) return;

    const redirectTo = resolveRouteGuardRedirect({
      loginStatus: authState.loginStatus,
      pathname,
      searchParams: window.location.search.replace(/^\?/, ""),
    });
    if (redirectTo) router.replace(redirectTo);
  }, [
    authState.hasInitialized,
    authState.isLoading,
    authState.loginStatus,
    pathname,
    router,
  ]);

  return null;
}
