"use client";

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

import {
  selectAuthIsLoading,
  useAuthSelector,
} from "@/stores/auth/auth-context";

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

export function AppNavigationGuard() {
  const authState = useAuthSelector(
    (state) => ({
      hasInitialized: state.context.hasInitialized,
      isLoading: selectAuthIsLoading(state),
      loginStatus: state.context.loginStatus,
    }),
    shallowEqual,
  );
  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;
}
