// ============================================================
// Language switcher
//   Desktop: EN | FR | ES pills, always visible
//   Mobile:  current language + chevron, tap to open a dropdown
// ============================================================

const LangSwitcherDesktop = ({ lang, setLang }) => (
  <div className="lang-switcher" role="group" aria-label="Language" style={{
    display: 'inline-flex', alignItems: 'center', gap: 2,
    border: '1px solid var(--border)', borderRadius: 6,
    padding: 2, marginRight: 12, background: 'rgba(255,255,255,.02)',
  }}>
    {LANGS.map((code) => {
      const active = lang === code;
      return (
        <button
          key={code}
          type="button"
          onClick={() => setLang(code)}
          aria-pressed={active}
          style={{
            background: active ? 'var(--gold-400)' : 'transparent',
            color: active ? '#000' : 'var(--fg-dim)',
            border: 'none', borderRadius: 4,
            padding: '4px 8px',
            fontFamily: 'RH Phonic', fontSize: 11, fontWeight: 500,
            letterSpacing: '.12em', textTransform: 'uppercase',
            cursor: active ? 'default' : 'pointer',
            transition: 'background 120ms var(--ease-out), color 120ms var(--ease-out)',
          }}
        >
          {LANG_LABELS[code]}
        </button>
      );
    })}
  </div>
);

const LangSwitcherMobile = ({ lang, setLang }) => {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);

  // Close on outside click and Escape key — standard menu behavior.
  React.useEffect(() => {
    if (!open) return;
    const onDoc = (e) => {
      if (ref.current && !ref.current.contains(e.target)) setOpen(false);
    };
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('touchstart', onDoc);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onDoc);
      document.removeEventListener('touchstart', onDoc);
      document.removeEventListener('keydown', onKey);
    };
  }, [open]);

  const others = LANGS.filter((code) => code !== lang);

  return (
    <div
      ref={ref}
      className="lang-switcher lang-switcher--mobile"
      role="group"
      aria-label="Language"
      style={{ position: 'relative', marginRight: 8 }}
    >
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        aria-haspopup="menu"
        aria-expanded={open}
        style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          background: 'rgba(255,255,255,.02)',
          color: 'var(--fg)',
          border: '1px solid var(--border)', borderRadius: 6,
          padding: '6px 10px',
          fontFamily: 'RH Phonic', fontSize: 11, fontWeight: 500,
          letterSpacing: '.12em', textTransform: 'uppercase',
          cursor: 'pointer',
        }}
      >
        {LANG_LABELS[lang]}
        <svg
          width="10" height="10" viewBox="0 0 10 10" aria-hidden="true"
          style={{
            transition: 'transform 160ms var(--ease-out)',
            transform: open ? 'rotate(180deg)' : 'rotate(0deg)',
          }}
        >
          <path d="M1.5 3.5 L5 7 L8.5 3.5" stroke="currentColor" strokeWidth="1.2" fill="none" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      </button>

      {open && (
        <div
          role="menu"
          style={{
            position: 'absolute', top: 'calc(100% + 6px)', right: 0,
            background: 'var(--ink-2)',
            border: '1px solid var(--border-strong)', borderRadius: 6,
            padding: 4, minWidth: 64, zIndex: 70,
            boxShadow: '0 12px 32px rgba(0,0,0,.45)',
            display: 'flex', flexDirection: 'column', gap: 2,
          }}
        >
          {others.map((code) => (
            <button
              key={code}
              type="button"
              role="menuitem"
              onClick={() => { setLang(code); setOpen(false); }}
              style={{
                background: 'transparent',
                color: 'var(--fg)',
                border: 'none', borderRadius: 4,
                padding: '8px 12px', textAlign: 'left',
                fontFamily: 'RH Phonic', fontSize: 11, fontWeight: 500,
                letterSpacing: '.12em', textTransform: 'uppercase',
                cursor: 'pointer',
                transition: 'background 120ms var(--ease-out)',
              }}
              onMouseEnter={(e) => { e.currentTarget.style.background = 'rgba(196,172,120,.12)'; }}
              onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; }}
            >
              {LANG_LABELS[code]}
            </button>
          ))}
        </div>
      )}
    </div>
  );
};

const LangSwitcher = () => {
  const { lang, setLang } = useI18n();

  // Match Hero.jsx's responsive pattern: track viewport in JS rather than rely
  // on a global CSS file we'd have to touch.
  const [isMobile, setIsMobile] = React.useState(() =>
    typeof window !== 'undefined' && window.matchMedia('(max-width: 768px)').matches
  );
  React.useEffect(() => {
    if (typeof window === 'undefined') return;
    const mq = window.matchMedia('(max-width: 768px)');
    const handler = (e) => setIsMobile(e.matches);
    if (mq.addEventListener) mq.addEventListener('change', handler);
    else mq.addListener(handler);
    return () => {
      if (mq.removeEventListener) mq.removeEventListener('change', handler);
      else mq.removeListener(handler);
    };
  }, []);

  return isMobile
    ? <LangSwitcherMobile lang={lang} setLang={setLang} />
    : <LangSwitcherDesktop lang={lang} setLang={setLang} />;
};

Object.assign(window, { LangSwitcher });
