import { Navigate, useLocation } from "react-router-dom";
import { useSessionContext } from "../lib/useSession.ts";
import LoadingFallback from "../LoadingFallback.tsx";

interface ProtectedRouteProps {
  children: React.ReactNode;
}

/**
 * Protected route wrapper - redirects to /login if not authenticated
 */
export function ProtectedRoute({ children }: ProtectedRouteProps) {
  const { session, isLoading } = useSessionContext();
  const location = useLocation();

  if (isLoading) {
    return <LoadingFallback />;
  }

  if (!session?.authenticated) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  return <>{children}</>;
}
