'use client';

import { useState, useRef, useEffect } from 'react';
import { Globe, Check } from 'lucide-react';
import { LOCALES, Locale } from '@/i18n/types';
import { useLocaleStore } from '@/store/locale';
import { useTranslation } from '@/hooks/useTranslation';
import { cn } from '@/lib/utils';

export default function LanguageSwitcher() {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  const { locale, setLocale } = useLocaleStore();
  const { t } = useTranslation();

  const current = LOCALES.find((l) => l.code === locale);

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

  return (
    <div ref={ref} className="relative">
      <button
        onClick={() => setOpen(!open)}
        className="flex items-center gap-1.5 rounded-lg px-2 py-2 text-sm font-medium text-gray-600 transition-colors hover:bg-gray-100 hover:text-brand-700"
        aria-label={t('nav.language')}
      >
        <Globe className="h-4 w-4" />
        <span className="hidden sm:inline">{current?.nativeLabel}</span>
      </button>

      {open && (
        <div className="absolute end-0 top-full z-50 mt-1 min-w-[10rem] overflow-hidden rounded-xl border border-gray-100 bg-white py-1 shadow-premium-lg">
          {LOCALES.map((lang) => (
            <button
              key={lang.code}
              onClick={() => {
                setLocale(lang.code as Locale);
                setOpen(false);
              }}
              className={cn(
                'flex w-full items-center justify-between gap-3 px-4 py-2.5 text-sm transition-colors hover:bg-brand-50',
                locale === lang.code
                  ? 'font-semibold text-brand-700'
                  : 'text-gray-600'
              )}
            >
              <span>
                {lang.nativeLabel}
                <span className="ms-2 text-xs text-gray-400">{lang.label}</span>
              </span>
              {locale === lang.code && (
                <Check className="h-4 w-4 shrink-0 text-brand-700" />
              )}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}