"use client";

import { useRouter } from "next/navigation";
import { useEffect, ReactNode } from "react";
import { useUser } from "./";
import Loading from "@/app/loading";

interface AuthGuardProps {
  children: ReactNode;
}

const AuthGuard = ({ children }: AuthGuardProps): React.ReactNode => {
  const { isAuthenticated, isLoading } = useUser();
  const router = useRouter();

  useEffect(() => {
    if (!isLoading && !isAuthenticated) {
      router.push("/auth/sign-in");
    }
  }, [isLoading, isAuthenticated, router]);

  if (isLoading || !isAuthenticated) {
    return <Loading />;
  }

  return children;
};

export default AuthGuard;
