'use client';

import { useRef, useState, useEffect } from 'react';
import { Globe } from 'lucide-react';
import { useLanguage } from '@client/contexts/LanguageContext';

interface LanguageSwitcherProps {
  variant?: 'landing' | 'sidebar';
  className?: string;
}

export default function LanguageSwitcher({ variant = 'landing', className = '' }: LanguageSwitcherProps) {
  const { currentLang, setLang, activeLanguages, t } = useLanguage();
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    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);
  }, [open]);

  const current = activeLanguages.find(l => l.code === currentLang);

  if (activeLanguages.length <= 1) return null;

  if (variant === 'sidebar') {
    return (
      <div ref={ref} className={`relative ${className}`}>
        <button
          onClick={() => setOpen(o => !o)}
          className="w-full flex items-center gap-3 px-4 py-2.5 text-left transition-colors hover:bg-black/5 text-sm"
          style={{ color: 'hsl(var(--foreground))' }}
        >
          <Globe size={15} style={{ color: 'hsl(var(--muted-foreground))' }} />
          <span className="flex-1">
            {current ? `${current.flag_emoji} ${current.name}` : t('nav.language', 'Language')}
          </span>
        </button>
        {open && (
          <div
            className="absolute bottom-full left-0 right-0 mb-1 rounded-xl shadow-xl z-50 overflow-hidden"
            style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}
          >
            {activeLanguages.map(lang => (
              <button
                key={lang.code}
                onClick={() => { setLang(lang.code); setOpen(false); }}
                className="w-full flex items-center gap-2.5 px-4 py-2.5 text-sm transition-colors hover:bg-black/5 text-left"
                style={{ color: lang.code === currentLang ? 'hsl(var(--primary))' : 'hsl(var(--foreground))' }}
              >
                <span>{lang.flag_emoji}</span>
                <span className="flex-1 truncate">{lang.name}</span>
                {lang.code === currentLang && (
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
                )}
              </button>
            ))}
          </div>
        )}
      </div>
    );
  }

  return (
    <div ref={ref} className={`relative ${className}`}>
      <button
        onClick={() => setOpen(o => !o)}
        aria-label={t('nav.changeLanguage', 'Change language')}
        className="p-2 rounded-lg text-slate-500 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800 transition-all duration-200 hover:scale-105 flex items-center gap-1.5"
      >
        <Globe size={17} />
        {current && <span className="text-sm leading-none">{current.flag_emoji}</span>}
      </button>
      {open && (
        <div className="absolute right-0 bottom-full mb-2 w-44 rounded-xl shadow-xl z-50 overflow-hidden bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700">
          {activeLanguages.map(lang => (
            <button
              key={lang.code}
              onClick={() => { setLang(lang.code); setOpen(false); }}
              className={`w-full flex items-center gap-2.5 px-3.5 py-2.5 text-sm text-left transition-colors ${lang.code === currentLang ? 'bg-orange-50 dark:bg-orange-500/10 text-orange-600 dark:text-orange-400' : 'text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-700'}`}
            >
              <span>{lang.flag_emoji}</span>
              <span className="flex-1 truncate">{lang.native_name || lang.name}</span>
              {lang.code === currentLang && (
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
              )}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
