import React, { useEffect, useRef, useState } from 'react';

type Lang = { code: string; label: string };

interface LanguageSwitcherProps {
  value?: string;
  languages?: Lang[];
  onChange?: (code: string) => void;
}

const DEFAULT_LANGUAGES: Lang[] = [
  { code: 'EN', label: 'English' },
  { code: 'NL', label: 'Nederlands' },
  { code: 'FR', label: 'Français' },
  { code: 'DE', label: 'Deutsch' }
];

const LanguageSwitcher: React.FC<LanguageSwitcherProps> = ({ value = 'EN', languages = DEFAULT_LANGUAGES, onChange }) => {
  const [open, setOpen] = useState(false);
  const [current, setCurrent] = useState(value);
  const rootRef = useRef<HTMLDivElement | null>(null);
  const buttonRef = useRef<HTMLButtonElement | null>(null);
  const menuId = 'language-switcher-menu';

  // Keep in sync if parent controls value
  useEffect(() => setCurrent(value), [value]);

  // Close on outside click
  useEffect(() => {
    const onPointerDown = (e: PointerEvent) => {
      if (!open) return;
      const target = e.target as Node;
      if (rootRef.current && !rootRef.current.contains(target)) setOpen(false);
    };
    window.addEventListener('pointerdown', onPointerDown);
    return () => window.removeEventListener('pointerdown', onPointerDown);
  }, [open]);

  // Close on ESC
  useEffect(() => {
    const onKeyDown = (e: KeyboardEvent) => {
      if (!open) return;
      if (e.key === 'Escape') {
        setOpen(false);
        buttonRef.current?.focus();
      }
    };
    window.addEventListener('keydown', onKeyDown);
    return () => window.removeEventListener('keydown', onKeyDown);
  }, [open]);

  const selectLang = (code: string) => {
    setCurrent(code);
    onChange?.(code);
    setOpen(false);
    buttonRef.current?.focus();
  };

  const onButtonKeyDown: React.KeyboardEventHandler<HTMLButtonElement> = (e) => {
    if (e.key === 'Enter' || e.key === ' ') {
      e.preventDefault();
      setOpen((v) => !v);
    }
    if (e.key === 'ArrowDown') {
      e.preventDefault();
      setOpen(true);
      // focus first option next tick
      requestAnimationFrame(() => {
        rootRef.current?.querySelector<HTMLButtonElement>('[role="menuitemradio"]')?.focus();
      });
    }
  };

  const onMenuKeyDown: React.KeyboardEventHandler<HTMLDivElement> = (e) => {
    const items = Array.from(rootRef.current?.querySelectorAll<HTMLButtonElement>('[role="menuitemradio"]') ?? []);
    if (!items.length) return;

    const idx = items.indexOf(document.activeElement as HTMLButtonElement);

    if (e.key === 'ArrowDown') {
      e.preventDefault();
      items[(idx + 1 + items.length) % items.length].focus();
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      items[(idx - 1 + items.length) % items.length].focus();
    } else if (e.key === 'Home') {
      e.preventDefault();
      items[0].focus();
    } else if (e.key === 'End') {
      e.preventDefault();
      items[items.length - 1].focus();
    }
  };

  return (
    <div className="nav__subnav__languages" ref={rootRef}>
      {/* <svg
        className="nav__subnav__languages__icon"
        xmlns="http://www.w3.org/2000/svg"
        width="16"
        height="16"
        fill="currentColor"
        viewBox="0 0 16 16"
        aria-hidden="true"
      >
        <path d="M0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8zm8-7a7 7 0 0 0-6.468 4.146h12.936A7 7 0 0 0 8 1zm-6.218 5.5a13.334 13.334 0 0 1 .664-1.75H13.55c.24.56.42 1.17.528 1.75H1.782zm-.57 1.5h13.576a13.334 13.334 0 0 1-.664 1.75H2.208a13.334 13.334 0 0 1-.664-1.75zm.57 3.5c.796 2.07 2.39 3.5 4.22 3.5s3.424-1.43 4.22-3.5H1.782zM8 15a7 7 0 0 0 6.468-4.146H1.532A7 7 0 0 0 8 15z" />
      </svg> */}

      <button
        ref={buttonRef}
        type="button"
        className="nav__subnav__languages__button"
        aria-haspopup="menu"
        aria-expanded={open}
        aria-controls={menuId}
        onClick={() => setOpen((v) => !v)}
        onKeyDown={onButtonKeyDown}>
        <span className="nav__subnav__languages__value">{current}</span>
        <svg
          className="nav__subnav__languages__chevron"
          xmlns="http://www.w3.org/2000/svg"
          width="14"
          height="14"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
          aria-hidden="true">
          <path d="m6 9 6 6 6-6" />
        </svg>
      </button>

      <div
        id={menuId}
        className={`nav__subnav__languages__dropdown ${open ? 'is-open' : ''}`}
        role="menu"
        aria-label="Select language"
        onKeyDown={onMenuKeyDown}>
        {languages.map((l) => (
          <button
            key={l.code}
            type="button"
            className={`nav__subnav__languages__option ${l.code === current ? 'is-active' : ''}`}
            role="menuitemradio"
            aria-checked={l.code === current}
            onClick={() => selectLang(l.code)}>
            <span className="nav__subnav__languages__option__code">{l.code}</span>
            <span className="nav__subnav__languages__option__label">{l.label}</span>
          </button>
        ))}
      </div>
    </div>
  );
};

export default LanguageSwitcher;
