document.addEventListener('DOMContentLoaded', () => {
  const modal = document.querySelector('[data-foodord-video-modal]');
  if (!modal) {
    return;
  }

  const iframe = modal.querySelector('.foodord-admin-video-modal__frame');
  const title = modal.querySelector('.foodord-admin-video-modal__title');
  const triggers = document.querySelectorAll('[data-foodord-video-trigger]');
  const closeButtons = modal.querySelectorAll('[data-foodord-video-close]');

  if (!iframe || !title || !triggers.length) {
    return;
  }

  const closeModal = () => {
    modal.setAttribute('hidden', 'hidden');
    document.body.classList.remove('foodord-admin-video-modal-open');
    iframe.setAttribute('src', '');
    title.textContent = '';
  };

  const openModal = (button) => {
    const embedUrl = button.getAttribute('data-foodord-video-embed');
    const videoTitle = button.getAttribute('data-foodord-video-title') || '';

    if (!embedUrl) {
      return;
    }

    title.textContent = videoTitle;
    iframe.setAttribute('src', embedUrl);
    modal.removeAttribute('hidden');
    document.body.classList.add('foodord-admin-video-modal-open');
  };

  triggers.forEach((trigger) => {
    trigger.addEventListener('click', () => openModal(trigger));
  });

  closeButtons.forEach((button) => {
    button.addEventListener('click', closeModal);
  });

  document.addEventListener('keydown', (event) => {
    if ('Escape' === event.key && !modal.hasAttribute('hidden')) {
      closeModal();
    }
  });
});
