"use client";

import { useEffect } from "react";
import { useAuthStore } from "@/stores/authStore";
import { useRouter, usePathname } from "next/navigation";

export default function AuthInitializer({
  children,
}: {
  children: React.ReactNode;
}) {
  const { initializeAuth, isLoading, token } = useAuthStore();
  const router = useRouter();
  const pathname = usePathname();

  useEffect(() => {
    const run = async () => {
      await initializeAuth();

      // Routing logic based on auth state
      const publicPages = ["/", "/login", "/register"];

      if (token) {
        if (publicPages.includes(pathname)) {
          router.replace("/home");
        }
      } else {
        if (!publicPages.includes(pathname)) {
          router.replace("/");
        }
      }
    };

    run();
  }, [pathname, token, initializeAuth, router]);

  if (isLoading) return <p>Loading...</p>;

  return <>{children}</>;
}
