"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { hydrateAuth, fetchProfile } from "@/store/slices/authSlice";

export default function AuthGuard({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const { isAuthenticated } = useAppSelector((state) => state.auth);
  const [isReady, setIsReady] = useState<boolean>(false);

  useEffect(() => {
    const checkAuth = async () => {
      const token = localStorage.getItem("token") || sessionStorage.getItem("token");

      if (!token) {
        router.replace("/login");
        return;
      }
      if (!isAuthenticated) {
        const storedUser = localStorage.getItem("user") || sessionStorage.getItem("user");
        if (storedUser) {
          try {
            const user = JSON.parse(storedUser);
            dispatch(hydrateAuth({ user }));
          } catch (e) {
            console.error("Failed to parse user from local storage");
          }
        }
        dispatch(fetchProfile());
      }

      setIsReady(true);
    };

    checkAuth();
  }, [router, dispatch, isAuthenticated]);


  if (!isReady && !isAuthenticated) {
    return null;
  }

  return <>{children}</>;
}
