'use client'

import { useLocale } from 'next-intl'
import { useRouter, usePathname } from '@/i18n/navigation'
import { routing } from '@/i18n/routing'
import { useState } from 'react'

export default function LanguageSwitcher() {
  const locale = useLocale()
  const router = useRouter()
  const pathname = usePathname()
  const [isOpen, setIsOpen] = useState(false)

  const handleLocaleChange = (newLocale: string) => {
    router.replace(pathname, { locale: newLocale })
    router.refresh()
    setIsOpen(false)
  }

  return (
    <div className="relative z-[100]">
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="px-3 py-1 border-2 border-slate-700 font-mono uppercase text-xs hover:border-cyan-500 transition-colors"
        aria-label="Switch language"
      >
        {locale}
      </button>

      {isOpen && (
        <div className="absolute right-0 top-full mt-2 bg-slate-900 border-2 border-slate-700 min-w-[120px] z-[100]">
          {routing.locales.map((loc: string) => (
            <button
              key={loc}
              onClick={() => handleLocaleChange(loc)}
              className={`
                w-full text-left px-4 py-2 font-mono uppercase text-xs
                border-b border-slate-700 last:border-b-0
                ${
                  locale === loc ? 'bg-cyan-900 text-cyan-300' : 'text-slate-400 hover:bg-slate-800'
                }
              `}
            >
              {loc === 'en' ? 'English' : 'Română'}
            </button>
          ))}
        </div>
      )}

      {isOpen && <div className="fixed inset-0 z-40" onClick={() => setIsOpen(false)} />}
    </div>
  )
}
