import React, { useState, useRef, useEffect } from 'react';
import { useLanguage } from '../contexts/LanguageContext';
import { ChevronDown } from 'lucide-react';

const LanguageSwitcher = ({ isScrolled }) => {
  const [isOpen, setIsOpen] = useState(false);
  const { language, setLanguage } = useLanguage();
  const dropdownRef = useRef(null);

  const languages = {
    ru: {
      name: 'Русский',
      flag: '🇷🇺'
    },
    en: {
      name: 'English',
      flag: '🇬🇧'
    },
    ar: {
      name: 'العربية',
      flag: '🇸🇦'
    }
  };

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setIsOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  return (
    <div className="relative" ref={dropdownRef}>
      <button
        onClick={() => setIsOpen(!isOpen)}
        className={`flex items-center space-x-2 px-3 py-1 rounded-md border-2 ${
          isScrolled 
            ? 'text-gray-800 hover:text-gray-600 border-gray-800' 
            : 'text-white hover:text-gray-200 border-white'
        }`}
      >
        <span className="text-lg">{languages[language].flag}</span>
        <span className="text-lg font-semibold">{languages[language].name}</span>
        <ChevronDown className={`w-4 h-4 transition-transform duration-200 ${isOpen ? 'rotate-180' : ''}`} />
      </button>

      {isOpen && (
        <div className="absolute right-0 mt-2 w-48 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5">
          <div className="py-1">
            {Object.entries(languages).map(([code, { name, flag }]) => (
              <button
                key={code}
                onClick={() => {
                  setLanguage(code);
                  setIsOpen(false);
                }}
                className={`flex items-center w-full px-4 py-2 text-sm ${
                  language === code ? 'bg-gray-100 text-gray-900' : 'text-gray-700'
                } hover:bg-gray-50`}
              >
                <span className="mr-2 text-lg">{flag}</span>
                <span>{name}</span>
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

export default LanguageSwitcher;