'use client'

import { useState, useRef, useEffect } from 'react'
import { useLanguage } from '@/lib/LanguageContext'
import { useTheme } from '@/lib/ThemeContext'
import { Language } from '@/lib/i18n'

interface LanguageDropdownProps {
  className?: string
}

export function LanguageDropdown({ className = '' }: LanguageDropdownProps) {
  const { language, setLanguage, availableLanguages } = useLanguage()
  const { isDark } = useTheme()
  const [isOpen, setIsOpen] = useState(false)
  const dropdownRef = useRef<HTMLDivElement>(null)

  // Schliessen bei Klick ausserhalb
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false)
      }
    }
    document.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [])

  // Schliessen bei Escape
  useEffect(() => {
    function handleEscape(event: KeyboardEvent) {
      if (event.key === 'Escape') setIsOpen(false)
    }
    document.addEventListener('keydown', handleEscape)
    return () => document.removeEventListener('keydown', handleEscape)
  }, [])

  const currentLang = availableLanguages[language]

  return (
    <div ref={dropdownRef} className={`relative ${className}`}>
      {/* Trigger Button */}
      <button
        onClick={() => setIsOpen(!isOpen)}
        className={`flex items-center gap-2 px-4 py-2.5 backdrop-blur-xl border rounded-2xl transition-all ${
          isDark
            ? 'bg-white/10 border-white/20 text-white hover:bg-white/20'
            : 'bg-black/5 border-black/10 text-slate-700 hover:bg-black/10'
        }`}
        aria-haspopup="listbox"
        aria-expanded={isOpen}
      >
        <span className="text-lg">{currentLang.flag}</span>
        <span className="text-sm font-medium hidden sm:inline">{currentLang.name}</span>
        <svg
          className={`w-4 h-4 transition-transform ${isOpen ? 'rotate-180' : ''} ${
            isDark ? 'text-white/60' : 'text-slate-500'
          }`}
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
        </svg>
      </button>

      {/* Dropdown Menu */}
      {isOpen && (
        <div className={`absolute right-0 mt-2 w-48 backdrop-blur-2xl border rounded-2xl shadow-xl overflow-hidden z-50 ${
          isDark
            ? 'bg-slate-900/90 border-white/20'
            : 'bg-white/95 border-black/10'
        }`}>
          <ul role="listbox" className="py-1">
            {(Object.keys(availableLanguages) as Language[]).map((lang) => {
              const langInfo = availableLanguages[lang]
              const isSelected = lang === language
              return (
                <li key={lang}>
                  <button
                    onClick={() => {
                      setLanguage(lang)
                      setIsOpen(false)
                    }}
                    className={`w-full flex items-center gap-3 px-4 py-3 text-left transition-all ${
                      isSelected
                        ? isDark
                          ? 'bg-white/20 text-white'
                          : 'bg-indigo-100 text-slate-900'
                        : isDark
                          ? 'text-white/80 hover:bg-white/10 hover:text-white'
                          : 'text-slate-700 hover:bg-slate-100 hover:text-slate-900'
                    }`}
                    role="option"
                    aria-selected={isSelected}
                  >
                    <span className="text-lg">{langInfo.flag}</span>
                    <span className="text-sm font-medium">{langInfo.name}</span>
                    {isSelected && (
                      <svg className={`w-4 h-4 ml-auto ${isDark ? 'text-green-400' : 'text-green-600'}`} fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                      </svg>
                    )}
                  </button>
                </li>
              )
            })}
          </ul>
        </div>
      )}
    </div>
  )
}
