(function () {
  function post(action, data) {
    var body = new FormData();
    body.append('action', action);
    body.append('nonce', pccAdmin.nonce);
    Object.keys(data || {}).forEach(function (key) {
      var val = data[key];
      if (Array.isArray(val)) {
        val.forEach(function (v) {
          body.append(key + '[]', v);
        });
      } else {
        body.append(key, val);
      }
    });
    return fetch(pccAdmin.ajaxUrl, { method: 'POST', credentials: 'same-origin', body: body }).then(function (r) {
      return r.json();
    });
  }

  function formDataFromScanForm() {
    var form = document.getElementById('pcc-scan-form');
    if (!form) {
      return {};
    }
    var data = {};
    ['target_php', 'target_wp', 'baseline_php', 'batch_size'].forEach(function (name) {
      var el = form.querySelector('[name="' + name + '"]');
      if (el) {
        data[name] = el.value;
      }
    });
    [
      'scan_plugins',
      'scan_themes',
      'scan_parent',
      'scan_mu_plugins',
      'scan_dropins',
      'scan_active_first',
      'skip_vendor',
      'delta_mode',
      'default_delta_mode',
      'errors_only',
      'runtime_monitor',
      'auto_rescan_update',
    ].forEach(function (name) {
      var el = form.querySelector('[name="' + name + '"]');
      data[name] = el && el.checked ? '1' : '';
    });
    data.selected_plugins = [];
    form.querySelectorAll('[name="selected_plugins[]"]:checked').forEach(function (el) {
      data.selected_plugins.push(el.value);
    });
    data.selected_themes = [];
    form.querySelectorAll('[name="selected_themes[]"]:checked').forEach(function (el) {
      data.selected_themes.push(el.value);
    });
    var maxWarn = document.getElementById('pcc-max-warnings');
    if (maxWarn) {
      data.max_warnings_verdict = maxWarn.value;
    }
    var excludes = document.getElementById('pcc-custom-excludes');
    if (excludes) {
      data.custom_excludes = excludes.value;
    }
    return data;
  }

  function setProgress(pct, label) {
    var wrap = document.getElementById('pcc-progress-wrap');
    var fill = document.getElementById('pcc-progress-fill');
    var lbl = document.getElementById('pcc-progress-label');
    if (wrap) {
      wrap.hidden = false;
    }
    if (fill) {
      fill.style.width = Math.min(100, pct) + '%';
    }
    if (lbl && label) {
      lbl.textContent = label;
    }
  }

  function toggleScanButtons(state) {
    var start = document.getElementById('pcc-start-scan');
    var pause = document.getElementById('pcc-pause-scan');
    var resume = document.getElementById('pcc-resume-scan');
    var stop = document.getElementById('pcc-stop-scan');
    if (start) {
      start.disabled = state === 'running' || state === 'paused';
    }
    if (pause) {
      pause.disabled = state !== 'running';
    }
    if (resume) {
      resume.disabled = state !== 'paused';
    }
    if (stop) {
      stop.disabled = state !== 'running' && state !== 'paused';
    }
  }

  function runBatches() {
    return post('pcc_scan_batch', {}).then(function (res) {
      if (!res.success) {
        throw new Error((res.data && res.data.message) || pccAdmin.i18n.error);
      }
      var d = res.data;
      if (d.status === 'paused') {
        setProgress(d.progress || 0, pccAdmin.i18n.paused);
        toggleScanButtons('paused');
        return;
      }
      setProgress(d.progress || 0, pccAdmin.i18n.scanning + ' ' + (d.progress || 0) + '%');
      if (!d.done) {
        return runBatches();
      }
      setProgress(100, pccAdmin.i18n.complete);
      window.location.reload();
    });
  }

  var startBtn = document.getElementById('pcc-start-scan');
  if (startBtn) {
    startBtn.addEventListener('click', function () {
      startBtn.disabled = true;
      toggleScanButtons('running');
      setProgress(0, pccAdmin.i18n.scanning);
      post('pcc_start_scan', formDataFromScanForm())
        .then(function (res) {
          if (!res.success) {
            throw new Error((res.data && res.data.message) || pccAdmin.i18n.error);
          }
          return runBatches();
        })
        .catch(function (err) {
          alert(err.message || pccAdmin.i18n.error);
          startBtn.disabled = false;
          toggleScanButtons('');
        });
    });
  }

  var pauseBtn = document.getElementById('pcc-pause-scan');
  if (pauseBtn) {
    pauseBtn.addEventListener('click', function () {
      post('pcc_pause_scan', {}).then(function (res) {
        if (res.success) {
          setProgress(0, pccAdmin.i18n.paused);
          toggleScanButtons('paused');
        }
      });
    });
  }

  var resumeBtn = document.getElementById('pcc-resume-scan');
  if (resumeBtn) {
    resumeBtn.addEventListener('click', function () {
      post('pcc_resume_scan', {}).then(function (res) {
        if (res.success) {
          toggleScanButtons('running');
          setProgress(0, pccAdmin.i18n.resuming);
          runBatches();
        }
      });
    });
  }

  var stopBtn = document.getElementById('pcc-stop-scan');
  if (stopBtn) {
    stopBtn.addEventListener('click', function () {
      if (!window.confirm(pccAdmin.i18n.confirmStop)) {
        return;
      }
      post('pcc_cancel_scan', {}).then(function () {
        window.location.reload();
      });
    });
  }

  document.querySelectorAll('.pcc-fp-btn').forEach(function (btn) {
    btn.addEventListener('click', function () {
      var fp = btn.getAttribute('data-fingerprint');
      if (!fp) {
        return;
      }
      post('pcc_mark_false_positive', { fingerprint: fp }).then(function (res) {
        if (res.success) {
          var row = btn.closest('tr');
          if (row) {
            row.remove();
          }
        }
      });
    });
  });

  document.querySelectorAll('.pcc-copy-path').forEach(function (btn) {
    btn.addEventListener('click', function () {
      var code = btn.closest('tr') && btn.closest('tr').querySelector('.pcc-file-path');
      if (!code) {
        return;
      }
      var text = code.getAttribute('data-full') || code.textContent;
      if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(text).then(function () {
          btn.textContent = pccAdmin.i18n.copied;
          setTimeout(function () {
            btn.textContent = 'Copy';
          }, 1200);
        });
      }
    });
  });

  function filterFindings() {
    var searchEl = document.getElementById('pcc-findings-search');
    var sevEl = document.getElementById('pcc-findings-severity');
    var table = document.getElementById('pcc-findings-table');
    var empty = document.getElementById('pcc-findings-empty');
    if (!table) {
      return;
    }
    var q = (searchEl && searchEl.value ? searchEl.value : '').toLowerCase();
    var sev = sevEl ? sevEl.value : '';
    var visible = 0;
    table.querySelectorAll('tbody tr').forEach(function (row) {
      var matchQ = !q || (row.getAttribute('data-search') || '').indexOf(q) !== -1;
      var matchS = !sev || row.getAttribute('data-severity') === sev;
      var show = matchQ && matchS;
      row.hidden = !show;
      if (show) {
        visible++;
      }
    });
    if (empty) {
      empty.hidden = visible > 0;
    }
  }

  var searchInput = document.getElementById('pcc-findings-search');
  if (searchInput) {
    searchInput.addEventListener('input', filterFindings);
  }
  var sevSelect = document.getElementById('pcc-findings-severity');
  if (sevSelect) {
    sevSelect.addEventListener('change', filterFindings);
  }

  var printBtn = document.getElementById('pcc-print-report');
  if (printBtn) {
    printBtn.addEventListener('click', function () {
      window.print();
    });
  }

  var selectAllPlugins = document.getElementById('pcc-select-all-plugins');
  if (selectAllPlugins) {
    selectAllPlugins.addEventListener('click', function () {
      document.querySelectorAll('#pcc-plugin-checkboxes input[type="checkbox"]').forEach(function (el) {
        el.checked = true;
      });
    });
  }

  var selectActivePlugins = document.getElementById('pcc-select-active-plugins');
  if (selectActivePlugins) {
    selectActivePlugins.addEventListener('click', function () {
      document.querySelectorAll('#pcc-plugin-checkboxes label').forEach(function (label) {
        var input = label.querySelector('input[type="checkbox"]');
        if (input) {
          input.checked = label.getAttribute('data-active') === '1';
        }
      });
    });
  }

  var selectAllThemes = document.getElementById('pcc-select-all-themes');
  if (selectAllThemes) {
    selectAllThemes.addEventListener('click', function () {
      document.querySelectorAll('#pcc-theme-checkboxes input[type="checkbox"]').forEach(function (el) {
        el.checked = true;
      });
    });
  }

  var compareBtn = document.getElementById('pcc-compare-btn');
  if (compareBtn) {
    compareBtn.addEventListener('click', function () {
      var a = document.getElementById('pcc-compare-a');
      var b = document.getElementById('pcc-compare-b');
      var out = document.getElementById('pcc-compare-result');
      if (!a || !b || !out) {
        return;
      }
      post('pcc_compare_scans', { scan_a: a.value, scan_b: b.value }).then(function (res) {
        if (!res.success) {
          out.hidden = false;
          out.textContent = (res.data && res.data.message) || pccAdmin.i18n.error;
          return;
        }
        var d = res.data.delta || {};
        var html =
          '<p><strong>Δ errors:</strong> ' +
          d.errors +
          ' · <strong>Δ warnings:</strong> ' +
          d.warnings +
          '</p>';
        if (res.data.component_delta && res.data.component_delta.length) {
          html += '<table class="widefat striped"><thead><tr><th>Component</th><th>Δ errors</th><th>Δ warnings</th></tr></thead><tbody>';
          res.data.component_delta.forEach(function (row) {
            html +=
              '<tr><td>' +
              (row.label || row.id || '') +
              '</td><td>' +
              row.errors +
              '</td><td>' +
              row.warnings +
              '</td></tr>';
          });
          html += '</tbody></table>';
        }
        out.hidden = false;
        out.innerHTML = html;
      });
    });
  }

  var introToggle = document.querySelector('.pcc-intro-toggle');
  if (introToggle) {
    introToggle.addEventListener('click', function () {
      var section = document.getElementById('pcc-intro');
      var content = document.getElementById('pcc-intro-content');
      if (!section || !content) {
        return;
      }
      var collapsed = !section.classList.contains('is-collapsed');
      section.classList.toggle('is-collapsed', collapsed);
      content.hidden = collapsed;
      introToggle.setAttribute('aria-expanded', collapsed ? 'false' : 'true');
      introToggle.textContent = collapsed
        ? introToggle.getAttribute('data-label-expand')
        : introToggle.getAttribute('data-label-collapse');
      post('pcc_save_intro_collapsed', { collapsed: collapsed ? '1' : '0' });
    });
  }

  document.querySelectorAll('.pcc-info-tip').forEach(function (tip) {
    var trigger = tip.querySelector('.pcc-info-tip-trigger');
    if (!trigger) {
      return;
    }
    trigger.addEventListener('click', function (e) {
      e.stopPropagation();
      var open = tip.classList.toggle('is-open');
      trigger.setAttribute('aria-expanded', open ? 'true' : 'false');
    });
  });

  document.addEventListener('click', function (e) {
    if (!e.target.closest('.pcc-info-tip')) {
      document.querySelectorAll('.pcc-info-tip.is-open').forEach(function (tip) {
        tip.classList.remove('is-open');
        var trigger = tip.querySelector('.pcc-info-tip-trigger');
        if (trigger) {
          trigger.setAttribute('aria-expanded', 'false');
        }
      });
    }
  });

  if (pccAdmin.scanState && pccAdmin.scanState.status === 'running') {
    toggleScanButtons('running');
    var pos = parseInt(pccAdmin.scanState.position || 0, 10);
    var total = (pccAdmin.scanState.queue && pccAdmin.scanState.queue.length) || 1;
    setProgress(Math.round((pos / total) * 100), pccAdmin.i18n.resuming);
    runBatches();
  } else if (pccAdmin.scanState && pccAdmin.scanState.status === 'paused') {
    toggleScanButtons('paused');
    var posPaused = parseInt(pccAdmin.scanState.position || 0, 10);
    var totalPaused = (pccAdmin.scanState.queue && pccAdmin.scanState.queue.length) || 1;
    setProgress(Math.round((posPaused / totalPaused) * 100), pccAdmin.i18n.paused);
  }
})();
