'use client';

import { useState, useRef, useEffect, useMemo } from 'react';
import { useTranslation, LANGUAGE_OPTIONS, Language } from '@/lib/i18n';
import { useAuthStore } from '@/lib/store';

export default function LanguageSelector() {
  const { language, setLanguage } = useTranslation();
  const { user } = useAuthStore();
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // Filter languages: Korean only visible to admins
  const isAdmin = user?.is_admin;
  const availableLanguages = useMemo(() =>
    LANGUAGE_OPTIONS.filter((lang) => lang.value !== 'ko' || isAdmin),
    [isAdmin]
  );

  // If current language is not available (e.g., 'ko' for non-admin), reset to first available
  useEffect(() => {
    const isCurrentLangAvailable = availableLanguages.some((l) => l.value === language);
    if (!isCurrentLangAvailable && availableLanguages.length > 0) {
      setLanguage(availableLanguages[0].value);
    }
  }, [language, availableLanguages, setLanguage]);

  const currentLang = availableLanguages.find((l) => l.value === language) || availableLanguages[0];

  useEffect(() => {
    const 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 handleSelect = (lang: Language) => {
    setLanguage(lang);
    setIsOpen(false);
  };

  return (
    <div className="relative" ref={dropdownRef}>
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center gap-2 px-3 py-2 bg-white border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors"
      >
        <span className="text-lg">{currentLang.flag}</span>
        <span className="text-sm font-medium text-gray-700 hidden sm:inline">
          {currentLang.label}
        </span>
        <svg
          className={`w-4 h-4 text-gray-500 transition-transform ${isOpen ? 'rotate-180' : ''}`}
          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>

      {isOpen && (
        <div className="absolute right-0 mt-2 w-40 bg-white border border-gray-200 rounded-lg shadow-lg z-50">
          {availableLanguages.map((option) => (
            <button
              key={option.value}
              onClick={() => handleSelect(option.value)}
              className={`w-full flex items-center gap-3 px-4 py-2.5 text-left hover:bg-gray-50 first:rounded-t-lg last:rounded-b-lg ${
                language === option.value ? 'bg-primary-50 text-primary-600' : 'text-gray-700'
              }`}
            >
              <span className="text-lg">{option.flag}</span>
              <span className="text-sm font-medium">{option.label}</span>
              {language === option.value && (
                <svg className="w-4 h-4 ml-auto" 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>
          ))}
        </div>
      )}
    </div>
  );
}
