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

function safeRedirectPath(value: string | null) {
  if (!value || !value.startsWith('/') || value.startsWith('//')) {
    return '/'
  }
  return value
}

export function GuestRoute() {
  const { user, isLoading } = useAuth()
  const location = useLocation()
  const redirectTo = safeRedirectPath(new URLSearchParams(location.search).get('redirect'))

  if (isLoading) {
    return <RouteLoader />
  }

  if (user) {
    return <Navigate to={redirectTo} replace />
  }

  return <Outlet />
}
