import { useEffect, useState } from "react"
import { Navigate, useLocation } from "react-router-dom"
import { AUTH_EVENT, isAuthed } from "@/api/token"

export default function AuthGuard({ children }: { children: React.ReactNode }) {
  const location = useLocation()
  const [isValid, setIsValid] = useState(isAuthed)

  useEffect(() => {
    const update = () => setIsValid(isAuthed())
    window.addEventListener(AUTH_EVENT, update)
    return () => window.removeEventListener(AUTH_EVENT, update)
  }, [])

  if (!isValid) {
    return (
      <Navigate
        to={`/login?redirect=${encodeURIComponent(location.pathname)}`}
        replace
      />
    )
  }

  return <>{children}</>
}
