'use client'

import { useEffect, useState, useRef, useCallback } from 'react'
import { usePathname, useSearchParams } from 'next/navigation'

export function NavigationProgress() {
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const [progress, setProgress] = useState(0)
  const [visible, setVisible] = useState(false)
  const timerRef = useRef<ReturnType<typeof setInterval> | null>(null)
  const hideTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)

  const clearTimers = useCallback(() => {
    if (timerRef.current) clearInterval(timerRef.current)
    if (hideTimerRef.current) clearTimeout(hideTimerRef.current)
  }, [])

  const startProgress = useCallback(() => {
    clearTimers()
    setVisible(true)
    setProgress(10)

    timerRef.current = setInterval(() => {
      setProgress((prev) => {
        if (prev >= 90) return prev
        const increment = prev < 40 ? 14 : prev < 70 ? 7 : 3
        return Math.min(prev + increment, 90)
      })
    }, 100)
  }, [clearTimers])

  const completeProgress = useCallback(() => {
    clearTimers()
    setProgress(100)
    hideTimerRef.current = setTimeout(() => {
      setVisible(false)
      setProgress(0)
    }, 400)
  }, [clearTimers])

  useEffect(() => {
    completeProgress()
  }, [pathname, searchParams, completeProgress])

  useEffect(() => {
    const handleClick = (e: MouseEvent) => {
      const anchor = (e.target as HTMLElement).closest('a')
      if (!anchor?.href) return
      if (anchor.target === '_blank' || anchor.hasAttribute('download')) return

      try {
        const url = new URL(anchor.href)
        if (url.origin !== window.location.origin) return

        const isSamePage =
          url.pathname === pathname &&
          url.search === (searchParams.toString() ? `?${searchParams.toString()}` : '')

        if (!isSamePage) startProgress()
      } catch {
        // ignore invalid URLs
      }
    }

    document.addEventListener('click', handleClick, true)
    return () => document.removeEventListener('click', handleClick, true)
  }, [pathname, searchParams, startProgress])

  useEffect(() => () => clearTimers(), [clearTimers])

  if (!visible && progress === 0) return null

  return (
    <div
      className="fixed top-0 left-0 right-0 z-[100] pointer-events-none"
      role="progressbar"
      aria-valuenow={progress}
      aria-valuemin={0}
      aria-valuemax={100}
      aria-label="Page loading"
    >
      {/* Track */}
      <div className="h-1.5 w-full bg-primary/15" />

      {/* Progress fill */}
      <div
        className="absolute top-0 left-0 h-1.5 rounded-r-full transition-[width] duration-150 ease-out"
        style={{
          width: `${progress}%`,
          background: 'linear-gradient(90deg, #9B1B30 0%, #C41E3A 45%, #E85D4C 100%)',
          boxShadow: '0 0 12px rgba(196, 30, 58, 0.75), 0 2px 8px rgba(155, 27, 48, 0.45)',
        }}
      />

      {/* Leading glow tip */}
      <div
        className="absolute top-0 h-1.5 w-16 rounded-full opacity-90"
        style={{
          left: `calc(${progress}% - 2rem)`,
          background: 'radial-gradient(circle, rgba(255,255,255,0.95) 0%, rgba(232, 93, 76, 0.8) 40%, transparent 70%)',
          filter: 'blur(1px)',
        }}
      />
    </div>
  )
}
