'use client';

import { useEffect, useState } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { isAuthenticated } from '@/lib/auth';

export default function AuthGuard({ children }: { children: React.ReactNode }) {
    const router = useRouter();
    const pathname = usePathname();
    const [authorized, setAuthorized] = useState(false);

    useEffect(() => {
        const checkAuth = () => {
            const isAuth = isAuthenticated();

            if (!isAuth) {
                setAuthorized(false);
                // Evitar redirect loop se já estiver no login
                if (pathname !== '/login') {
                    router.push('/login');
                }
            } else {
                setAuthorized(true);
            }
        };

        checkAuth();

        const handleStorageChange = (e: StorageEvent) => {
            if (e.key === 'token' || e.key === 'user') {
                checkAuth();
            }
        };

        window.addEventListener('storage', handleStorageChange);
        return () => window.removeEventListener('storage', handleStorageChange);
    }, [router, pathname]);

    if (!authorized) {
        return null;
    }

    return <>{children}</>;
}
