'use client';

import { useState } from 'react';
import { useLanguage } from '@/lib/language-context';
import { languages, Language } from '@/lib/translations';
import { ChevronDown } from 'lucide-react';

export default function LanguageSwitcher() {
  const { language, setLanguage } = useLanguage();
  const [isOpen, setIsOpen] = useState(false);

  const currentLang = languages.find(l => l.code === language)!;

  const handleSelect = (lang: Language) => {
    setLanguage(lang);
    setIsOpen(false);
  };

  return (
    <div className="relative">
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center gap-1.5 rounded-full border border-[#c99a2e]/30 bg-white/70 px-3 py-1.5 text-sm font-medium text-[#101724] backdrop-blur-xl transition hover:border-[#c99a2e] hover:bg-white"
      >
        <span className="text-base">{currentLang.flag}</span>
        <span className="hidden sm:inline text-xs font-semibold tracking-wider">{currentLang.native}</span>
        <ChevronDown className={`h-3.5 w-3.5 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
      </button>

      {isOpen && (
        <>
          {/* Backdrop */}
          <div 
            className="fixed inset-0 z-[1010]" 
            onClick={() => setIsOpen(false)} 
          />
          
          {/* Dropdown */}
          <div className="absolute right-0 top-full mt-2 z-[1020] w-44 rounded-2xl border border-[#c99a2e]/20 bg-[#fbf7ef] shadow-2xl overflow-hidden">
            {languages.map((lang) => (
              <button
                key={lang.code}
                onClick={() => handleSelect(lang.code)}
                className={`w-full flex items-center gap-3 px-4 py-3 text-left text-sm transition hover:bg-[#fff6dc] ${
                  language === lang.code 
                    ? 'bg-[#fff6dc] text-[#0f5a4a] font-semibold' 
                    : 'text-[#101724]'
                }`}
              >
                <span className="text-xl">{lang.flag}</span>
                <div className="flex flex-col">
                  <span>{lang.native}</span>
                  <span className="text-[10px] text-[#8a6a25] -mt-0.5">{lang.name}</span>
                </div>
              </button>
            ))}
          </div>
        </>
      )}
    </div>
  );
}
