(function () {
  'use strict';

  var mediaQuery = window.matchMedia ? window.matchMedia('(max-width: 782px)') : null;
  var activeField = null;

  function isMobile() {
    return mediaQuery ? mediaQuery.matches : window.innerWidth <= 782;
  }

  function qs(root, selector) {
    return root ? root.querySelector(selector) : null;
  }

  function cssEscape(value) {
    value = String(value || '');

    if (window.CSS && typeof window.CSS.escape === 'function') {
      return window.CSS.escape(value);
    }

    return value
      .replace(/\\/g, '\\\\')
      .replace(/"/g, '\\"')
      .replace(/[\n\r\f]/g, ' ');
  }

  function isEditableField(field) {
    if (!field || !field.matches) return false;
    if (!isMobile()) return false;
    if (!field.closest('.custausu-settings-page')) return false;
    if (field.closest('.wp-editor-wrap')) return false;
    if (field.closest('.wp-picker-container')) return false;
    if (field.closest('.custausu-rm-placement')) return false;
    if (field.closest('.custausu-rm-admin-top-wrap')) return false;
    if (field.disabled || field.readOnly) return false;
    if (field.dataset.casNoMobileOverlay === '1') return false;

    var tag = (field.tagName || '').toLowerCase();
    var type = (field.getAttribute('type') || 'text').toLowerCase();

    if (tag === 'textarea') return true;

    if (tag !== 'input') return false;

    return [
      '',
      'text',
      'url',
      'email',
      'number',
      'search',
      'tel'
    ].indexOf(type) !== -1;
  }

  function fieldLabel(field) {
    var id = field.getAttribute('id') || '';
    var label = null;

    if (id) {
      label = qs(document, 'label[for="' + cssEscape(id) + '"]');
    }

    if (!label) {
      label = field.closest('label');
    }

    if (label) {
      return (label.textContent || '').replace(/\s+/g, ' ').trim();
    }

    var row = field.closest('tr, .custausu-input-row, .custausu-card, .custausu-settings-section');
    if (row) {
      var heading = qs(row, 'th, h2, h3, h4, strong');
      if (heading) {
        return (heading.textContent || '').replace(/\s+/g, ' ').trim();
      }
    }

    var name = field.getAttribute('name') || '';
    return name ? name.replace(/^custausu_global_settings\[|\]$/g, '').replace(/[_-]+/g, ' ') : 'Edit field';
  }

  function ensureOverlay() {
    var overlay = qs(document, '.custausu-mobile-field-overlay');
    if (overlay) return overlay;

    overlay = document.createElement('div');
    overlay.className = 'custausu-mobile-field-overlay';
    overlay.innerHTML =
      '<div class="custausu-mobile-field-overlay__panel" role="dialog" aria-modal="true">' +
        '<div class="custausu-mobile-field-overlay__head">' +
          '<strong>Edit field</strong>' +
          '<button type="button" class="button custausu-mobile-field-overlay__close">Done</button>' +
        '</div>' +
        '<textarea class="custausu-mobile-field-overlay__field" rows="7"></textarea>' +
        '<p class="custausu-mobile-field-overlay__hint">Value is synced automatically with the original field.</p>' +
      '</div>';

    document.body.appendChild(overlay);
    return overlay;
  }

  function syncToOriginal(textarea) {
    if (!activeField) return;

    activeField.value = textarea.value;
    activeField.dispatchEvent(new Event('input', { bubbles: true }));
    activeField.dispatchEvent(new Event('change', { bubbles: true }));
  }

  function closeOverlay() {
    var overlay = qs(document, '.custausu-mobile-field-overlay');
    if (!overlay) return;

    overlay.classList.remove('is-open');
    document.body.classList.remove('custausu-mobile-field-overlay-open');
    activeField = null;
  }

  function openOverlay(field) {
    if (!isEditableField(field)) return;

    activeField = field;

    var overlay = ensureOverlay();
    var textarea = qs(overlay, '.custausu-mobile-field-overlay__field');
    var title = qs(overlay, '.custausu-mobile-field-overlay__head strong');

    if (!textarea || !title) return;

    title.textContent = fieldLabel(field);
    textarea.value = field.value || '';

    overlay.classList.add('is-open');
    document.body.classList.add('custausu-mobile-field-overlay-open');

    textarea.oninput = function () {
      syncToOriginal(textarea);
    };

    window.setTimeout(function () {
      try {
        textarea.focus({ preventScroll: true });
      } catch (e) {
        try { textarea.focus(); } catch (err) {}
      }

      try {
        textarea.setSelectionRange(textarea.value.length, textarea.value.length);
      } catch (e) {}
    }, 80);
  }

  document.addEventListener('focusin', function (event) {
    var field = event.target && event.target.closest
      ? event.target.closest('input, textarea')
      : null;

    if (!field || !isEditableField(field)) return;

    window.setTimeout(function () {
      if (document.activeElement === field || field.matches(':focus')) {
        openOverlay(field);
      }
    }, 80);
  });

  document.addEventListener('click', function (event) {
    var close = event.target && event.target.closest
      ? event.target.closest('.custausu-mobile-field-overlay__close')
      : null;

    if (close) {
      event.preventDefault();
      closeOverlay();
      return;
    }

    if (event.target && event.target.classList && event.target.classList.contains('custausu-mobile-field-overlay')) {
      closeOverlay();
    }
  });

  document.addEventListener('keydown', function (event) {
    if (event.key === 'Escape') {
      closeOverlay();
    }
  });
})();
