'use client'

import { useEffect, useState } from 'react'
import Image from 'next/image'
import { Menu, X } from 'lucide-react'
import { motion, AnimatePresence } from 'framer-motion'
import { useTranslations } from 'next-intl'
import { Link, usePathname, useRouter } from '@/i18n/navigation'
import { locales } from '@/i18n/config'

// Pages that have dedicated routes vs. homepage anchor sections
const ROUTE_LINKS: Record<string, string> = {
  services: '/services',
  work: '/work',
  about: '/about',
}

const ANCHOR_LINKS: Record<string, string> = {
  services: '#services',
  configure: '#configure',
  process: '#process',
  work: '#work',
  about: '#about',
}

const NAV_KEYS = ['services', 'configure', 'process', 'work', 'about'] as const
type NavKey = (typeof NAV_KEYS)[number]

function useScrolled(threshold = 100) {
  const [scrolled, setScrolled] = useState(false)

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > threshold)
    // check immediately in case page is already scrolled
    onScroll()
    window.addEventListener('scroll', onScroll, { passive: true })
    return () => window.removeEventListener('scroll', onScroll)
  }, [threshold])

  return scrolled
}

interface NavLinkProps {
  navKey: NavKey
  label: string
  isHomePage: boolean
  onClick?: () => void
  mobile?: boolean
}

function NavLink({ navKey, label, isHomePage, onClick, mobile }: NavLinkProps) {
  const pathname = usePathname()
  const isActive = pathname === ROUTE_LINKS[navKey]

  const sharedStyle = mobile
    ? 'block w-full text-left text-2xl font-serif text-on-surface py-3'
    : 'label-md text-on-surface/70 hover:text-on-surface transition-colors duration-200 relative group'

  // On homepage, use anchor links for smooth scrolling
  if (isHomePage || !ROUTE_LINKS[navKey]) {
    return (
      <a
        href={ANCHOR_LINKS[navKey]}
        className={sharedStyle}
        onClick={onClick}
      >
        {label}
        {!mobile && (
          <span
            className="absolute -bottom-1 left-0 h-px bg-primary transition-all duration-300 w-0 group-hover:w-full"
            aria-hidden="true"
          />
        )}
      </a>
    )
  }

  // On other pages, use the actual route
  return (
    <Link
      href={ROUTE_LINKS[navKey] as any}
      className={`${sharedStyle} ${isActive ? 'text-primary' : ''}`}
      onClick={onClick}
    >
      {label}
      {!mobile && (
        <span
          className={`absolute -bottom-1 left-0 h-px bg-primary transition-all duration-300 ${
            isActive ? 'w-full' : 'w-0 group-hover:w-full'
          }`}
          aria-hidden="true"
        />
      )}
    </Link>
  )
}

export default function Nav() {
  const t = useTranslations('nav')
  const pathname = usePathname()
  const router = useRouter()
  const scrolled = useScrolled(10)
  const [mobileOpen, setMobileOpen] = useState(false)

  // Derive current locale from pathname (next-intl with localePrefix: 'as-needed')
  // The pathname from usePathname() is always locale-stripped for the default locale.
  // We can detect the locale from the URL directly.
  const [currentLocale, setCurrentLocale] = useState<string>('en')

  useEffect(() => {
    // Read locale from <html lang> attribute set by the layout
    const htmlLang = document.documentElement.lang
    if (locales.includes(htmlLang as any)) {
      setCurrentLocale(htmlLang)
    }
  }, [pathname])

  const [localeMenuOpen, setLocaleMenuOpen] = useState(false)

  const LOCALE_DISPLAY: Record<string, { flag: string; label: string; short: string }> = {
    en: { flag: '🇬🇧', label: 'English', short: 'EN' },
    fr: { flag: '🇫🇷', label: 'Français', short: 'FR' },
    it: { flag: '🇮🇹', label: 'Italiano', short: 'IT' },
    es: { flag: '🇪🇸', label: 'Español', short: 'ES' },
  }

  const isHomePage = pathname === '/'

  function handleLocaleSwitch(targetLocale: string) {
    router.replace(pathname as any, { locale: targetLocale as any })
    setLocaleMenuOpen(false)
  }

  // Prevent body scroll when mobile menu is open
  useEffect(() => {
    document.body.style.overflow = mobileOpen ? 'hidden' : ''
    return () => {
      document.body.style.overflow = ''
    }
  }, [mobileOpen])

  return (
    <>
      {/* ── Fixed navbar ── */}
      <motion.header
        className="fixed top-0 left-0 right-0 z-50"
        initial={false}
        animate={scrolled ? 'glass' : 'transparent'}
        variants={{
          transparent: {
            backgroundColor: 'rgba(255,255,255,0)',
            backdropFilter: 'blur(0px)',
            boxShadow: '0 0px 0px rgba(25,28,29,0)',
          } as any,
          glass: {
            backgroundColor: 'rgba(255,255,255,0.82)',
            backdropFilter: 'blur(20px)',
            boxShadow: '0 20px 40px rgba(25,28,29,0.06)',
          } as any,
        }}
        transition={{ duration: 0.35, ease: [0.25, 0.46, 0.45, 0.94] }}
        role="banner"
      >
        <nav
          className="mx-auto max-w-7xl px-6 lg:px-8 h-[72px] flex items-center justify-between gap-8"
          aria-label="Main navigation"
        >
          {/* ── Logo ── */}
          <Link href="/" aria-label="LetsBe. — Back to homepage" className="shrink-0">
            <Image
              src="/images/letsbe-logo-short.png"
              alt="LetsBe."
              width={168}
              height={56}
              className="h-14 w-auto object-contain"
              priority
            />
          </Link>

          {/* ── Desktop nav links (center) ── */}
          <ul className="hidden lg:flex items-center gap-8 xl:gap-10" role="list">
            {NAV_KEYS.map((key) => (
              <li key={key}>
                <NavLink
                  navKey={key}
                  label={t(key)}
                  isHomePage={isHomePage}
                />
              </li>
            ))}
          </ul>

          {/* ── Desktop right controls ── */}
          <div className="hidden lg:flex items-center gap-4 shrink-0">
            {/* Language dropdown */}
            <div className="relative">
              <button
                onClick={() => setLocaleMenuOpen((prev) => !prev)}
                className="label-md text-on-surface/60 hover:text-on-surface transition-colors duration-200 px-2 py-1 rounded focus-visible:outline-2 focus-visible:outline-primary focus-visible:outline-offset-2"
                aria-label="Switch language"
                aria-expanded={localeMenuOpen}
                aria-haspopup="listbox"
              >
                {LOCALE_DISPLAY[currentLocale]?.short ?? currentLocale.toUpperCase()}
              </button>

              {/* Transparent overlay to close on outside click */}
              {localeMenuOpen && (
                <div
                  className="fixed inset-0 z-[40]"
                  aria-hidden="true"
                  onClick={() => setLocaleMenuOpen(false)}
                />
              )}

              <AnimatePresence>
                {localeMenuOpen && (
                  <motion.ul
                    role="listbox"
                    aria-label="Select language"
                    className="absolute right-0 top-full mt-2 z-[41] bg-surface-high rounded-xl shadow-lg border border-outline-variant/20 overflow-hidden min-w-[140px]"
                    initial={{ opacity: 0, y: -6, scale: 0.97 }}
                    animate={{ opacity: 1, y: 0, scale: 1 }}
                    exit={{ opacity: 0, y: -6, scale: 0.97 }}
                    transition={{ duration: 0.18, ease: [0.25, 0.46, 0.45, 0.94] }}
                  >
                    {locales
                      .filter((l) => l !== currentLocale)
                      .map((l) => {
                        const display = LOCALE_DISPLAY[l]
                        return (
                          <li key={l} role="option" aria-selected={false}>
                            <button
                              onClick={() => handleLocaleSwitch(l)}
                              className="w-full flex items-center gap-2.5 px-4 py-2.5 label-md text-on-surface/70 hover:text-on-surface hover:bg-surface-low transition-colors duration-150 text-left"
                            >
                              <span aria-hidden="true">{display?.flag}</span>
                              <span>{display?.label}</span>
                            </button>
                          </li>
                        )
                      })}
                  </motion.ul>
                )}
              </AnimatePresence>
            </div>

            {/* Start a Project CTA */}
            <a
              href="#configure"
              className="inline-flex items-center gap-2 px-5 py-2.5 rounded-full text-white label-md whitespace-nowrap transition-all duration-300 hover:scale-[1.03] hover:shadow-lg focus-visible:outline-2 focus-visible:outline-primary focus-visible:outline-offset-2"
              style={{
                background: 'linear-gradient(135deg, #006494, #5BA4D9)',
              }}
            >
              {t('startProject')}
            </a>
          </div>

          {/* ── Mobile hamburger ── */}
          <button
            className="lg:hidden p-2 -mr-2 text-on-surface focus-visible:outline-2 focus-visible:outline-primary focus-visible:outline-offset-2 rounded"
            onClick={() => { setMobileOpen(true); setLocaleMenuOpen(false) }}
            aria-label="Open navigation menu"
            aria-expanded={mobileOpen}
            aria-controls="mobile-menu"
          >
            <Menu size={24} strokeWidth={1.5} />
          </button>
        </nav>
      </motion.header>

      {/* ── Mobile menu overlay + panel ── */}
      <AnimatePresence>
        {mobileOpen && (
          <>
            {/* Backdrop */}
            <motion.div
              key="backdrop"
              className="fixed inset-0 z-[60] bg-on-surface/30"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.25 }}
              onClick={() => setMobileOpen(false)}
              aria-hidden="true"
            />

            {/* Slide-in panel */}
            <motion.div
              key="panel"
              id="mobile-menu"
              role="dialog"
              aria-modal="true"
              aria-label="Navigation menu"
              className="fixed top-0 right-0 bottom-0 z-[70] w-[min(320px,85vw)] bg-surface-high flex flex-col"
              initial={{ x: '100%' }}
              animate={{ x: 0 }}
              exit={{ x: '100%' }}
              transition={{ duration: 0.35, ease: [0.25, 0.46, 0.45, 0.94] }}
            >
              {/* Panel header */}
              <div className="flex items-center justify-between px-6 py-5">
                <Link
                  href="/"
                  onClick={() => setMobileOpen(false)}
                  aria-label="LetsBe. — Back to homepage"
                >
                  <Image
                    src="/images/letsbe-logo-short.png"
                    alt="LetsBe."
                    width={132}
                    height={44}
                    className="h-11 w-auto object-contain"
                  />
                </Link>
                <button
                  onClick={() => setMobileOpen(false)}
                  className="p-2 -mr-2 text-on-surface/60 hover:text-on-surface transition-colors rounded focus-visible:outline-2 focus-visible:outline-primary focus-visible:outline-offset-2"
                  aria-label="Close navigation menu"
                >
                  <X size={22} strokeWidth={1.5} />
                </button>
              </div>

              {/* Tonal divider */}
              <div className="h-px mx-6 bg-surface-low" aria-hidden="true" />

              {/* Nav links */}
              <nav className="flex-1 px-6 py-8 overflow-y-auto" aria-label="Mobile navigation">
                <ul className="flex flex-col" role="list">
                  {NAV_KEYS.map((key, i) => (
                    <motion.li
                      key={key}
                      initial={{ opacity: 0, x: 20 }}
                      animate={{ opacity: 1, x: 0 }}
                      transition={{ delay: 0.05 + i * 0.06, duration: 0.3 }}
                    >
                      <NavLink
                        navKey={key}
                        label={t(key)}
                        isHomePage={isHomePage}
                        onClick={() => setMobileOpen(false)}
                        mobile
                      />
                      {i < NAV_KEYS.length - 1 && (
                        <div className="h-px bg-surface-low my-1" aria-hidden="true" />
                      )}
                    </motion.li>
                  ))}
                </ul>
              </nav>

              {/* Bottom controls */}
              <div className="px-6 pb-8 pt-4 flex flex-col gap-3">
                {/* Language options */}
                <div className="flex flex-col gap-1">
                  {locales
                    .filter((l) => l !== currentLocale)
                    .map((l) => {
                      const display = LOCALE_DISPLAY[l]
                      return (
                        <button
                          key={l}
                          onClick={() => {
                            handleLocaleSwitch(l)
                            setMobileOpen(false)
                          }}
                          className="w-full py-2.5 label-md text-on-surface/60 hover:text-on-surface transition-colors duration-200 text-left focus-visible:outline-2 focus-visible:outline-primary focus-visible:outline-offset-2 rounded flex items-center gap-2.5"
                        >
                          <span aria-hidden="true">{display?.flag}</span>
                          <span>{display?.label}</span>
                        </button>
                      )
                    })}
                </div>

                {/* CTA */}
                <a
                  href="#configure"
                  onClick={() => setMobileOpen(false)}
                  className="w-full inline-flex items-center justify-center py-3.5 rounded-full text-white label-md transition-all duration-200 active:scale-95 focus-visible:outline-2 focus-visible:outline-primary focus-visible:outline-offset-2"
                  style={{
                    background: 'linear-gradient(135deg, #006494, #5BA4D9)',
                  }}
                >
                  {t('startProject')}
                </a>
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </>
  )
}
