import { Navigate, Outlet, useLocation } from 'react-router-dom'
import { useAuth } from './AuthProvider'

export function RequireAuth() {
  const { isAuthenticated, roles, selectedRole } = useAuth()
  const location = useLocation()

  if (!isAuthenticated) {
    return <Navigate to="/login" replace state={{ from: location.pathname }} />
  }

  const needsRoleSelection = roles.length > 1 && !selectedRole
  if (needsRoleSelection && location.pathname !== '/app/select-role') {
    return <Navigate to="/app/select-role" replace state={{ from: location.pathname }} />
  }

  return <Outlet />
}
