"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, token, hydrated } = useAuthStore(); const router = useRouter(); const pathname = usePathname(); // 1️⃣ Run initialization once useEffect(() => { initializeAuth(); }, [initializeAuth]); // 2️⃣ Run routing logic only after hydration useEffect(() => { if (!hydrated) return; const publicPages = ["/", "/login", "/register"]; if (token) { if (publicPages.includes(pathname)) { router.replace("/home"); } } else { if (!publicPages.includes(pathname)) { router.replace("/login"); } } }, [pathname, token, hydrated, router]); // 3️⃣ Show loading until hydrated if (!hydrated) { return (

Loading...

); } return <>{children}; }