'use client';

import { useAuthStore } from '@/lib/auth-store';
import { useLanguage } from '@/lib/language-context';
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';

interface AuthGuardProps {
    children: React.ReactNode;
}

export default function AuthGuard({ children }: AuthGuardProps) {
    const router = useRouter();
    const { t } = useLanguage();
    const { token, isLoading, checkTokenExpiration } = useAuthStore();
    const [isChecking, setIsChecking] = useState(true);

    useEffect(() => {
        // Check authentication status
        const checkAuth = () => {
            if (!isLoading) {
                if (!token || !checkTokenExpiration()) {
                    // Not authenticated or token expired, redirect to login
                    router.push('/login');
                } else {
                    // Authenticated and token valid
                    setIsChecking(false);
                }
            }
        };

        checkAuth();
    }, [token, isLoading, checkTokenExpiration, router]);

    // Show loading state while checking authentication
    if (isLoading || isChecking) {
        return (
            <div className="flex items-center justify-center min-h-screen">
                <div className="text-center">
                    <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
                    <p className="mt-4 text-gray-600">{t('common.loading')}</p>
                </div>
            </div>
        );
    }

    // Render children if authenticated
    return <>{children}</>;
}
