"use client";

import { useEffect } from "react";
import { usePathname, useRouter } from "next/navigation";
import { useAuthStore } from "@/features/auth/stores/auth.store";

export function AccountRouteGuard() {
  const router = useRouter();
  const pathname = usePathname();
  const isAuthenticated = useAuthStore(state => state.isAuthenticated);
  const hasCheckedAuth = useAuthStore(state => state.hasCheckedAuth);
  const loading = useAuthStore(state => state.loading);
  const checkAuth = useAuthStore(state => state.checkAuth);

  useEffect(() => {
    if (!hasCheckedAuth) {
      void checkAuth();
    }
  }, [checkAuth, hasCheckedAuth]);

  useEffect(() => {
    if (!hasCheckedAuth || loading || isAuthenticated) {
      return;
    }

    const destination = pathname || "/account";
    router.replace(`/auth/login?redirect=${encodeURIComponent(destination)}`);
  }, [hasCheckedAuth, isAuthenticated, loading, pathname, router]);

  return null;
}
