'use client';

import { useLocale, useTranslations } from 'next-intl';
import { useTransition, useState, useRef, useEffect } from 'react';
import { usePathname, useRouter } from '@/i18n/navigation';
import { useParams } from 'next/navigation';
import { Globe, ChevronDown } from 'lucide-react';
import { routing } from '@/i18n/routing';

type Variant = 'dark' | 'light';

interface LanguageSwitcherProps {
  variant?: Variant;
  className?: string;
}

const LANGUAGE_LABELS: Record<string, string> = {
  fr: 'Français',
  en: 'English',
};

const LANGUAGE_FLAGS: Record<string, string> = {
  fr: '🇫🇷',
  en: '🇬🇧',
};

export function LanguageSwitcher({ variant = 'dark', className = '' }: LanguageSwitcherProps) {
  const t = useTranslations('language');
  const locale = useLocale();
  const router = useRouter();
  const pathname = usePathname();
  const params = useParams();
  const [isPending, startTransition] = useTransition();
  const [isOpen, setIsOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!isOpen) return;
    const handleClickOutside = (event: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [isOpen]);

  const handleSelect = (nextLocale: string) => {
    if (nextLocale === locale) {
      setIsOpen(false);
      return;
    }

    // Persist the choice in a cookie so the server-side resolver can use it on next load
    document.cookie = `NEXT_LOCALE=${nextLocale}; path=/; max-age=${60 * 60 * 24 * 365}; samesite=lax`;

    setIsOpen(false);
    startTransition(() => {
      router.replace(
        // @ts-expect-error — params passthrough for dynamic routes
        { pathname, params },
        { locale: nextLocale }
      );
    });
  };

  const isDark = variant === 'dark';
  const buttonClasses = isDark
    ? 'text-white hover:text-brand-turquoise'
    : 'text-gray-700 hover:text-brand-navy';

  return (
    <div ref={containerRef} className={`relative ${className}`}>
      <button
        type="button"
        onClick={() => setIsOpen(v => !v)}
        disabled={isPending}
        aria-haspopup="listbox"
        aria-expanded={isOpen}
        aria-label={t('label')}
        className={`flex items-center gap-1.5 font-medium transition-colors ${buttonClasses} ${
          isPending ? 'opacity-60 cursor-wait' : ''
        }`}
      >
        <Globe className="w-4 h-4" />
        <span className="text-sm uppercase">{locale}</span>
        <ChevronDown className={`w-3.5 h-3.5 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
      </button>

      {isOpen && (
        <ul
          role="listbox"
          className="absolute right-0 top-full mt-2 min-w-[160px] bg-white rounded-xl shadow-xl border border-gray-100 overflow-hidden z-50"
        >
          {routing.locales.map(loc => {
            const active = loc === locale;
            return (
              <li key={loc}>
                <button
                  type="button"
                  role="option"
                  aria-selected={active}
                  onClick={() => handleSelect(loc)}
                  className={`w-full flex items-center gap-3 px-4 py-2.5 text-sm text-left transition-colors ${
                    active
                      ? 'bg-brand-turquoise/10 text-brand-navy font-semibold'
                      : 'text-gray-700 hover:bg-gray-50'
                  }`}
                >
                  <span aria-hidden="true">{LANGUAGE_FLAGS[loc] ?? ''}</span>
                  <span>{LANGUAGE_LABELS[loc] ?? loc}</span>
                </button>
              </li>
            );
          })}
        </ul>
      )}
    </div>
  );
}

export default LanguageSwitcher;
