/**
 * useRouter — React hook wrapping the vanilla Router.
 *
 * Creates a Router instance, starts it, and exposes the current pathname as
 * reactive state.  The Router's `on('navigate', ...)` subscription API is
 * used to track path changes; useSyncExternalStore is not used here because
 * `Router.on()` is not compatible with the snapshot/subscribe pattern —
 * snapshot reads are sync but `navigate()` is async.
 *
 * Cleanup: calls `router.destroy()` on unmount.
 */
import { useState, useEffect, useMemo, useCallback } from 'react'
import { Router } from '../../services/router'
import type { RouterConfig } from '../../services/router'

export type { RouterConfig }

export interface UseRouterResult {
  /** The underlying Router instance. */
  router: Router
  /** Current pathname, updated on each navigation event. */
  pathname: string
  /** Stable navigate function bound to the router instance. */
  navigate: (path: string) => void
}

/**
 * @param config - Optional RouterConfig forwarded to the Router constructor.
 *   Pass a stable reference to avoid teardown / re-creation on every render.
 */
export function useRouter(config?: RouterConfig): UseRouterResult {
  const router = useMemo(() => new Router(config), [config])

  const [pathname, setPathname] = useState<string>(() => {
    if (typeof window !== 'undefined') return window.location.pathname
    return '/'
  })

  useEffect(() => {
    router.start()

    const unsub = router.on('navigate', event => {
      setPathname(event.path)
    })

    return () => {
      unsub()
      router.destroy()
    }
  }, [router])

  const navigate = useCallback(
    (path: string) => {
      void router.navigate(path)
    },
    [router]
  )

  return { router, pathname, navigate }
}
