'use client'

import { useState, useEffect } from 'react'
import { Link, usePathname, useRouter } from '@/i18n/routing'
import { useTranslations, useLocale } from 'next-intl'
import { Menu, X, Globe, PlusCircle, Heart } from 'lucide-react'
import { Category } from '@prisma/client'

export default function Navbar({ categories = [] }: { categories?: Category[] }) {
  const t = useTranslations('nav')
  const activeLocale = useLocale()
  const pathname = usePathname()
  const router = useRouter()
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false)
  const [langMenuOpen, setLangMenuOpen] = useState(false)
  const [favoritesCount, setFavoritesCount] = useState(0)

  useEffect(() => {
    const updateCount = () => {
      try {
        const stored = localStorage.getItem('savedListingIds')
        if (stored) {
          const ids = JSON.parse(stored) as string[]
          setFavoritesCount(ids.length)
        } else {
          setFavoritesCount(0)
        }
      } catch (e) {
        console.error('Error reading localStorage:', e)
      }
    }

    updateCount()

    window.addEventListener('favorites-updated', updateCount)
    window.addEventListener('storage', updateCount)

    return () => {
      window.removeEventListener('favorites-updated', updateCount)
      window.removeEventListener('storage', updateCount)
    }
  }, [])

  const languages = [
    { code: 'tr', label: 'Türkçe' },
    { code: 'en', label: 'English' },
    { code: 'ru', label: 'Русский' }
  ]

  const getLocalizedName = (obj: any) => {
    if (!obj) return ''
    return activeLocale === 'ru' ? obj.nameRu : activeLocale === 'en' ? obj.nameEn : obj.nameTr
  }

  const categoryItems = categories.map(cat => ({
    name: getLocalizedName(cat),
    href: `/${cat.slug}`
  }))

  const navItems = [
    ...categoryItems,
    { name: t('events'), href: '/events' },
    { name: t('blog'), href: '/blog' },
    { name: t('aiPlanner'), href: '/plan-olustur' },
  ]

  const handleLanguageChange = (localeCode: string) => {
    setLangMenuOpen(false)
    router.replace(pathname, { locale: localeCode })
  }

  return (
    <header className="bg-pine text-stone border-b border-white/10 sticky top-0 z-40">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex items-center justify-between h-20">

          {/* Logo & Wordmark */}
          <Link href="/" className="flex items-center gap-3 group">
            <div className="w-11 h-11 rounded-full border-2 border-stone flex items-center justify-center relative bg-paper shrink-0 shadow-sm transition-transform group-hover:scale-105">
              <div className="absolute inset-[3px] rounded-full border border-dashed border-turquoise" />
              <span className="font-heading font-extrabold text-pine text-sm tracking-tighter">ML</span>
            </div>
            <div className="hidden sm:block">
              <p className="font-heading font-extrabold text-lg text-stone tracking-tight leading-none lowercase">
                marmaris <span className="text-turquoise">local</span>
              </p>
              <p className="text-[10px] font-mono text-stone/75 font-medium tracking-wider mt-0.5 uppercase">
                local knowledge
              </p>
            </div>
          </Link>

          {/* Desktop Navigation */}
          <nav className="hidden lg:flex items-center gap-8">
            {navItems.map((item) => {
              const isActive = pathname === item.href
              return (
                <Link
                  key={item.name}
                  href={item.href}
                  className={`text-sm font-medium transition-colors hover:text-turquoise ${isActive ? 'text-turquoise font-semibold' : 'text-stone/80'
                    }`}
                >
                  {item.name}
                </Link>
              )
            })}
          </nav>

          {/* Action Items */}
          <div className="hidden lg:flex items-center gap-4">
            {/* Saved items trigger - 44px touch target */}
            <Link
              href="/saved"
              className="relative w-11 h-11 rounded-full border border-stone/20 hover:border-turquoise transition text-stone hover:text-turquoise flex items-center justify-center shrink-0"
              title={t('saved')}
              aria-label={t('saved')}
            >
              <Heart className="w-4.5 h-4.5" />
              {favoritesCount > 0 && (
                <span className="absolute -top-1 -right-1 w-4 h-4 rounded-full bg-bougainvillea text-stone text-[8px] font-mono font-bold flex items-center justify-center shadow-sm shrink-0">
                  {favoritesCount}
                </span>
              )}
            </Link>

            {/* Language Selector */}
            <div className="relative">
              <button
                type="button"
                onClick={() => setLangMenuOpen(!langMenuOpen)}
                className="flex items-center gap-1.5 px-3.5 py-2.5 rounded-full border border-stone/20 hover:border-turquoise transition text-xs font-mono min-h-[44px] cursor-pointer"
                aria-label="Select language"
                aria-expanded={langMenuOpen}
                aria-haspopup="true"
              >
                <Globe className="w-4 h-4 text-turquoise" />
                {activeLocale.toUpperCase()}
              </button>

              {langMenuOpen && (
                <>
                  <div className="fixed inset-0 z-10" onClick={() => setLangMenuOpen(false)} />
                  <div className="absolute right-0 mt-2 w-36 rounded-xl bg-paper text-ink shadow-lg ring-1 ring-black/5 z-20 py-1.5 overflow-hidden">
                    {languages.map((lang) => (
                      <button
                        key={lang.code}
                        type="button"
                        onClick={() => handleLanguageChange(lang.code)}
                        className={`w-full text-left px-4 py-2.5 text-xs hover:bg-stone transition flex items-center justify-between min-h-[40px] cursor-pointer ${activeLocale === lang.code ? 'font-bold text-turquoise bg-stone/40' : 'text-ink/80'
                          }`}
                      >
                        {lang.label}
                        <span className="font-mono text-[10px] text-pine/70">{lang.code.toUpperCase()}</span>
                      </button>
                    ))}
                  </div>
                </>
              )}
            </div>

            {/* Add Business Button */}
            <Link
              href="/add-business"
              className="flex items-center gap-1.5 bg-turquoise hover:bg-turquoise/90 text-paper font-medium text-xs py-2.5 px-4 rounded-full transition-transform active:scale-95 shadow-sm min-h-[44px]"
            >
              <PlusCircle className="w-4 h-4" />
              {t('addBusiness')}
            </Link>
          </div>

          {/* Mobile menu button */}
          <div className="flex items-center gap-2 lg:hidden">
            {/* Mobile Saved trigger - 44px touch target */}
            <Link
              href="/saved"
              className="relative w-11 h-11 rounded-full border border-stone/20 text-stone flex items-center justify-center shrink-0"
              title={t('saved')}
              aria-label={t('saved')}
            >
              <Heart className="w-4.5 h-4.5" />
              {favoritesCount > 0 && (
                <span className="absolute -top-1 -right-1 w-4 h-4 rounded-full bg-bougainvillea text-stone text-[8px] font-mono font-bold flex items-center justify-center shadow-sm shrink-0">
                  {favoritesCount}
                </span>
              )}
            </Link>

            {/* Lang menu for mobile - 44px touch target */}
            <div className="relative">
              <button
                type="button"
                onClick={() => setLangMenuOpen(!langMenuOpen)}
                className="flex items-center gap-1.5 px-3 py-2.5 rounded-full border border-stone/20 text-xs font-mono min-h-[44px] cursor-pointer"
                aria-label="Select language"
                aria-expanded={langMenuOpen}
                aria-haspopup="true"
              >
                <Globe className="w-4 h-4 text-turquoise" />
                {activeLocale.toUpperCase()}
              </button>
              {langMenuOpen && (
                <>
                  <div className="fixed inset-0 z-10" onClick={() => setLangMenuOpen(false)} />
                  <div className="absolute right-0 mt-2 w-36 rounded-xl bg-paper text-ink shadow-lg ring-1 ring-black/5 z-20 py-1">
                    {languages.map((lang) => (
                      <button
                        key={lang.code}
                        type="button"
                        onClick={() => handleLanguageChange(lang.code)}
                        className="w-full text-left px-4 py-2.5 text-xs hover:bg-stone min-h-[40px] cursor-pointer"
                      >
                        {lang.label}
                      </button>
                    ))}
                  </div>
                </>
              )}
            </div>

            {/* Mobile Menu Toggle Button - 44px touch target */}
            <button
              type="button"
              onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
              className="w-11 h-11 flex items-center justify-center rounded-xl text-stone hover:text-turquoise hover:bg-white/10 transition cursor-pointer"
              aria-label="Toggle navigation menu"
              aria-expanded={mobileMenuOpen}
            >
              {mobileMenuOpen ? <X className="w-6 h-6" /> : <Menu className="w-6 h-6" />}
            </button>
          </div>

        </div>
      </div>

      {/* Mobile Menu */}
      {mobileMenuOpen && (
        <div className="lg:hidden border-t border-white/10 bg-pine py-4 px-4 space-y-3">
          <nav className="flex flex-col gap-3">
            {navItems.map((item) => {
              const isActive = pathname === item.href
              return (
                <Link
                  key={item.name}
                  href={item.href}
                  onClick={() => setMobileMenuOpen(false)}
                  className={`text-sm font-medium py-2 px-3 rounded-lg transition-colors ${isActive ? 'bg-white/10 text-turquoise' : 'text-stone/80 hover:bg-white/5'
                    }`}
                >
                  {item.name}
                </Link>
              )
            })}
          </nav>
          <div className="pt-4 border-t border-white/10">
            <Link
              href="/add-business"
              onClick={() => setMobileMenuOpen(false)}
              className="w-full flex items-center justify-center gap-2 bg-turquoise hover:bg-turquoise/90 text-paper font-medium py-3 rounded-lg text-sm transition"
            >
              <PlusCircle className="w-4 h-4" />
              {t('addBusiness')}
            </Link>
          </div>
        </div>
      )}
    </header>
  )
}
