import { Navigate } from 'react-router-dom'
import { useAuth } from './auth-context'
import type { PropsWithChildren } from 'react'
import { useEffect, useState } from 'react'

export default function ProtectedRoute({ children }: PropsWithChildren) {
  const { isAuthed, ensureFreshToken, logout } = useAuth()
  const [ready, setReady] = useState(false)

  useEffect(() => {
    let active = true
    ;(async () => {
      if (!isAuthed) {
        if (active) setReady(true)
        return
      }
      try {
        await ensureFreshToken()
      } catch {
        await logout()
      } finally {
        if (active) setReady(true)
      }
    })()

    return () => {
      active = false
    }
  }, [isAuthed, ensureFreshToken, logout])

  if (!ready) return null
  if (!isAuthed) return <Navigate to="/login" replace />
  return <>{children}</>
}
