export { initModal, openModal, initModalStorybook };

function initModal(modalEl) {
  const isDialogSupported = typeof HTMLDialogElement === 'function';
  let modalWrapper = modalEl.querySelector('.ds-modal__inner');
  if (!isDialogSupported) {
    modalWrapper = modalEl;
    const modalElInner = modalEl.querySelector('.ds-modal__inner');
    const modalAttributes = Array.from(modalElInner.attributes);
    const fallbackDiv = document.createElement('div');
    modalEl.classList.add('ds-modal--hidden', 'ds-modal--fallback');
    modalAttributes.forEach((attr) => {
      fallbackDiv.setAttribute(attr.name, attr.value);
    });
    fallbackDiv.setAttribute('role', 'dialog');
    fallbackDiv.setAttribute('aria-modal', 'true');
    fallbackDiv.innerHTML = modalElInner.innerHTML;
    modalEl.replaceChild(fallbackDiv, modalElInner);
  }

  modalEl.addEventListener('click', (e) => {
    if (e.target === modalEl.querySelector('.ds-modal__inner')) closeModal(modalEl, isDialogSupported);
  });

  const closeButtons = Array.from(modalEl.getElementsByClassName('ds-modal__close'));
  closeButtons.forEach((button) => {
    button.addEventListener('click', () => {
      closeModal(modalEl, isDialogSupported);
    });
  });
}

function openModal(modalEl) {
  if (typeof HTMLDialogElement === 'function') {
    const modalElInner = modalEl.querySelector('.ds-modal__inner');
    modalElInner.showModal();
    modalElInner.focus(); // Ensure the modal is focused when opened and not a button/link within it
  } else {
    modalEl.classList.remove('ds-modal--hidden');
    document.body.classList.add('no-scroll');
  }
}

function closeModal(modalEl, isDialogSupported) {
  if (isDialogSupported) {
    const modalElInner = modalEl.querySelector('.ds-modal__inner');
    modalElInner.close();
  } else {
    modalEl.classList.add('ds-modal--hidden');
    document.body.classList.remove('no-scroll');
  }
}

function initModalStorybook() {
  const modalEl = document.querySelector('.ds-modal');
  initModal(modalEl);
  openModal(modalEl);
}
