(function () {
  'use strict';

  const root = document.querySelector('.wrc-pwa-container');
  if (!root) {
    return;
  }

  const enabledInput = root.querySelector('#foodord_pwa_enabled');
  const settings = root.querySelector('[data-foodord-pwa-settings]');
  const labels = window.foodordPwaSettings || {};

  const updateEnabledState = () => {
    settings?.classList.toggle('is-disabled', !enabledInput?.checked);
  };

  enabledInput?.addEventListener('change', updateEnabledState);
  updateEnabledState();

  root.querySelectorAll('[data-foodord-pwa-icon-field]').forEach((field) => {
    const input = field.querySelector('[data-foodord-pwa-icon-input]');
    const preview = field.querySelector('[data-foodord-pwa-icon-preview]');
    const previewTrigger = field.querySelector('[data-foodord-pwa-preview-trigger]');
    const selectButton = field.querySelector('[data-foodord-pwa-select-icon]');
    const removeButton = field.querySelector('[data-foodord-pwa-remove-icon]');
    let mediaFrame = null;

    const openMediaLibrary = () => {
      if (!window.wp?.media) {
        return;
      }

      if (!mediaFrame) {
        mediaFrame = window.wp.media({
          title: labels.mediaTitle || 'Select app icon',
          button: { text: labels.mediaButton || 'Use this image' },
          library: { type: 'image' },
          multiple: false
        });

        mediaFrame.on('select', () => {
          const attachment = mediaFrame.state().get('selection').first()?.toJSON();
          if (!attachment || !input || !preview) {
            return;
          }

          const source = attachment.sizes?.thumbnail?.url || attachment.url || '';
          input.value = String(attachment.id || '');
          preview.replaceChildren();

          if (source) {
            const image = document.createElement('img');
            image.src = source;
            image.alt = '';
            preview.appendChild(image);
          }

          if (removeButton) {
            removeButton.hidden = false;
          }
        });
      }

      mediaFrame.open();
    };

    previewTrigger?.addEventListener('click', openMediaLibrary);
    selectButton?.addEventListener('click', openMediaLibrary);

    removeButton?.addEventListener('click', () => {
      if (!input || !preview) {
        return;
      }

      input.value = '';
      preview.replaceChildren();
      const placeholder = document.createElement('span');
      placeholder.setAttribute('aria-hidden', 'true');
      placeholder.textContent = '+';
      preview.appendChild(placeholder);
      removeButton.hidden = true;
    });
  });
})();
