(function () {
  if (!window.ABTESTKIT_DELETE_REASON) return;

  var cfg = window.ABTESTKIT_DELETE_REASON;
  if (!cfg.pluginBase || !cfg.rest || !cfg.nonce) return;

  function escapeHtml(str) {
    return String(str || '').replace(/[&<>"']/g, function (m) {
      return ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' })[m];
    });
  }

  function getQueryParam(href, key) {
    if (!href) return '';
    var re = new RegExp('[?&]' + key + '=([^&#]*)');
    var m = re.exec(href);
    return m ? m[1] : '';
  }

  function decodeParam(v) {
    v = String(v || '').replace(/\+/g, ' ');
    try { return decodeURIComponent(v); } catch (e) { return v; }
  }

  function isOurDeactivateLink(link) {
    if (!link) return false;
    var href = link.getAttribute('href') || '';
    var pluginParam = decodeParam(getQueryParam(href, 'plugin'));
    if (!pluginParam) return false;
    return pluginParam === cfg.pluginBase;
  }

  function findDeactivateLinkFromEventTarget(target) {
    if (!target) return null;

    if (target.nodeType === 3 && target.parentElement) target = target.parentElement;
    if (!target.closest) return null;

    var link = target.closest('a');
    if (!link) {
      var wrap = target.closest('span.deactivate');
      if (wrap) link = wrap.querySelector('a');
    }
    if (!link) return null;

    var href = link.getAttribute('href') || '';
    if (href.indexOf('action=deactivate') === -1) return null;

    return isOurDeactivateLink(link) ? link : null;
  }

  function injectStyles() {
    if (document.getElementById('abtestkit-delete-reason-styles')) return;

    var css = document.createElement('style');
    css.id = 'abtestkit-delete-reason-styles';
    css.textContent =
      '#abtestkit-delete-reason-modal{position:fixed;inset:0;z-index:100000;display:flex;align-items:center;justify-content:center;padding:12px;box-sizing:border-box;}' +
      '#abtestkit-delete-reason-modal .abtestkit-delete-reason-backdrop{position:absolute;inset:0;background:rgba(0,0,0,.45);}' +
      '#abtestkit-delete-reason-modal .abtestkit-delete-reason-box{position:relative;background:#fff;width:100%;max-width:520px;max-height:calc(100vh - 24px);overflow:auto;padding:14px 14px 12px;border-radius:8px;box-shadow:0 10px 30px rgba(0,0,0,.2);box-sizing:border-box;}' +
      '#abtestkit-delete-reason-modal h2{margin:0 0 8px;font-size:20px;line-height:1.25;}' +
      '#abtestkit-delete-reason-modal .abtk-label{margin:0 0 8px;font-weight:600;font-size:13px;}' +
      '#abtestkit-delete-reason-modal .abtk-help{margin:0 0 4px;color:#646970;font-size:12px;}' +
      '#abtestkit-delete-reason-modal .abtk-radios{display:flex;flex-direction:column;gap:8px;margin-top:6px;}' +
      '#abtestkit-delete-reason-modal .abtk-radio{display:flex;align-items:flex-start;gap:8px;padding:8px 10px;border:1px solid #dcdcde;border-radius:6px;cursor:pointer;}' +
      '#abtestkit-delete-reason-modal .abtk-radio input{margin:2px 0 0;flex:0 0 auto;}' +
      '#abtestkit-delete-reason-modal .abtk-radio span{display:block;line-height:1.35;font-size:13px;}' +
      '#abtestkit-delete-reason-modal .abtk-input{width:100%;max-width:100%;height:34px;padding:0 10px;border:1px solid #8c8f94;border-radius:4px;box-sizing:border-box;}' +
      '#abtestkit-delete-reason-modal .abtk-footer{display:flex;justify-content:space-between;align-items:flex-end;gap:12px;margin-top:14px;padding-top:4px;}' +
      '#abtestkit-delete-reason-modal .abtk-actions{display:flex;gap:8px;justify-content:flex-end;flex-wrap:wrap;}' +
      '#abtestkit-delete-reason-modal .abtk-skip{font-size:12px;text-decoration:underline;color:#646970;align-self:flex-end;}' +
      '#abtestkit-delete-reason-modal .abtk-skip:hover{color:#135e96;}' +
      '#abtestkit-delete-reason-modal #abtestkit-delete-reason-confirm[disabled]{opacity:.55;cursor:not-allowed;}' +
      '@media (max-width:600px){' +
        '#abtestkit-delete-reason-modal{align-items:flex-start;}' +
        '#abtestkit-delete-reason-modal .abtk-footer{flex-direction:column;align-items:stretch;gap:10px;}' +
        '#abtestkit-delete-reason-modal .abtk-actions{justify-content:stretch;}' +
        '#abtestkit-delete-reason-modal .abtk-actions .button{flex:1;}' +
        '#abtestkit-delete-reason-modal .abtk-skip{align-self:flex-start;}' +
      '}';
    document.head.appendChild(css);
  }

  function buildModal() {
    var overlay = document.createElement('div');
    overlay.id = 'abtestkit-delete-reason-modal';

    var options = Array.isArray(cfg.options) ? cfg.options : [];
    var radiosHtml = '';
    for (var i = 0; i < options.length; i++) {
      radiosHtml +=
        '<label class="abtk-radio">' +
          '<input type="radio" name="abtestkit_delete_reason" value="' + escapeHtml(options[i].value) + '">' +
          '<span>' + escapeHtml(options[i].label) + '</span>' +
        '</label>';
    }

    overlay.innerHTML =
      '<div class="abtestkit-delete-reason-backdrop"></div>' +
      '<div class="abtestkit-delete-reason-box" role="dialog" aria-modal="true" aria-labelledby="abtestkit-delete-reason-title">' +
        '<h2 id="abtestkit-delete-reason-title">' + escapeHtml(cfg.title) + '</h2>' +

        '<p class="abtk-label">' + escapeHtml(cfg.label) + '</p>' +
        '<div class="abtk-radios">' + radiosHtml + '</div>' +

        '<p class="abtk-label" style="margin-top:14px;">' + escapeHtml(cfg.detailLabel) + '</p>' +
        '<p class="abtk-help">Optional</p>' +
        '<input type="text" id="abtestkit-delete-reason-detail" class="abtk-input" maxlength="255">' +

        '<p id="abtestkit-delete-reason-error" style="color:#b32d2e;display:none;margin:10px 0 0;"></p>' +

        '<div class="abtk-footer">' +
          '<a href="#" id="abtestkit-delete-reason-skip" class="abtk-skip">' + escapeHtml(cfg.skipText) + '</a>' +
          '<div class="abtk-actions">' +
            '<button type="button" class="button" id="abtestkit-delete-reason-cancel">' + escapeHtml(cfg.cancelText) + '</button>' +
            '<button type="button" class="button button-primary" id="abtestkit-delete-reason-confirm" disabled>' + escapeHtml(cfg.confirmText) + '</button>' +
          '</div>' +
        '</div>' +
      '</div>';

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

  function closeModal(modal) {
    if (modal && modal.parentNode) modal.parentNode.removeChild(modal);
  }

  // SAFE: posts to same-origin WP REST route with nonce (your PHP then sends telemetry server-side).
  function postReason(reason, detail) {
    return fetch(cfg.rest, {
      method: 'POST',
      credentials: 'same-origin',
      headers: {
        'Content-Type': 'application/json',
        'X-WP-Nonce': cfg.nonce
      },
      body: JSON.stringify({ reason: reason, detail: detail })
    }).catch(function () {});
  }

  function openModalForLink(link) {
    if (document.getElementById('abtestkit-delete-reason-modal')) return;

    var modal = buildModal();
    var detail = modal.querySelector('#abtestkit-delete-reason-detail');
    var error = modal.querySelector('#abtestkit-delete-reason-error');
    var cancel = modal.querySelector('#abtestkit-delete-reason-cancel');
    var skip = modal.querySelector('#abtestkit-delete-reason-skip');
    var confirm = modal.querySelector('#abtestkit-delete-reason-confirm');
    var radios = modal.querySelectorAll('input[name="abtestkit_delete_reason"]');

    function getSelectedReason() {
      for (var i = 0; i < radios.length; i++) {
        if (radios[i].checked) return (radios[i].value || '').trim();
      }
      return '';
    }

    function updateConfirmState() {
      var hasReason = !!getSelectedReason();
      confirm.disabled = !hasReason;
      if (hasReason) {
        error.style.display = 'none';
        error.textContent = '';
      }
    }

    for (var i = 0; i < radios.length; i++) {
      radios[i].addEventListener('change', updateConfirmState);
    }

    cancel.addEventListener('click', function () {
      closeModal(modal);
    });

    // Skip = no feedback => do NOT ping anything
    skip.addEventListener('click', function (e) {
      e.preventDefault();
      window.location.href = link.href;
    });

    confirm.addEventListener('click', function () {
      var reason = getSelectedReason();
      var extra = (detail.value || '').trim();

      if (!reason) {
        error.style.display = 'block';
        error.textContent = cfg.requiredText;
        confirm.disabled = true;
        return;
      }

      confirm.disabled = true;
      cancel.disabled = true;
      skip.style.pointerEvents = 'none';
      skip.style.opacity = '0.6';

      postReason(reason, extra).then(function () {
        window.location.href = link.href;
      });
    });

    updateConfirmState();
  }

  function init() {
    injectStyles();

    document.addEventListener('click', function (e) {
      var link = findDeactivateLinkFromEventTarget(e.target);
      if (!link) return;

      e.preventDefault();
      e.stopPropagation();
      if (typeof e.stopImmediatePropagation === 'function') e.stopImmediatePropagation();

      openModalForLink(link);
    }, true);
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();