'use client';

import { useAuthStore } from '@/lib/auth-store';
import { useRouter } from 'next/navigation';
import { ReactNode, useEffect } from 'react';

interface AuthGuardProps {
    children: ReactNode;
    requireAuth?: boolean;
}

export function AuthGuard({ children, requireAuth = false }: AuthGuardProps) {
    const { token, checkTokenExpiration, isLoading } = useAuthStore();
    const router = useRouter();

    useEffect(() => {
        if (!isLoading && requireAuth) {
            const isAuthenticated = token && checkTokenExpiration();

            if (!isAuthenticated) {
                router.push('/login');
            }
        }
    }, [token, isLoading, requireAuth, router, checkTokenExpiration]);

    // Show loading state while checking auth
    if (isLoading) {
        return (
            <div className="flex items-center justify-center min-h-screen">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-teal-600"></div>
            </div>
        );
    }

    // If auth is required and user is not authenticated, show nothing (will redirect)
    if (requireAuth && (!token || !checkTokenExpiration())) {
        return null;
    }

    return <>{children}</>;
}
