import { Navigate, Outlet } from 'react-router';
import { useAuth } from './useAuth';

const REQUIRED_ROLE = 'WING_PERMIT';

export function ProtectedRoute() {
  const { user, loading } = useAuth();

  if (loading) {
    return (
      <div className="auth-loading">
        <div className="auth-loading__spinner" />
      </div>
    );
  }

  if (!user) {
    return <Navigate to="/login" replace />;
  }

  if (user.status === 'PENDING') {
    return <Navigate to="/pending" replace />;
  }

  if (user.status === 'REJECTED' || user.status === 'DISABLED') {
    return <Navigate to="/denied" replace />;
  }

  const hasPermit = user.roles.some((r) => r.name === REQUIRED_ROLE);
  if (!hasPermit) {
    return <Navigate to="/denied" replace />;
  }

  return <Outlet />;
}
