'use client';

import { useEffect, useRef, useState } from 'react';
import { useSalesChannel } from '@/lib/sales-channel-context';

export default function LanguageSwitcher() {
  const { storefrontLanguages, currentLanguageId, setLanguage, isReady } = useSalesChannel();
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    const onClick = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setOpen(false);
    };
    window.addEventListener('mousedown', onClick);
    window.addEventListener('keydown', onKey);
    return () => {
      window.removeEventListener('mousedown', onClick);
      window.removeEventListener('keydown', onKey);
    };
  }, [open]);

  // Only show the switcher when 2+ languages have an admin-configured domain.
  if (!isReady || storefrontLanguages.length < 2) return null;

  const current =
    storefrontLanguages.find((l) => l.languageId === currentLanguageId) || storefrontLanguages[0];
  const label =
    current?.localeCode?.split('-')[0]?.toUpperCase() || current?.name || 'EN';

  return (
    <div ref={ref} className="relative">
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        className="flex items-center gap-1 px-2 py-1.5 text-sm text-surface-600 hover:text-surface-900 transition-colors"
        aria-label="Change language"
      >
        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={1.5}
            d="M12 21a9 9 0 100-18 9 9 0 000 18zm0 0c2.5-2.5 4-6 4-9s-1.5-6.5-4-9m0 18c-2.5-2.5-4-6-4-9s1.5-6.5 4-9M3 12h18"
          />
        </svg>
        <span className="font-medium">{label}</span>
        <svg className={`w-3 h-3 transition-transform ${open ? 'rotate-180' : ''}`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
        </svg>
      </button>

      {open && (
        <div className="absolute right-0 mt-1 w-48 bg-white border border-surface-200 rounded-lg shadow-lg py-1 z-[60]">
          {storefrontLanguages.map((l) => (
            <button
              key={l.languageId}
              type="button"
              onClick={() => {
                setOpen(false);
                if (l.languageId !== currentLanguageId) setLanguage(l.languageId);
              }}
              className={`w-full text-left px-3 py-2 text-sm transition-colors ${
                l.languageId === currentLanguageId
                  ? 'bg-brand-50 text-brand-700 font-medium'
                  : 'text-surface-700 hover:bg-surface-50'
              }`}
            >
              {l.name}
              <span className="text-xs text-surface-400 ml-2">{l.localeCode}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
