import { useState, useRef, useEffect } from 'react';
import { motion, AnimatePresence } from 'motion/react';
import { Globe, Check } from 'lucide-react';
import { Language } from '../types';

interface LanguageSelectorProps {
  currentLang: Language;
  onLanguageChange: (lang: Language) => void;
}

export const DanishFlag = () => (
  <svg viewBox="0 0 100 100" className="w-6 h-6 rounded-full shadow-xs border border-neutral-100" aria-hidden="true">
    <circle cx="50" cy="50" r="50" fill="#C8102E" />
    <rect x="30" y="0" width="12" height="100" fill="#FFFFFF" />
    <rect x="0" y="44" width="100" height="12" fill="#FFFFFF" />
  </svg>
);

export const BritishFlag = () => (
  <svg viewBox="0 0 100 100" className="w-6 h-6 rounded-full shadow-xs border border-neutral-100" aria-hidden="true">
    <circle cx="50" cy="50" r="50" fill="#012169" />
    {/* St George's Cross background lines */}
    <path d="M 0,0 L 100,100 M 0,100 L 100,0" stroke="#FFFFFF" strokeWidth="12" />
    <path d="M 0,0 L 100,100 M 0,100 L 100,0" stroke="#C8102E" strokeWidth="6" />
    <path d="M 50,0 V 100 M 0,50 H 100" stroke="#FFFFFF" strokeWidth="20" />
    <path d="M 50,0 V 100 M 0,50 H 100" stroke="#C8102E" strokeWidth="12" />
  </svg>
);

export const GermanFlag = () => (
  <svg viewBox="0 0 100 100" className="w-6 h-6 rounded-full shadow-xs border border-neutral-100" aria-hidden="true">
    <clipPath id="circle-clip">
      <circle cx="50" cy="50" r="50" />
    </clipPath>
    <g clipPath="url(#circle-clip)">
      <rect x="0" y="0" width="100" height="33.3" fill="#000000" />
      <rect x="0" y="33.3" width="100" height="33.3" fill="#D00F0F" />
      <rect x="0" y="66.6" width="100" height="33.4" fill="#FFCE00" />
    </g>
  </svg>
);

export default function LanguageSelector({ currentLang, onLanguageChange }: LanguageSelectorProps) {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  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);
  }, []);

  const getFlagComponent = (lang: Language) => {
    switch (lang) {
      case 'da': return <DanishFlag />;
      case 'en': return <BritishFlag />;
      case 'de': return <GermanFlag />;
    }
  };

  const getLanguageName = (lang: Language) => {
    switch (lang) {
      case 'da': return 'Dansk (DA)';
      case 'en': return 'English (EN)';
      case 'de': return 'Deutsch (DE)';
    }
  };

  const options: Language[] = ['da', 'en', 'de'];

  return (
    <div id="lang-selector-container" className="relative z-50 font-sans" ref={dropdownRef}>
      <button
        id="lang-selector-btn"
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center gap-2 p-1.5 focus:outline-hidden hover:bg-neutral-100/50 rounded-full transition-all duration-200"
        title="Vælg sprog / Choose language"
      >
        <span className="relative flex h-6 w-6">
          {getFlagComponent(currentLang)}
        </span>
      </button>

      <AnimatePresence>
        {isOpen && (
          <motion.div
            id="lang-dropdown"
            initial={{ opacity: 0, y: 10, scale: 0.95 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: 10, scale: 0.95 }}
            transition={{ duration: 0.15, ease: 'easeOut' }}
            className="absolute right-0 mt-2 w-48 bg-white border border-neutral-200/80 rounded-xl shadow-lg p-1"
          >
            <div className="px-3 py-2 text-[10px] uppercase font-mono tracking-wider text-neutral-400 border-b border-neutral-100 mb-1 flex items-center gap-1.5">
              <Globe className="w-3.5 h-3.5" />
              <span>Language / Sprog</span>
            </div>
            {options.map((opt) => (
              <button
                key={opt}
                id={`lang-opt-${opt}`}
                onClick={() => {
                  onLanguageChange(opt);
                  setIsOpen(false);
                }}
                className={`w-full flex items-center justify-between px-3 py-2 text-sm rounded-lg text-left transition-colors duration-150 ${
                  currentLang === opt
                    ? 'bg-neutral-50 font-medium text-neutral-900'
                    : 'text-neutral-600 hover:bg-neutral-100/60 hover:text-neutral-900'
                }`}
              >
                <div className="flex items-center gap-2.5">
                  {getFlagComponent(opt)}
                  <span>{getLanguageName(opt)}</span>
                </div>
                {currentLang === opt && (
                  <Check className="w-4 h-4 text-[#00965e]" />
                )}
              </button>
            ))}
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
