export function createInfoModal({ onOpen } = {}) {
  const modal = document.querySelector('#infoModal');
  const openButton = document.querySelector('#helpButton');
  const closeButton = document.querySelector('#closeInfoButton');
  const tabs = [...modal.querySelectorAll('[data-info-tab]')];
  const panels = [...modal.querySelectorAll('.info-panel')];
  let lastFocus = null;

  function selectPanel(panelId) {
    tabs.forEach(tab => {
      const active = tab.dataset.infoTab === panelId;
      tab.classList.toggle('is-active', active);
      tab.setAttribute('aria-selected', String(active));
      tab.tabIndex = active ? 0 : -1;
    });
    panels.forEach(panel => {
      const active = panel.id === panelId;
      panel.classList.toggle('is-active', active);
      panel.hidden = !active;
    });
  }

  function open() {
    lastFocus = document.activeElement;
    onOpen?.();
    selectPanel('howToPanel');
    modal.classList.add('is-visible');
    modal.setAttribute('aria-hidden', 'false');
    document.body.classList.add('has-open-modal');
    closeButton.focus();
  }

  function close() {
    if (!modal.classList.contains('is-visible')) return;
    modal.classList.remove('is-visible');
    modal.setAttribute('aria-hidden', 'true');
    document.body.classList.remove('has-open-modal');
    lastFocus?.focus?.();
  }

  openButton.addEventListener('click', open);
  closeButton.addEventListener('click', close);
  modal.addEventListener('click', event => { if (event.target === modal) close(); });
  tabs.forEach(tab => tab.addEventListener('click', () => selectPanel(tab.dataset.infoTab)));
  modal.addEventListener('keydown', event => {
    if (event.key === 'Escape') { event.preventDefault(); close(); }
    if (event.key === 'Tab') {
      const focusable = [...modal.querySelectorAll('button:not([hidden])')].filter(el => !el.disabled && el.offsetParent !== null);
      const first = focusable[0], last = focusable.at(-1);
      if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
      else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
    }
  });

  return { open, close, isOpen: () => modal.classList.contains('is-visible') };
}
