/**
 * LanguageSelector — dropdown in the admin sidebar to switch the active language.
 *
 * Only rendered when more than one language is enabled.
 *
 * @since 1.2.0
 */

import { useState, useRef, useEffect } from 'react'
import { Globe, ChevronDown, Check } from 'lucide-react'
import { useLanguage } from '@/contexts/LanguageContext'
import { useNavigationGuard } from '@/contexts/NavigationGuardContext'

export function LanguageSelector() {
  const { currentLanguage, enabledLanguages, labels, setLanguage, isMultilingual } = useLanguage()
  const { checkGuard } = useNavigationGuard()
  const [open, setOpen] = useState(false)
  const ref = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) {
        setOpen(false)
      }
    }
    document.addEventListener('mousedown', handler)
    return () => document.removeEventListener('mousedown', handler)
  }, [])

  if (!isMultilingual) return null

  return (
    <div ref={ref} className="relative">
      <button
        type="button"
        onClick={() => setOpen(!open)}
        className="flex items-center gap-2 px-3 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg transition-colors w-full"
      >
        <Globe className="w-4 h-4 shrink-0" />
        <span className="flex-1 text-start truncate">
          {labels[currentLanguage] ?? currentLanguage.toUpperCase()}
        </span>
        <ChevronDown className={`w-4 h-4 shrink-0 transition-transform ${open ? 'rotate-180' : ''}`} />
      </button>

      {open && (
        <div className="absolute start-0 end-0 mt-1 bg-white border border-gray-200 rounded-lg shadow-lg z-50 py-1">
          {enabledLanguages.map((lang) => (
            <button
              key={lang}
              type="button"
              onClick={() => {
                if (lang === currentLanguage) { setOpen(false); return }
                checkGuard(() => { setLanguage(lang); setOpen(false) })
              }}
              className={`flex items-center gap-2 w-full px-3 py-2 text-sm transition-colors
                ${lang === currentLanguage ? 'bg-primary-50 text-primary-600' : 'text-gray-700 hover:bg-gray-50'}
              `}
            >
              <span className="flex-1 text-start">{labels[lang] ?? lang.toUpperCase()}</span>
              {lang === currentLanguage && <Check className="w-4 h-4 shrink-0" />}
            </button>
          ))}
        </div>
      )}
    </div>
  )
}
