'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'

export default function Navbar() {
  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 navItems = [
    { name: t('home'), href: '/' },
    { name: t('restaurants'), href: '/restoranlar' },
    { name: t('aparts'), href: '/apartlar' },
    { name: t('businesses'), href: '/isletmeler' },
    { name: t('collections'), href: '/seckiler' },
    { name: t('blog'), href: '/blog' },
    { name: t('about'), href: '/hakkinda' },
    { name: t('contact'), href: '/iletisim' }
  ]

  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">
              <h1 className="font-heading font-extrabold text-lg text-stone tracking-tight leading-none lowercase">
                marmaris <span className="text-turquoise">local</span>
              </h1>
              <p className="text-[9px] font-mono text-shutter tracking-wider mt-0.5 uppercase">
                local knowledge
              </p>
            </div>
          </Link>

          {/* Desktop Navigation */}
          <nav className="hidden lg:flex items-center gap-6">
            {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 */}
            <Link
              href="/kaydedilenler"
              className="relative w-8 h-8 rounded-full border border-stone/20 hover:border-turquoise transition text-stone hover:text-turquoise flex items-center justify-center"
              title={t('saved')}
            >
              <Heart className="w-4 h-4" />
              {favoritesCount > 0 && (
                <span className="absolute -top-1.5 -right-1.5 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
                onClick={() => setLangMenuOpen(!langMenuOpen)}
                className="flex items-center gap-1.5 px-3 py-1.5 rounded-full border border-stone/20 hover:border-turquoise transition text-xs font-mono"
              >
                <Globe className="w-3.5 h-3.5 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}
                        onClick={() => handleLanguageChange(lang.code)}
                        className={`w-full text-left px-4 py-2 text-xs hover:bg-stone transition flex items-center justify-between ${
                          activeLocale === lang.code ? 'font-bold text-turquoise bg-stone/40' : 'text-ink/80'
                        }`}
                      >
                        {lang.label}
                        <span className="font-mono text-[10px] text-shutter">{lang.code.toUpperCase()}</span>
                      </button>
                    ))}
                  </div>
                </>
              )}
            </div>

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

          {/* Mobile menu button */}
          <div className="flex items-center gap-3 lg:hidden">
            {/* Mobile Saved trigger */}
            <Link
              href="/kaydedilenler"
              className="relative w-8 h-8 rounded-full border border-stone/20 text-stone flex items-center justify-center"
              title={t('saved')}
            >
              <Heart className="w-4 h-4" />
              {favoritesCount > 0 && (
                <span className="absolute -top-1.5 -right-1.5 w-3.5 h-3.5 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 */}
            <div className="relative">
              <button
                onClick={() => setLangMenuOpen(!langMenuOpen)}
                className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-full border border-stone/20 text-xs font-mono"
              >
                <Globe className="w-3.5 h-3.5 text-turquoise" />
                {activeLocale.toUpperCase()}
              </button>
              {langMenuOpen && (
                <>
                  <div className="fixed inset-0 z-10" onClick={() => setLangMenuOpen(false)} />
                  <div className="absolute right-0 mt-2 w-32 rounded-xl bg-paper text-ink shadow-lg ring-1 ring-black/5 z-20 py-1">
                    {languages.map((lang) => (
                      <button
                        key={lang.code}
                        onClick={() => handleLanguageChange(lang.code)}
                        className="w-full text-left px-3 py-1.5 text-xs hover:bg-stone"
                      >
                        {lang.label}
                      </button>
                    ))}
                  </div>
                </>
              )}
            </div>

            <button
              onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
              className="text-stone hover:text-turquoise focus:outline-none"
            >
              {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="/isletme-ekle"
              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>
  )
}
