document.addEventListener('DOMContentLoaded', () => {
  const modal = document.getElementById('foodord-optin-modal');
  if (!modal) {
    return;
  }

  document.body.addEventListener('click', (event) => {
    const trigger = event.target.closest('.foodord-optin-modal-trigger');
    if (!trigger) {
      return;
    }

    event.preventDefault();
    if (typeof modal.showModal === 'function') {
      modal.showModal();
    }
  });

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

  modal.addEventListener('click', (event) => {
    const rect = modal.getBoundingClientRect();
    const isInDialog = (
      rect.top <= event.clientY &&
      event.clientY <= rect.top + rect.height &&
      rect.left <= event.clientX &&
      event.clientX <= rect.left + rect.width
    );

    if (!isInDialog) {
      modal.close();
    }
  });
});
