import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router';
import { jwtexp } from '@/lib/utils';

export default function RootRedirect() {
    const navigate = useNavigate();
    const [checking, setChecking] = useState(true);

    useEffect(() => {
        const checkAuthAndRedirect = async () => {
            try {
                const token = localStorage.getItem('access_token');

                if (token) {
                    const isTokenValid = await jwtexp(token);

                    if (isTokenValid) {
                        navigate('/dashboard', { replace: true });
                    } else {
                        console.error('Token is invalid, redirecting...');
                        navigate('/auth/login', { replace: true });
                    }
                } else {
                    console.error('No token found, redirecting...');
                    navigate('/auth/login', { replace: true });
                }
            } catch (error) {
                console.error('Error checking auth:', error);
                navigate('/auth/login', { replace: true });
            } finally {
                setChecking(false);
            }
        };

        checkAuthAndRedirect();
    }, [navigate]);

    if (checking) {
        return (
            <div className="flex items-center justify-center min-h-screen">
                <p className="text-xl">Checking authentication...</p>
            </div>
        );
    }

    return null;
}

