import { useEffect, useState } from 'react';
import { Navigate, useLocation } from 'react-router-dom';

/**
 * ProtectedRoute component that checks for authentication token.
 * Redirects to login if not authenticated.
 */
interface ProtectedRouteProps {
  children: React.ReactNode;
}

export default function ProtectedRoute({ children }: ProtectedRouteProps) {
  const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null);
  const location = useLocation();

  useEffect(() => {
    // Check for JWT token in localStorage
    const token = localStorage.getItem('auth-storage');
    if (token) {
      try {
        const authData = JSON.parse(token);
        setIsAuthenticated(!!authData?.state?.token);
      } catch {
        setIsAuthenticated(false);
      }
    } else {
      setIsAuthenticated(false);
    }
  }, []);

  if (isAuthenticated === null) {
    // Still checking authentication
    return <div>Checking authentication...</div>;
  }

  if (!isAuthenticated) {
    // Redirect to login (or main app login page)
    // In production, this might redirect to app.igny8.com/login
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  return <>{children}</>;
}

