import { Navigate, Outlet, useLocation } from 'react-router-dom'
import { RouteLoader } from '@meshkee/dashboard-ui'
import { useAuth } from '../context/AuthContext'
import { loginPathWithRedirect } from '../lib/redirect'

export function ProtectedRoute() {
  const { user, isLoading } = useAuth()
  const location = useLocation()

  if (isLoading) {
    return <RouteLoader />
  }

  if (!user) {
    const returnTo = `${location.pathname}${location.search}${location.hash}`
    return <Navigate to={loginPathWithRedirect(returnTo)} replace />
  }

  return <Outlet />
}
