import { useAuth } from '@/context/AuthContext'; import React, { useEffect } from 'react'; import { useLocation, useNavigate } from "react-router" export default function AuthGuard({ children }: { children: React.ReactNode }) { const { isAuthenticated } = useAuth(); const navigate = useNavigate(); const location = useLocation(); const publicRoutes = ['/login', '/register']; const isPublic = publicRoutes.includes(location.pathname); useEffect(() => { // Handle redirects based on auth state if (isAuthenticated && isPublic) { // Redirect authenticated users away from public pages navigate('/', { replace: true }); } else if (!isAuthenticated && !isPublic) { // Redirect unauthenticated users trying to access protected pages navigate('/login', { replace: true }); } }, [isAuthenticated, location.pathname, isPublic, navigate]); // Render children for all routes - redirects will happen via useEffect return <>{children}; }