import { useState, useEffect } from 'react'
import { parseRoute, type Route } from './routes.ts'

export function useRoute(): Route {
  const [route, setRoute] = useState<Route>(() => parseRoute())

  useEffect(() => {
    function onPopState() {
      setRoute(parseRoute())
    }
    window.addEventListener('popstate', onPopState)
    return () => window.removeEventListener('popstate', onPopState)
  }, [])

  return route
}

/** Navigate without page reload */
export function navigate(path: string) {
  window.history.pushState(null, '', path)
  window.dispatchEvent(new PopStateEvent('popstate'))
}
