import { useNavigate } from 'react-router-dom'
import { useEffect } from 'react'
import { SPA_ROUTES, POST_ID_TO_SLUG } from '../config'

export function useNavFix(ref) {
  const navigate = useNavigate()

  useEffect(() => {
    const el = ref.current
    if (!el) return

    const handler = (e) => {
      const link = e.target.closest('a[href]')
      if (!link) return

      let href = link.getAttribute('href')
      if (!href || href.startsWith('#')) return

      // External links (http/https) — open in new tab if different host
      if (href.startsWith('http')) {
        try {
          const url = new URL(href)
          if (url.hostname !== window.location.hostname) {
            e.preventDefault()
            window.open(href, '_blank', 'noopener,noreferrer')
          }
        } catch (_) { console.warn('useNavFix: failed to parse URL:', href) }
        return
      }

      // Prevent default for ALL same-site links to use SPA routing
      e.preventDefault()

      // Normalize: remove leading /, handle relative paths
      let route = href.replace(/^\//, '')

      // Handle ?p= service links → SPA route
      const serviceMatch = route.match(/service\?p=(\d+)/)
      if (serviceMatch) {
        const slug = POST_ID_TO_SLUG[serviceMatch[1]]
        if (slug) {
          navigate('/service/' + slug)
        } else {
          navigate('/service')
        }
        return
      }

      // Handle ../ x/index.html relative paths like ../contact/index.html
      route = route.replace(/\.\.\//g, '')

      // Strip .html and index.html
      route = route.replace(/\/?index\.html$/, '').replace(/\.html$/, '')

      // Strip wp- prefix (for wp-content links that aren't really pages)
      if (route.startsWith('wp-')) return

      // If route matches known SPA routes or starts with /service/, navigate
      const normalizedRoute = '/' + route
      if (SPA_ROUTES.includes(normalizedRoute) || normalizedRoute.startsWith('/service/')) {
        navigate(normalizedRoute)
        return
      }

      // Fallback: just navigate to the cleaned route
      navigate(normalizedRoute || '/')
    }

    el.addEventListener('click', handler)
    return () => el.removeEventListener('click', handler)
  }, [ref, navigate])
}
