import { useEffect, useState } from 'react'
import { Link, useLocation } from 'react-router-dom'
import './Navigation.css'

export default function Navigation() {
  const [scrolled, setScrolled] = useState(false)
  const [mobileOpen, setMobileOpen] = useState(false)
  const location = useLocation()

  useEffect(() => {
    const handleScroll = () => setScrolled(window.scrollY > 50)
    window.addEventListener('scroll', handleScroll)
    return () => window.removeEventListener('scroll', handleScroll)
  }, [])

  useEffect(() => {
    function handleKeyDown(event) {
      if (event.key === 'Escape') setMobileOpen(false)
    }

    document.addEventListener('keydown', handleKeyDown)
    return () => document.removeEventListener('keydown', handleKeyDown)
  }, [])

  function closeMenu() {
    setMobileOpen(false)
  }

  const navLinks = [
    { to: '/artikel', label: 'Artikel' },
    { to: '/kniepunkt', label: 'Kniepunkt' },
    { to: '/podcast', label: 'Podcast' },
    { to: '/speaking', label: 'Speaking' },
    { to: '/consulting', label: 'Beratung' },
    { to: '/ueber-mich', label: 'Über mich' },
    { to: '/kontakt', label: 'Kontakt' },
  ]

  const isActive = (path) => location.pathname === path || location.pathname.startsWith(`${path}/`)

  return (
    <nav className={`navigation ${scrolled ? 'scrolled' : ''}`} aria-label="Hauptnavigation">
      <div className="nav-container app-container">
        <Link to="/" className="logo" onClick={closeMenu}>
          <span className="logo-text">Dr. André Knie</span>
        </Link>

        <div className="nav-links">
          {navLinks.map(link => (
            <Link
              key={link.to}
              to={link.to}
              className={`nav-link ${isActive(link.to) ? 'active' : ''}`}
              aria-current={isActive(link.to) ? 'page' : undefined}
            >
              {link.label}
            </Link>
          ))}
        </div>

        <button
          className={`hamburger ${mobileOpen ? 'active' : ''}`}
          onClick={() => setMobileOpen(open => !open)}
          aria-label={mobileOpen ? 'Menü schließen' : 'Menü öffnen'}
          aria-expanded={mobileOpen}
          aria-controls="mobile-navigation"
          type="button"
        >
          <span></span>
          <span></span>
          <span></span>
        </button>
      </div>

      <div id="mobile-navigation" className={`nav-mobile ${mobileOpen ? 'open' : ''}`} hidden={!mobileOpen}>
        {navLinks.map(link => (
          <Link
            key={link.to}
            to={link.to}
            className={`nav-mobile-link ${isActive(link.to) ? 'active' : ''}`}
            onClick={closeMenu}
            aria-current={isActive(link.to) ? 'page' : undefined}
          >
            {link.label}
          </Link>
        ))}
      </div>
    </nav>
  )
}
