// LanguageModal — full-screen-ish centered overlay for picking UI language.
// Matches the pasted reference: search field at top, two sections
// (Gateway / All), each a 3-col grid of cards with:
//   • native name (serif-ish, large)
//   • English name (medium)
//   • country (smaller, muted)
// Current language is highlighted. Clicking commits and closes.

function LanguageModal({ open, onClose }) {
  const I = window.I18n;
  const [q, setQ] = React.useState('');
  const [hover, setHover] = React.useState(null);
  const modalRef = React.useRef(null);
  const openerRef = React.useRef(null);

  // audit rank 5: real dialog — Escape closes, Tab stays trapped in the modal,
  // and focus returns to whatever opened it when it closes.
  React.useEffect(() => {
    if (!open) {
      if (openerRef.current && openerRef.current.focus) { openerRef.current.focus(); openerRef.current = null; }
      return;
    }
    // openerRef is captured during render (below) BEFORE the modal's own
    // controls take focus, so focus returns to the true opener on close.
    const onKey = (e) => {
      if (e.key === 'Escape') { onClose(); return; }
      if (e.key === 'Tab' && modalRef.current) {
        const f = Array.prototype.slice.call(
          modalRef.current.querySelectorAll('a[href],button:not([disabled]),input:not([disabled]),select,textarea,[tabindex]:not([tabindex="-1"])')
        ).filter(el => el.offsetParent !== null);
        if (!f.length) return;
        const first = f[0], last = f[f.length - 1];
        if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
        else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
      }
    };
    window.addEventListener('keydown', onKey, true);
    const t = setTimeout(() => {
      const el = modalRef.current && modalRef.current.querySelector('input,button:not([disabled]),a[href]');
      if (el && el.focus) el.focus();
    }, 0);
    return () => { window.removeEventListener('keydown', onKey, true); clearTimeout(t); };
  }, [open, onClose]);

  // Capture the opener while it still has focus (during the open render, before
  // the modal's fields mount and grab focus). — audit rank 5
  if (open && !openerRef.current) openerRef.current = document.activeElement;

  if (!open) return null;

  const matches = (l) => {
    const s = q.trim().toLowerCase();
    if (!s) return true;
    return l.native.toLowerCase().includes(s)
        || l.en.toLowerCase().includes(s)
        || l.country.toLowerCase().includes(s)
        || l.code.toLowerCase().includes(s);
  };

  const current = I.getLang();

  const Card = (l) => React.createElement('button', {
    key: l.code,
    className: 'amos-lang-card ' + (current === l.code ? 'on' : '') + (l.script === 'rtl' ? ' rtl' : ''),
    onClick: () => { I.setLang(l.code); onClose(); },
    onMouseEnter: () => setHover(l.code),
    onMouseLeave: () => setHover(null),
  },
    React.createElement('div', { className:'wl-native', dir: l.script==='rtl'?'rtl':undefined }, l.native),
    React.createElement('div', { className:'wl-en' }, l.en),
    React.createElement('div', { className:'wl-country' }, l.country),
    current === l.code && React.createElement('div', { className:'wl-check' }, window.I.check ? window.I.check(14) : '✓')
  );

  const gw = I.GATEWAY.filter(matches);
  const all = I.LANGUAGES.filter(matches);

  return React.createElement('div', { className:'amos-modal-backdrop', onClick: onClose },
    React.createElement('div', {
      className:'amos-lang-modal', ref: modalRef,
      role:'dialog', 'aria-modal':'true', 'aria-labelledby':'lang-modal-title',
      onClick: (e) => e.stopPropagation()
    },
      React.createElement('div', { className:'wlm-head' },
        React.createElement('h2', { id:'lang-modal-title' }, I.t('lang.modal.title')),
        React.createElement('button', { className:'wlm-close', onClick: onClose, 'aria-label':'Close' }, window.I.x(18))
      ),
      React.createElement('div', { className:'wlm-search' },
        window.I.search(16),
        React.createElement('input', {
          value: q,
          onChange: (e) => setQ(e.target.value),
          placeholder: I.t('lang.modal.search')
        })
      ),
      React.createElement('div', { className:'wlm-body' },
        gw.length > 0 && React.createElement('div', { className:'wlm-sec-title' }, I.t('lang.modal.gateway')),
        gw.length > 0 && React.createElement('div', { className:'wlm-grid' }, gw.map(Card)),
        all.length > 0 && React.createElement('div', { className:'wlm-sec-title' }, I.t('lang.modal.all')),
        all.length > 0 && React.createElement('div', { className:'wlm-grid' }, all.map(Card)),
        gw.length === 0 && all.length === 0 && React.createElement('div', { className:'wlm-empty' },
          'No matches for “', q, '”'
        )
      )
    )
  );
}

Object.assign(window, { LanguageModal });
