/**
 * Modal: open/close by data attributes, Escape key, backdrop click.
 *
 * Markup:
 * - Trigger: <button data-modal-open="modal-id">. Target modal must have id and class="modal".
 * - Close: .modal-close, [data-modal-close], or click on .modal-backdrop.
 * - Size: add .modal-small, .modal-medium, .modal-large to the .modal element.
 *
 * Initialization: automatic. All [data-modal-open] buttons and .modal elements
 * are wired on load (or on DOMContentLoaded if the script runs before DOM ready).
 *
 * Programmatic API: Modal.open(id), Modal.close(idOrElement).
 */
(function () {
  const CLOSE_DURATION_MS = 200;

  function getModal(idOrEl) {
    if (typeof idOrEl === 'string') return document.getElementById(idOrEl);
    if (idOrEl?.classList?.contains('modal')) return idOrEl;
    return null;
  }

  function openModal(id) {
    const modal = getModal(id);
    if (!modal?.classList.contains('modal')) return;
    modal.setAttribute('aria-hidden', 'false');
    modal.classList.add('is-open');
    modal.classList.remove('is-closing');
    document.body.style.overflow = 'hidden';
    const firstFocus = modal.querySelector('.modal-close, [data-modal-close], .btn');
    if (firstFocus) firstFocus.focus();
  }

  function closeModal(modal) {
    const el = getModal(modal);
    if (!el?.classList.contains('modal')) return;
    el.classList.add('is-closing');
    el.classList.remove('is-open');
    setTimeout(() => {
      el.setAttribute('aria-hidden', 'true');
      el.classList.remove('is-closing');
      document.body.style.overflow = '';
    }, CLOSE_DURATION_MS);
  }

  function init() {
    document.querySelectorAll('[data-modal-open]').forEach((btn) => {
      const id = btn.getAttribute('data-modal-open');
      if (id) btn.addEventListener('click', () => openModal(id));
    });

    document.querySelectorAll('.modal').forEach((modal) => {
      modal.setAttribute('aria-hidden', 'true');
      modal.setAttribute('role', 'dialog');
      modal.setAttribute('aria-modal', 'true');

      const closeBtn = modal.querySelector('.modal-close');
      if (closeBtn) closeBtn.addEventListener('click', () => closeModal(modal));

      modal.querySelectorAll('[data-modal-close]').forEach((btn) => {
        btn.addEventListener('click', () => closeModal(modal));
      });

      const backdrop = modal.querySelector('.modal-backdrop');
      if (backdrop) backdrop.addEventListener('click', () => closeModal(modal));
    });

    document.addEventListener('keydown', (e) => {
      if (e.key !== 'Escape') return;
      const openEl = document.querySelector('.modal.is-open, .modal[aria-hidden="false"]');
      if (openEl) closeModal(openEl);
    });
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }

  window.Modal = {
    open: openModal,
    close: closeModal
  };
})();
