(function () {
  var root = document.querySelector('[data-shieldx-admin]');

  if (!root) {
    return;
  }

  root.dataset.ready = 'true';

  var wpI18n = window.wp && window.wp.i18n ? window.wp.i18n : null;

  function __(text) {
    return wpI18n && typeof wpI18n.__ === 'function' ? wpI18n.__(text, 'xerotact-shield-x-security') : text;
  }

  function sprintf(template) {
    var args = Array.prototype.slice.call(arguments, 1);

    if (wpI18n && typeof wpI18n.sprintf === 'function') {
      return wpI18n.sprintf.apply(wpI18n, [template].concat(args));
    }

    return String(template).replace(/%[sd]/g, function () {
      return String(args.shift());
    });
  }

  function onNextFrame(callback) {
    if (window.requestAnimationFrame) {
      window.requestAnimationFrame(callback);
      return;
    }

    window.setTimeout(callback, 0);
  }

  function replaceServerHtml(container, html) {
    var template;

    if (!container || typeof html !== 'string') {
      return;
    }

    template = document.createElement('template');
    template.innerHTML = html;
    container.replaceChildren(template.content);
  }

  function toastQueryKeys() {
    var raw = root.getAttribute('data-shieldx-toast-query-keys') || '[]';

    try {
      var parsed = JSON.parse(raw);
      return Array.isArray(parsed) ? parsed.filter(function (key) {
        return typeof key === 'string' && key.indexOf('shieldx_') === 0;
      }) : [];
    } catch (error) {
      return [];
    }
  }

  function cleanToastQueryString() {
    var keys = toastQueryKeys();
    var url;
    var changed = false;

    if (!keys.length || !window.URL || !window.history || !window.history.replaceState) {
      return;
    }

    try {
      url = new URL(window.location.href);
    } catch (error) {
      return;
    }

    keys.forEach(function (key) {
      if (url.searchParams.has(key)) {
        url.searchParams.delete(key);
        changed = true;
      }
    });

    if (changed) {
      window.history.replaceState(null, '', url.pathname + url.search + url.hash);
    }
  }

  function pageLevelNotices() {
    var scope = root.closest('.shieldx-admin') || root;

    return Array.prototype.slice.call(scope.querySelectorAll('.notice')).filter(function (notice) {
      return !notice.closest('.shieldx-toast-stack') &&
        !notice.closest('.shieldx-panel') &&
        !notice.closest('.shieldx-form-modal') &&
        !notice.closest('.shieldx-modal') &&
        !notice.closest('.shieldx-scan-modal');
    });
  }

  function initToastNotices() {
    var notices = pageLevelNotices();
    var stack = root.querySelector('.shieldx-toast-stack');

    cleanToastQueryString();

    if (!notices.length) {
      return;
    }

    if (!stack) {
      stack = document.createElement('div');
      stack.className = 'shieldx-toast-stack';
      stack.setAttribute('aria-live', 'polite');
      stack.setAttribute('aria-relevant', 'additions text');
      root.appendChild(stack);
    }

    notices.forEach(function (notice) {
      notice.classList.add('shieldx-toast');
      if (!notice.getAttribute('role')) {
        notice.setAttribute('role', notice.classList.contains('notice-error') ? 'alert' : 'status');
      }
      stack.appendChild(notice);
    });
  }

  function observeToastNotices() {
    var scope = root.closest('.shieldx-admin') || root;
    var scheduled = false;
    var observer;

    if (!window.MutationObserver || !scope) {
      return;
    }

    observer = new window.MutationObserver(function (mutations) {
      var shouldRun = false;

      mutations.forEach(function (mutation) {
        if (mutation.target && mutation.target.closest && mutation.target.closest('.shieldx-toast-stack')) {
          return;
        }

        shouldRun = true;
      });

      if (!shouldRun || scheduled) {
        return;
      }

      scheduled = true;
      window.setTimeout(function () {
        scheduled = false;
        initToastNotices();
      }, 0);
    });

    observer.observe(scope, {
      childList: true,
      subtree: true
    });
  }

  onNextFrame(initToastNotices);
  window.setTimeout(initToastNotices, 150);
  window.setTimeout(initToastNotices, 500);
  window.setTimeout(initToastNotices, 1000);

  if (document.readyState === 'complete') {
    window.setTimeout(initToastNotices, 300);
  } else {
    window.addEventListener('load', function () {
      window.setTimeout(initToastNotices, 150);
    }, { once: true });
  }

  observeToastNotices();

  function initAutoRedirects() {
    root.querySelectorAll('[data-shieldx-auto-redirect-url]').forEach(function (node) {
      var url = node.getAttribute('data-shieldx-auto-redirect-url') || '';
      var delay = parseInt(node.getAttribute('data-shieldx-auto-redirect-delay') || '750', 10);

      if (!url || node.getAttribute('data-shieldx-auto-redirect-ready') === '1') {
        return;
      }

      node.setAttribute('data-shieldx-auto-redirect-ready', '1');
      window.setTimeout(function () {
        window.location.href = url;
      }, Math.max(100, Math.min(5000, delay || 750)));
    });
  }

  initAutoRedirects();

  function initDashboardWidgetContent() {
    root.querySelectorAll('[data-shieldx-dashboard-widget-content]').forEach(function (container) {
      var url = container.getAttribute('data-shieldx-dashboard-widget-url') || '';
      var nonce = container.getAttribute('data-shieldx-dashboard-widget-nonce') || '';
      var postbox = container.closest('.postbox');
      var observer;
      var requested = false;

      function canLoad() {
        return !postbox || !postbox.classList.contains('closed');
      }

      function renderError() {
        var message = container.getAttribute('data-shieldx-dashboard-widget-error') || __('SHIELD-X could not load security trends.');
        var notice = document.createElement('p');

        notice.className = 'shieldx-empty';
        notice.textContent = message;
        container.innerHTML = '';
        container.appendChild(notice);
      }

      function load() {
        var formData;

        if (requested || !canLoad() || !url || !nonce || !window.FormData || !window.fetch) {
          return;
        }

        requested = true;
        formData = new window.FormData();
        formData.append('action', 'shieldx_dashboard_overview');
        formData.append('_ajax_nonce', nonce);

        window.fetch(url, {
          method: 'POST',
          credentials: 'same-origin',
          body: formData
        }).then(function (response) {
          return response.json().then(function (payload) {
            if (!response.ok || !payload || !payload.success || !payload.data || typeof payload.data.html !== 'string') {
              throw new Error(__('Invalid SHIELD-X dashboard response'));
            }

            return payload.data.html;
          });
        }).then(function (html) {
          replaceServerHtml(container, html);
          initInsertedAdminContent(container);
        }).catch(renderError);
      }

      if (container.getAttribute('data-shieldx-dashboard-widget-ready') === '1') {
        return;
      }

      container.setAttribute('data-shieldx-dashboard-widget-ready', '1');

      if (window.IntersectionObserver) {
        observer = new window.IntersectionObserver(function (entries) {
          entries.forEach(function (entry) {
            if (!entry.isIntersecting) {
              return;
            }

            observer.disconnect();
            load();
          });
        });
        observer.observe(container);
      } else {
        onNextFrame(load);
      }

      document.addEventListener('click', function (event) {
        var toggle = event.target.closest('.hndle, .handlediv');

        if (!toggle || !postbox || !postbox.contains(toggle)) {
          return;
        }

        window.setTimeout(load, 0);
      });
    });
  }

  initDashboardWidgetContent();

  root.querySelectorAll('details.shieldx-accordion-panel:not([data-shieldx-accordion-open])').forEach(function (panel) {
    panel.open = false;
  });

  function hashTarget() {
    var hash = window.location.hash || '';

    if (hash.charAt(0) !== '#') {
      return null;
    }

    hash = hash.slice(1);

    if (!hash) {
      return null;
    }

    try {
      hash = window.decodeURIComponent(hash);
    } catch (error) {
      return null;
    }

    return document.getElementById(hash);
  }

  function directChildByClass(parent, className) {
    for (var index = 0; index < parent.children.length; index += 1) {
      if (parent.children[index].classList.contains(className)) {
        return parent.children[index];
      }
    }

    return null;
  }

  function isAccordionHeaderInteractiveTarget(target, toggle) {
    var interactiveSelector = 'a, button, input, select, textarea, label, summary, [role="button"], [data-shieldx-no-accordion-toggle]';

    if (!target || target === toggle || toggle.contains(target)) {
      return false;
    }

    return !!target.closest(interactiveSelector);
  }

  function initSectionAccordions() {
    var panels = root.querySelectorAll('.shieldx-layout > section.shieldx-panel, .shieldx-layout > .shieldx-system-side-stack > section.shieldx-panel');
    var initialized = [];

    panels.forEach(function (panel) {
      var head;
      var body;
      var toggle;
      var target;

      if (
        panel.classList.contains('shieldx-accordion-panel') ||
        panel.classList.contains('shieldx-js-accordion-panel') ||
        panel.classList.contains('shieldx-setup-hero') ||
        panel.classList.contains('shieldx-setup-progress') ||
        panel.hasAttribute('data-shieldx-scan-panel') ||
        panel.hasAttribute('data-shieldx-accordion-skip')
      ) {
        return;
      }

      head = directChildByClass(panel, 'shieldx-section-head');

      if (!head) {
        return;
      }

      body = document.createElement('div');
      body.className = 'shieldx-js-accordion-body';

      while (head.nextSibling) {
        body.appendChild(head.nextSibling);
      }

      toggle = document.createElement('button');
      toggle.type = 'button';
      toggle.className = 'shieldx-accordion-toggle';
      toggle.setAttribute('aria-label', __('Toggle section'));
      toggle.setAttribute('aria-expanded', 'false');

      head.appendChild(toggle);
      panel.appendChild(body);
      panel.classList.add('shieldx-js-accordion-panel');

      function setOpen(open) {
        panel.classList.toggle('is-open', open);
        body.hidden = !open;
        toggle.setAttribute('aria-expanded', open ? 'true' : 'false');

        if (open && typeof equalizeScopeGridCards === 'function') {
          onNextFrame(equalizeScopeGridCards);
        }
      }

      target = hashTarget();
      setOpen(!!(target && (target === panel || panel.contains(target))) || panel.hasAttribute('data-shieldx-accordion-open'));

      function togglePanel() {
        setOpen(!panel.classList.contains('is-open'));
      }

      toggle.addEventListener('click', function (event) {
        event.stopPropagation();
        togglePanel();
      });

      head.addEventListener('click', function (event) {
        if (isAccordionHeaderInteractiveTarget(event.target, toggle)) {
          return;
        }

        togglePanel();
      });

      initialized.push({
        panel: panel,
        setOpen: setOpen
      });
    });

    if (!initialized.length) {
      return;
    }

    window.addEventListener('hashchange', function () {
      var target = hashTarget();

      if (!target) {
        return;
      }

      initialized.forEach(function (item) {
        if (target === item.panel || item.panel.contains(target)) {
          item.setOpen(true);
        }
      });
    });
  }

  initSectionAccordions();

  function equalizeScopeGridCards() {
    root.querySelectorAll('.shieldx-scope-grid').forEach(function (grid) {
      var cards = Array.prototype.slice.call(grid.querySelectorAll('.shieldx-scope-card'));
      var maxHeight = 0;

      if (!cards.length) {
        return;
      }

      cards.forEach(function (card) {
        card.style.minHeight = '';
      });

      if (grid.offsetParent === null) {
        return;
      }

      cards.forEach(function (card) {
        maxHeight = Math.max(maxHeight, Math.ceil(card.getBoundingClientRect().height));
      });

      if (maxHeight <= 0) {
        return;
      }

      cards.forEach(function (card) {
        card.style.minHeight = maxHeight + 'px';
      });
    });
  }

  equalizeScopeGridCards();
  window.addEventListener('resize', equalizeScopeGridCards);

  function initMetricTitles(scope) {
    (scope || root).querySelectorAll('.shieldx-metric strong').forEach(function (metric) {
      metric.setAttribute('title', metric.textContent.trim());
    });
  }

  initMetricTitles(root);

  function initOverviewCharts() {
    root.querySelectorAll('[data-shieldx-overview-chart]').forEach(function (chart) {
      var control = chart.querySelector('[data-shieldx-chart-control]');
      var toggle;
      var menu;
      var summary;
      var message;
      var options;
      var maxSelected;
      var rangeSelect;
      var groupSelect;

      if (chart.getAttribute('data-shieldx-chart-ready') === '1') {
        return;
      }

      rangeSelect = chart.querySelector('[data-shieldx-chart-range-select]');
      groupSelect = chart.querySelector('[data-shieldx-chart-group-select]');

      if (!control) {
        if (!rangeSelect && !groupSelect) {
            return;
        }

        chart.setAttribute('data-shieldx-chart-ready', '1');

        function syncRangeOnly() {
          if (!rangeSelect) {
            return;
          }

          var range = rangeSelect.value || 'daily';

          chart.querySelectorAll('[data-shieldx-chart-range-panel]').forEach(function (node) {
            node.classList.toggle('is-hidden', node.getAttribute('data-shieldx-chart-range-panel') !== range);
          });

          chart.querySelectorAll('[data-shieldx-chart-range-summary]').forEach(function (node) {
            node.classList.toggle('is-hidden', node.getAttribute('data-shieldx-chart-range-summary') !== range);
          });
        }

        function syncGroupOnly() {
          if (!groupSelect) {
            return;
          }

          var group = groupSelect.value || 'action';

          chart.querySelectorAll('[data-shieldx-chart-series-group]').forEach(function (node) {
            var seriesGroup = node.getAttribute('data-shieldx-chart-series-group') || '';
            node.classList.toggle('is-hidden', seriesGroup !== 'baseline' && seriesGroup !== group);
          });
        }

        syncRangeOnly();
        syncGroupOnly();
        if (rangeSelect) {
          rangeSelect.addEventListener('change', syncRangeOnly);
        }
        if (groupSelect) {
          groupSelect.addEventListener('change', syncGroupOnly);
        }
        return;
      }

      toggle = control.querySelector('[data-shieldx-chart-toggle]');
      menu = control.querySelector('[data-shieldx-chart-menu]');
      summary = control.querySelector('[data-shieldx-chart-summary]');
      message = control.querySelector('[data-shieldx-chart-message]');
      options = Array.prototype.slice.call(control.querySelectorAll('[data-shieldx-chart-option]'));
      maxSelected = parseInt(chart.getAttribute('data-shieldx-chart-max') || '5', 10);
      if (!toggle || !menu || !options.length) {
        return;
      }

      chart.setAttribute('data-shieldx-chart-ready', '1');

      if (!maxSelected || maxSelected < 1) {
        maxSelected = 5;
      }

      function selectedValues() {
        return options.filter(function (option) {
          return option.checked;
        }).map(function (option) {
          return option.value;
        });
      }

      function setMenuOpen(open) {
        menu.hidden = !open;
        toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
      }

      function setSeriesVisible(key, visible) {
        chart.querySelectorAll('[data-shieldx-chart-series="' + key + '"]').forEach(function (node) {
          node.classList.toggle('is-hidden', !visible);
        });

        chart.querySelectorAll('[data-shieldx-chart-legend="' + key + '"]').forEach(function (node) {
          node.classList.toggle('is-hidden', !visible);
        });

        chart.querySelectorAll('[data-shieldx-chart-summary-card="' + key + '"]').forEach(function (node) {
          node.classList.toggle('is-hidden', !visible);
        });
      }

      function syncRange() {
        var range = rangeSelect ? rangeSelect.value : 'daily';

        chart.querySelectorAll('[data-shieldx-chart-range-panel]').forEach(function (node) {
          node.classList.toggle('is-hidden', node.getAttribute('data-shieldx-chart-range-panel') !== range);
        });

        chart.querySelectorAll('[data-shieldx-chart-range-summary]').forEach(function (node) {
          node.classList.toggle('is-hidden', node.getAttribute('data-shieldx-chart-range-summary') !== range);
        });
      }

      function syncChart() {
        var selected = selectedValues();
        var selectedMap = {};

        if (!selected.length) {
          options[0].checked = true;
          selected = selectedValues();
        }

        selected.forEach(function (key) {
          selectedMap[key] = true;
        });

        options.forEach(function (option) {
          setSeriesVisible(option.value, !!selectedMap[option.value]);
          option.disabled = !option.checked && selected.length >= maxSelected;
        });

        if (summary) {
          summary.textContent = sprintf(__('%d selected'), selected.length);
        }
      }

      if (rangeSelect) {
        rangeSelect.addEventListener('change', syncRange);
      }

      options.forEach(function (option) {
        option.addEventListener('change', function () {
          if (selectedValues().length > maxSelected) {
            option.checked = false;
            if (message) {
              message.hidden = false;
            }
          } else if (message) {
            message.hidden = true;
          }

          syncChart();
        });
      });

      toggle.addEventListener('click', function (event) {
        event.stopPropagation();
        setMenuOpen(menu.hidden);
      });

      control.addEventListener('keydown', function (event) {
        if (event.key === 'Escape') {
          setMenuOpen(false);
          toggle.focus();
        }
      });

      document.addEventListener('click', function (event) {
        if (!control.contains(event.target)) {
          setMenuOpen(false);
        }
      });

      syncChart();
      syncRange();
    });
  }

  initOverviewCharts();

  function overviewCardTitle(card) {
    var label = card ? card.querySelector('.shieldx-metric-head > span:not(.shieldx-metric-icon)') : null;

    return label ? label.textContent.trim() : __('overview');
  }

  function syncOverviewDisabledState(container) {
    var section = container.parentNode ? container.parentNode.querySelector('[data-shieldx-overview-disabled-section]') : null;
    var grid = section ? section.querySelector('[data-shieldx-overview-disabled-grid]') : null;
    var button = section ? section.querySelector('[data-shieldx-overview-show-disabled]') : null;
    var scoreSlot = container.querySelector('[data-shieldx-overview-score-slot]');
    var disabledCount = grid ? grid.querySelectorAll('[data-shieldx-overview-card]').length : 0;

    if (section) {
      section.hidden = disabledCount < 1;
    }

    if (grid && disabledCount < 1) {
      grid.hidden = true;
    }

    if (button && disabledCount < 1) {
      button.setAttribute('aria-expanded', 'false');
      button.textContent = __('Show all');
    }

    if (scoreSlot) {
      scoreSlot.hidden = scoreSlot.querySelector('[data-shieldx-overview-card]') === null;
      container.classList.toggle('shieldx-overview-attention--no-score', scoreSlot.hidden);
    }
  }

  function updateOverviewCardToggle(card, disabled) {
    var button = card.querySelector('[data-shieldx-overview-card-toggle]');
    var text = button ? button.querySelector('.shieldx-screen-reader-text') : null;
    var title = overviewCardTitle(card);

    card.classList.toggle('is-disabled', disabled);
    card.setAttribute('data-shieldx-overview-card-disabled', disabled ? '1' : '0');

    if (button) {
      button.setAttribute('aria-pressed', disabled ? 'true' : 'false');
    }

    if (text) {
      text.textContent = disabled ? sprintf(__('Enable %s overview card'), title) : sprintf(__('Disable %s overview card'), title);
    }
  }

  function moveOverviewCard(container, card, disabled) {
    var section = container.parentNode ? container.parentNode.querySelector('[data-shieldx-overview-disabled-section]') : null;
    var disabledGrid = section ? section.querySelector('[data-shieldx-overview-disabled-grid]') : null;
    var visibleGrid = container.querySelector('[data-shieldx-overview-visible-grid]');
    var scoreSlot = container.querySelector('[data-shieldx-overview-score-slot]');
    var isSummary = card.getAttribute('data-shieldx-overview-card-summary') === '1';

    updateOverviewCardToggle(card, disabled);

    if (disabled && disabledGrid) {
      disabledGrid.appendChild(card);
    } else if (isSummary && scoreSlot) {
      scoreSlot.appendChild(card);
    } else if (visibleGrid) {
      visibleGrid.appendChild(card);
    }

    syncOverviewDisabledState(container);
  }

  function saveOverviewCardState(container, cardId, disabled) {
    var url = container.getAttribute('data-shieldx-overview-card-url') || '';
    var nonce = container.getAttribute('data-shieldx-overview-card-nonce') || '';
    var formData;

    if (!url || !nonce || !cardId || !window.FormData || !window.fetch) {
      return Promise.reject(new Error('missing-overview-card-transport'));
    }

    formData = new window.FormData();
    formData.append('action', 'shieldx_overview_card_visibility');
    formData.append('_ajax_nonce', nonce);
    formData.append('card_id', cardId);
    formData.append('disabled', disabled ? '1' : '0');

    return window.fetch(url, {
      method: 'POST',
      credentials: 'same-origin',
      body: formData
    }).then(function (response) {
      return response.json().then(function (payload) {
        if (!response.ok || !payload || !payload.success) {
          throw new Error('overview-card-save-failed');
        }

        return payload;
      });
    });
  }

  function initOverviewCards(scope) {
    (scope || root).querySelectorAll('[data-shieldx-overview-cards]:not([data-shieldx-overview-cards-ready])').forEach(function (container) {
      var disabledSection = container.parentNode ? container.parentNode.querySelector('[data-shieldx-overview-disabled-section]') : null;
      var showAll = disabledSection ? disabledSection.querySelector('[data-shieldx-overview-show-disabled]') : null;
      var disabledGrid = disabledSection ? disabledSection.querySelector('[data-shieldx-overview-disabled-grid]') : null;

      container.setAttribute('data-shieldx-overview-cards-ready', '1');

      function handleCardToggle(event) {
        var button = event.target.closest ? event.target.closest('[data-shieldx-overview-card-toggle]') : null;
        var card;
        var cardId;
        var disabled;

        if (!button || (!container.contains(button) && (!disabledSection || !disabledSection.contains(button)))) {
          return;
        }

        event.preventDefault();
        card = button.closest('[data-shieldx-overview-card]');
        if (!card) {
          return;
        }

        cardId = card.getAttribute('data-shieldx-overview-card-id') || '';
        if (cardId === 'needs_attention' || card.getAttribute('data-shieldx-overview-card-summary') === '1') {
          return;
        }

        disabled = card.getAttribute('data-shieldx-overview-card-disabled') !== '1';
        button.disabled = true;
        moveOverviewCard(container, card, disabled);

        saveOverviewCardState(container, cardId, disabled).catch(function () {
          moveOverviewCard(container, card, !disabled);
          window.alert(__('Could not save overview card preference.'));
        }).then(function () {
          button.disabled = false;
        });
      }

      container.addEventListener('click', handleCardToggle);
      if (disabledSection) {
        disabledSection.addEventListener('click', handleCardToggle);
      }

      if (showAll && disabledGrid) {
        showAll.addEventListener('click', function () {
          var expanded = disabledGrid.hidden;

          disabledGrid.hidden = !expanded;
          showAll.setAttribute('aria-expanded', expanded ? 'true' : 'false');
          showAll.textContent = expanded ? __('Hide') : __('Show all');
        });
      }

      syncOverviewDisabledState(container);
    });
  }

  initOverviewCards(root);

  function renderAdminPageError(container, retry) {
    var section = document.createElement('section');
    var message = document.createElement('p');
    var retryButton;

    section.className = 'shieldx-panel shieldx-panel--full shieldx-overview-loading';
    section.setAttribute('aria-live', 'polite');
    message.className = 'shieldx-empty';
    message.textContent = container.getAttribute('data-shieldx-admin-page-error') || __('SHIELD-X could not load this page. Try again or reload the page.');
    section.appendChild(message);

    if (typeof retry === 'function') {
      retryButton = document.createElement('button');
      retryButton.type = 'button';
      retryButton.className = 'button shieldx-button-secondary';
      retryButton.textContent = __('Try again');
      retryButton.addEventListener('click', function () {
        retryButton.disabled = true;
        retry();
      });
      section.appendChild(retryButton);
    }

    container.textContent = '';
    container.appendChild(section);
    container.removeAttribute('data-shieldx-admin-page-loading');
    container.removeAttribute('data-shieldx-admin-page-ready');
    container.setAttribute('data-shieldx-admin-page-failed', '1');
  }

  function appendAdminPageContext(formData) {
    var search;

    if (!window.URLSearchParams) {
      return;
    }

    search = new window.URLSearchParams(window.location.search || '');
    search.forEach(function (value, key) {
      if (key === 'action' || key === '_ajax_nonce' || key === 'context' || key === 'page') {
        return;
      }

      formData.append('context[' + key + ']', value);
    });
  }

  function loadAdminPageContent(container) {
    var url = container.getAttribute('data-shieldx-admin-page-url') || '';
    var nonce = container.getAttribute('data-shieldx-admin-page-nonce') || '';
    var page = container.getAttribute('data-shieldx-admin-page') || '';
    var formData;
    var requestOptions;
    var controller = null;
    var deadline = 0;
    var requestNumber = parseInt(container.getAttribute('data-shieldx-admin-page-request') || '0', 10);
    var requestId;
    var settled = false;
    var requestTimeout = page === 'shield-x-backup' || page === 'shield-x-backup-restore' ? 120000 : 60000;

    if (container.getAttribute('data-shieldx-admin-page-loading') === '1' || !url || !nonce || !page || !window.FormData || !window.fetch) {
      return;
    }

    if (isNaN(requestNumber)) {
      requestNumber = 0;
    }

    requestId = String(requestNumber + 1);
    container.setAttribute('data-shieldx-admin-page-request', requestId);
    container.setAttribute('data-shieldx-admin-page-ready', '1');
    container.setAttribute('data-shieldx-admin-page-loading', '1');
    container.removeAttribute('data-shieldx-admin-page-failed');
    formData = new window.FormData();
    formData.append('action', 'shieldx_admin_page_content');
    formData.append('_ajax_nonce', nonce);
    formData.append('page', page);
    appendAdminPageContext(formData);
    requestOptions = {
      method: 'POST',
      credentials: 'same-origin',
      body: formData
    };

    if (window.AbortController) {
      controller = new window.AbortController();
      requestOptions.signal = controller.signal;
    }

    function isCurrentRequest() {
      return container.getAttribute('data-shieldx-admin-page-request') === requestId;
    }

    function clearDeadline() {
      if (deadline) {
        window.clearTimeout(deadline);
        deadline = 0;
      }
    }

    function fail() {
      if (settled || !isCurrentRequest()) {
        return;
      }

      settled = true;
      clearDeadline();
      renderAdminPageError(container, function () {
        loadAdminPageContent(container);
      });
    }

    deadline = window.setTimeout(function () {
      if (controller) {
        controller.abort();
      }

      fail();
    }, requestTimeout);

    window.fetch(url, requestOptions).then(function (response) {
      return response.json().then(function (payload) {
        if (!response.ok || !payload || !payload.success || !payload.data || typeof payload.data.html !== 'string') {
          throw new Error(__('Invalid SHIELD-X admin page response'));
        }

        return payload;
      });
    }).then(function (payload) {
      var headerActions;

      if (settled || !isCurrentRequest()) {
        return;
      }

      settled = true;
      clearDeadline();
      headerActions = root.querySelector('[data-shieldx-header-actions]');

      if (headerActions && typeof payload.data.header_actions_html === 'string') {
        replaceServerHtml(headerActions, payload.data.header_actions_html);
      }

      replaceServerHtml(container, payload.data.html);
      container.removeAttribute('data-shieldx-admin-page-loading');
      container.setAttribute('data-shieldx-admin-page-loaded', '1');
      initInsertedAdminContent(container);
    }).catch(fail);
  }

  function initAdminPageLoader() {
    root.querySelectorAll('[data-shieldx-admin-page-content]').forEach(function (container) {
      if (container.getAttribute('data-shieldx-admin-page-ready') === '1') {
        return;
      }

      loadAdminPageContent(container);
    });
  }

  initAdminPageLoader();

  function initProgressiveList(options) {
    function itemsForList(list) {
      return Array.prototype.slice.call(list.querySelectorAll(options.itemSelector));
    }

    function hiddenItemsForList(list) {
      return itemsForList(list).filter(function (item) {
        return item.hidden;
      });
    }

    function initialVisibleCount(list) {
      var stored = parseInt(list.getAttribute('data-shieldx-initial-visible-count') || '', 10);
      var visibleCount;

      if (!isNaN(stored) && stored > 0) {
        return stored;
      }

      visibleCount = itemsForList(list).filter(function (item) {
        return !item.hidden;
      }).length;

      if (!visibleCount || visibleCount < 1) {
        visibleCount = options.defaultStep;
      }

      list.setAttribute('data-shieldx-initial-visible-count', String(visibleCount));

      return visibleCount;
    }

    function updateButton(list, button) {
      var items = itemsForList(list);
      var hiddenCount = hiddenItemsForList(list).length;
      var initialCount = initialVisibleCount(list);
      var label = button.getAttribute('data-label') || button.textContent || __('Read more');
      var collapseLabel = button.getAttribute('data-collapse-label') || __('Show less');

      if (items.length <= initialCount) {
        button.hidden = true;
        return;
      }

      button.hidden = false;
      if (hiddenCount <= 0) {
        button.textContent = collapseLabel;
        button.setAttribute('aria-expanded', 'true');
        return;
      }

      button.textContent = label + ' (' + hiddenCount + ')';
      button.setAttribute('aria-expanded', 'false');
    }

    function collapseList(list) {
      var initialCount = initialVisibleCount(list);

      itemsForList(list).forEach(function (item, index) {
        item.hidden = index >= initialCount;
      });
    }

    function revealNext(list, button, event) {
      var hiddenItems;
      var step;

      if (event) {
        event.preventDefault();
      }

      step = parseInt(list.getAttribute('data-visible-step') || String(options.defaultStep), 10);

      if (!step || step < 1) {
        step = options.defaultStep;
      }

      hiddenItems = hiddenItemsForList(list);
      if (!hiddenItems.length) {
        collapseList(list);
        updateButton(list, button);
        return;
      }

      hiddenItems.slice(0, step).forEach(function (item) {
        item.hidden = false;
      });

      updateButton(list, button);
    }

    root.querySelectorAll(options.listSelector).forEach(function (list) {
      var button = list.querySelector(options.buttonSelector);

      if (!button || button.getAttribute('data-shieldx-progressive-ready') === '1') {
        return;
      }

      button.setAttribute('data-shieldx-progressive-ready', '1');
      updateButton(list, button);
      button.addEventListener('click', function (event) {
        revealNext(list, button, event);
      });
    });
  }

  function initShadowHistory() {
    initProgressiveList({
      listSelector: '[data-shieldx-shadow-history]',
      itemSelector: '[data-shieldx-shadow-history-item]',
      buttonSelector: '[data-shieldx-shadow-history-more]',
      defaultStep: 3
    });
  }

  initShadowHistory();

  function initManualBackupsList() {
    initProgressiveList({
      listSelector: '[data-shieldx-manual-backups]',
      itemSelector: '[data-shieldx-manual-backup-item]',
      buttonSelector: '[data-shieldx-manual-backups-more]',
      defaultStep: 2
    });
  }

  initManualBackupsList();

  function initRestorePointsList() {
    initProgressiveList({
      listSelector: '[data-shieldx-restore-points]',
      itemSelector: '[data-shieldx-restore-point-item]',
      buttonSelector: '[data-shieldx-restore-points-more]',
      defaultStep: 2
    });
  }

  initRestorePointsList();

  function initWafLatestHitsList() {
    root.querySelectorAll('[data-shieldx-waf-latest-hits]').forEach(function (list) {
      var panel = list.closest ? list.closest('.shieldx-waf-latest-hits-card') : null;
      var filter = panel ? panel.querySelector('[data-shieldx-waf-hit-filter]') : null;
      var filterToggle = filter ? filter.querySelector('[data-shieldx-waf-hit-filter-toggle]') : null;
      var filterMenu = filter ? filter.querySelector('[data-shieldx-waf-hit-filter-menu]') : null;
      var options = filter ? Array.prototype.slice.call(filter.querySelectorAll('[data-shieldx-waf-hit-filter-option]')) : [];
      var moreButton = list.querySelector('[data-shieldx-waf-latest-hits-more]');
      var moreActions = moreButton && moreButton.closest ? moreButton.closest('.shieldx-waf-latest-hits-actions') : null;
      var emptyMessage = list.querySelector('[data-shieldx-waf-latest-hits-empty]');
      var visibleStep = parseInt(list.getAttribute('data-visible-step') || '3', 10);
      var visibleCount;

      if (list.getAttribute('data-shieldx-waf-latest-hits-ready') === '1') {
        return;
      }

      list.setAttribute('data-shieldx-waf-latest-hits-ready', '1');
      visibleStep = !isNaN(visibleStep) && visibleStep > 0 ? visibleStep : 3;
      visibleCount = visibleStep;

      function items() {
        return Array.prototype.slice.call(list.querySelectorAll('[data-shieldx-waf-latest-hit]'));
      }

      function selectedFilters() {
        return options.filter(function (option) {
          return option.checked;
        }).map(function (option) {
          return option.value;
        });
      }

      function allOption() {
        var all = null;

        options.forEach(function (option) {
          if (option.value === 'all') {
            all = option;
          }
        });

        return all;
      }

      function itemMatches(item, selected) {
        var categories = (item.getAttribute('data-shieldx-waf-hit-categories') || '').split(/\s+/).filter(Boolean);

        return selected.some(function (filterName) {
          return categories.indexOf(filterName) !== -1;
        });
      }

      function matchingItems() {
        var selected = selectedFilters();

        if (!selected.length) {
          return [];
        }

        if (selected.indexOf('all') !== -1) {
          return items();
        }

        return items().filter(function (item) {
          return itemMatches(item, selected);
        });
      }

      function updateList() {
        var matched = matchingItems();
        var hiddenCount = Math.max(0, matched.length - visibleCount);
        var label = moreButton ? (moreButton.getAttribute('data-label') || moreButton.textContent || __('Read more')) : __('Read more');
        var collapseLabel = moreButton ? (moreButton.getAttribute('data-collapse-label') || __('Show less')) : __('Show less');

        items().forEach(function (item) {
          var index = matched.indexOf(item);
          item.hidden = index === -1 || index >= visibleCount;
        });

        if (emptyMessage) {
          emptyMessage.hidden = matched.length > 0;
        }

        if (!moreButton) {
          return;
        }

        if (moreActions) {
          moreActions.hidden = matched.length <= visibleStep;
        }
        moreButton.hidden = matched.length <= visibleStep;
        if (matched.length <= visibleStep) {
          moreButton.setAttribute('aria-expanded', 'false');
          return;
        }

        if (hiddenCount <= 0) {
          moreButton.textContent = collapseLabel;
          moreButton.setAttribute('aria-expanded', 'true');
          return;
        }

        moreButton.textContent = label + ' (' + hiddenCount + ')';
        moreButton.setAttribute('aria-expanded', 'false');
      }

      function closeFilterMenu() {
        if (!filterToggle || !filterMenu) {
          return;
        }

        filterMenu.hidden = true;
        filter.classList.remove('is-filter-menu-above');
        filterMenu.style.maxHeight = '';
        filterMenu.style.overflowY = '';
        filterToggle.setAttribute('aria-expanded', 'false');
      }

      function positionFilterMenu() {
        var availableHeight;
        var menuHeight;
        var openAbove;
        var spaceAbove;
        var spaceBelow;
        var toggleBounds;
        var viewportGap = 12;

        if (!filter || !filterToggle || !filterMenu) {
          return;
        }

        filter.classList.remove('is-filter-menu-above');
        filterMenu.style.maxHeight = '';
        filterMenu.style.overflowY = '';

        toggleBounds = filterToggle.getBoundingClientRect();
        menuHeight = filterMenu.scrollHeight;
        spaceAbove = Math.max(0, toggleBounds.top - viewportGap);
        spaceBelow = Math.max(0, window.innerHeight - toggleBounds.bottom - viewportGap);
        openAbove = menuHeight > spaceBelow && spaceAbove > spaceBelow;
        availableHeight = openAbove ? spaceAbove : spaceBelow;

        if (openAbove) {
          filter.classList.add('is-filter-menu-above');
        }

        if (menuHeight > availableHeight) {
          filterMenu.style.maxHeight = Math.max(1, Math.floor(availableHeight)) + 'px';
          filterMenu.style.overflowY = 'auto';
        }
      }

      if (filterToggle && filterMenu) {
        filterToggle.addEventListener('click', function (event) {
          var open = filterMenu.hidden;

          event.preventDefault();
          if (open) {
            filterMenu.hidden = false;
            positionFilterMenu();
            filterToggle.setAttribute('aria-expanded', 'true');
            return;
          }

          closeFilterMenu();
        });

        filter.addEventListener('keydown', function (event) {
          if (event.key === 'Escape') {
            closeFilterMenu();
            filterToggle.focus();
          }
        });

        document.addEventListener('click', function (event) {
          if (!filter.contains(event.target)) {
            closeFilterMenu();
          }
        });

        window.addEventListener('resize', function () {
          if (!filterMenu.hidden) {
            positionFilterMenu();
          }
        });
      }

      options.forEach(function (option) {
        option.addEventListener('change', function () {
          var all = allOption();

          if (option.value === 'all') {
            if (option.checked) {
              options.forEach(function (otherOption) {
                if (otherOption !== option) {
                  otherOption.checked = false;
                }
              });
            } else if (!selectedFilters().length && all) {
              all.checked = true;
            }
          } else if (option.checked && all) {
            all.checked = false;
          } else if (!selectedFilters().length && all) {
            all.checked = true;
          }

          visibleCount = visibleStep;
          updateList();
        });
      });

      if (moreButton) {
        moreButton.addEventListener('click', function (event) {
          var matched = matchingItems();

          event.preventDefault();
          if (visibleCount >= matched.length) {
            visibleCount = visibleStep;
          } else {
            visibleCount += visibleStep;
          }
          updateList();
        });
      }

      updateList();
    });
  }

  initWafLatestHitsList();

  function initLogFilesList() {
    initProgressiveList({
      listSelector: '[data-shieldx-log-files]',
      itemSelector: '[data-shieldx-log-file]',
      buttonSelector: '[data-shieldx-log-files-more]',
      defaultStep: 8
    });
  }

  initLogFilesList();

  function initTabSelector(selector, options) {
    var tabAttribute = options.tabAttribute;
    var panelAttribute = options.panelAttribute;
    var fallback = options.fallback;
    var tabs = selector.querySelectorAll('[' + tabAttribute + ']');
    var panels = root.querySelectorAll('[' + panelAttribute + ']');
    var preferMarkup = selector.getAttribute('data-shieldx-prefer-markup') === '1';
    var preferredHash = selector.getAttribute('data-shieldx-preferred-hash') || '';

    if (!tabs.length || !panels.length) {
      return;
    }

    function idFromHash() {
      var hash = window.location.hash || '';

      for (var index = 0; index < tabs.length; index += 1) {
        if ((tabs[index].getAttribute('href') || '') === hash) {
          return tabs[index].getAttribute(tabAttribute) || '';
        }
      }

      for (var panelIndex = 0; panelIndex < panels.length; panelIndex += 1) {
        var panel = panels[panelIndex];

        if (('#' + (panel.id || '')) === hash) {
          return panel.getAttribute(panelAttribute) || '';
        }

        try {
          if (panel.querySelector(hash)) {
            return panel.getAttribute(panelAttribute) || '';
          }
        } catch (error) {
          // Ignore malformed hashes and use the active tab instead.
        }
      }

      return '';
    }

    function selectedFromMarkup() {
      for (var index = 0; index < tabs.length; index += 1) {
        if (tabs[index].classList.contains('is-active')) {
          return tabs[index].getAttribute(tabAttribute) || fallback;
        }
      }

      return fallback;
    }

    function setActive(section, focusTab) {
      section = section || fallback;

      tabs.forEach(function (tab) {
        var selected = tab.getAttribute(tabAttribute) === section;
        tab.classList.toggle('is-active', selected);
        tab.setAttribute('aria-selected', selected ? 'true' : 'false');
        tab.tabIndex = selected ? 0 : -1;

        if (selected && focusTab) {
          tab.focus();
        }
      });

      panels.forEach(function (panel) {
        var selected = panel.getAttribute(panelAttribute) === section;
        panel.hidden = !selected;
        panel.classList.toggle('is-active', selected);
      });
    }

    function indexOfTab(tab) {
      for (var index = 0; index < tabs.length; index += 1) {
        if (tabs[index] === tab) {
          return index;
        }
      }

      return -1;
    }

    function activateByIndex(index) {
      var tab = tabs[(index + tabs.length) % tabs.length];
      var href = tab.getAttribute('href') || '';

      setActive(tab.getAttribute(tabAttribute) || fallback, true);

      if (href && window.history && window.history.replaceState) {
        window.history.replaceState(null, '', href);
      }
    }

    tabs.forEach(function (tab) {
      tab.addEventListener('click', function (event) {
        var section = tab.getAttribute(tabAttribute) || fallback;
        var href = tab.getAttribute('href') || '';

        event.preventDefault();
        setActive(section, false);

        if (href && window.history && window.history.replaceState) {
          window.history.replaceState(null, '', href);
        }
      });

      tab.addEventListener('keydown', function (event) {
        var index = indexOfTab(tab);

        if (index === -1) {
          return;
        }

        if (event.key === 'ArrowRight' || event.key === 'ArrowDown') {
          event.preventDefault();
          activateByIndex(index + 1);
          return;
        }

        if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') {
          event.preventDefault();
          activateByIndex(index - 1);
          return;
        }

        if (event.key === 'Home') {
          event.preventDefault();
          activateByIndex(0);
          return;
        }

        if (event.key === 'End') {
          event.preventDefault();
          activateByIndex(tabs.length - 1);
          return;
        }

        if (event.key === ' ') {
          event.preventDefault();
          tab.click();
        }
      });
    });

    window.addEventListener('hashchange', function () {
      setActive(idFromHash() || selectedFromMarkup(), false);
    });

    setActive(preferMarkup ? selectedFromMarkup() : (idFromHash() || selectedFromMarkup()), false);

    if (preferMarkup && preferredHash && window.history && window.history.replaceState && window.location.hash !== preferredHash) {
      window.history.replaceState(null, '', preferredHash);
    }
  }

  function initPageTabSelectors(scope) {
    var scanSelector = (scope || root).querySelector('[data-shieldx-scan-selector]');
    var systemSelector = (scope || root).querySelector('[data-shieldx-system-selector]');

    if (scanSelector && scanSelector.getAttribute('data-shieldx-tabs-ready') !== '1') {
      scanSelector.setAttribute('data-shieldx-tabs-ready', '1');
      initTabSelector(scanSelector, {
        tabAttribute: 'data-shieldx-scan-tab',
        panelAttribute: 'data-shieldx-scan-panel',
        fallback: 'file'
      });
    }

    if (systemSelector && systemSelector.getAttribute('data-shieldx-tabs-ready') !== '1') {
      systemSelector.setAttribute('data-shieldx-tabs-ready', '1');
      initTabSelector(systemSelector, {
        tabAttribute: 'data-shieldx-system-tab',
        panelAttribute: 'data-shieldx-system-panel',
        fallback: 'challenge'
      });
    }
  }

  initPageTabSelectors(root);

  function findNamedControl(container, name) {
    var controls = container.querySelectorAll('input, select, textarea, button');

    for (var index = 0; index < controls.length; index += 1) {
      if (controls[index].name === name) {
        return controls[index];
      }
    }

    return null;
  }

  function setContainedControlsDisabled(container, disabled) {
    var controls = container.querySelectorAll('input, select, textarea, button');

    controls.forEach(function (control) {
      control.disabled = disabled;
    });
  }

  var toggleGroupIndex = 0;

  function syncToggleGroup(group) {
    var inputName = group.getAttribute('data-shieldx-toggle-input') || '';
    var toggle = findNamedControl(group, inputName);
    var fields = group.querySelector('[data-shieldx-toggle-fields]');

    if (!toggle || !fields) {
      return;
    }

    var enabled = !!toggle.checked;

    if (!fields.id) {
      toggleGroupIndex += 1;
      fields.id = 'shieldx-toggle-fields-' + toggleGroupIndex;
    }

    fields.hidden = !enabled;
    toggle.setAttribute('aria-controls', fields.id);
    toggle.setAttribute('aria-expanded', enabled ? 'true' : 'false');
    group.classList.toggle('is-collapsed', !enabled);
    setContainedControlsDisabled(fields, !enabled);
  }

  function initToggleGroups(scope) {
    (scope || root).querySelectorAll('[data-shieldx-toggle-group]').forEach(function (group) {
      var inputName;
      var toggle;

      if (group.getAttribute('data-shieldx-toggle-ready') === '1') {
        return;
      }

      group.setAttribute('data-shieldx-toggle-ready', '1');
      inputName = group.getAttribute('data-shieldx-toggle-input') || '';
      toggle = findNamedControl(group, inputName);
      syncToggleGroup(group);

      if (toggle) {
        toggle.addEventListener('change', function () {
          syncToggleGroup(group);
        });
      }
    });
  }

  initToggleGroups(root);

  function syncSelectConditional(node) {
    var name = node.getAttribute('data-shieldx-select-name') || '';
    var expected = node.getAttribute('data-shieldx-select-value') || '';
    var scope = node.closest('form') || root;
    var control = findNamedControl(scope, name);

    if (!name || !control) {
      return;
    }

    var visible = control.value === expected;
    node.hidden = !visible;
    setContainedControlsDisabled(node, !visible);
  }

  function initSelectConditionals(scope) {
    (scope || root).querySelectorAll('[data-shieldx-select-conditional]').forEach(function (node) {
      var name;
      var fieldScope;
      var control;

      if (node.getAttribute('data-shieldx-select-ready') === '1') {
        return;
      }

      node.setAttribute('data-shieldx-select-ready', '1');
      name = node.getAttribute('data-shieldx-select-name') || '';
      fieldScope = node.closest('form') || root;
      control = findNamedControl(fieldScope, name);
      syncSelectConditional(node);

      if (control) {
        control.addEventListener('change', function () {
          syncSelectConditional(node);
        });
      }
    });
  }

  initSelectConditionals(root);

  function escapedAttributeValue(value) {
    if (window.CSS && window.CSS.escape) {
      return window.CSS.escape(value);
    }

    return value.replace(/[^A-Za-z0-9_-]/g, '\\$&');
  }

  function initRestoreSelectionTools(tools) {
    if (tools.getAttribute('data-shieldx-restore-tools-ready') === '1') {
      return;
    }

    tools.setAttribute('data-shieldx-restore-tools-ready', '1');
    var formId = tools.getAttribute('data-restore-form') || '';
    var restoreId = tools.getAttribute('data-restore-id') || 'restore-point';
    var detailBlock = tools.closest('.shieldx-restore-detail-block') || root;
    var hiddenSelector = '[data-shieldx-restore-search-input][form="' + escapedAttributeValue(formId) + '"]';
    var countNode = tools.querySelector('[data-shieldx-restore-selected-count]');
    var exportButton = tools.querySelector('[data-shieldx-restore-export]');

    if (!formId) {
      return;
    }

    function rowCheckboxes() {
      return detailBlock.querySelectorAll('input[type="checkbox"][name="restore_files[]"]');
    }

    function searchInputs() {
      return root.querySelectorAll(hiddenSelector);
    }

    function syncHiddenForPath(path, selected) {
      searchInputs().forEach(function (input) {
        if (input.value === path) {
          input.disabled = !selected;
        }
      });
    }

    function fileFromInput(input) {
      return {
        path: input.getAttribute('data-restore-path') || input.value || '',
        size: input.getAttribute('data-restore-size') || '',
        sizeHuman: input.getAttribute('data-restore-size-human') || '',
        modified: input.getAttribute('data-restore-modified') || '',
        change: input.getAttribute('data-restore-change') || '',
        hash: input.getAttribute('data-restore-hash') || '',
        restoreData: input.getAttribute('data-restore-data') || ''
      };
    }

    function selectedFiles() {
      var selected = {};
      var ordered = [];

      function add(input) {
        var file = fileFromInput(input);

        if (!file.path || selected[file.path]) {
          return;
        }

        selected[file.path] = true;
        ordered.push(file);
      }

      rowCheckboxes().forEach(function (checkbox) {
        if (checkbox.checked) {
          add(checkbox);
        }
      });

      searchInputs().forEach(function (input) {
        if (!input.disabled) {
          add(input);
        }
      });

      return ordered;
    }

    function updateSelectionCount() {
      var files = selectedFiles();
      var template = countNode ? (countNode.getAttribute('data-selected-template') || __('%d selected')) : __('%d selected');

      if (countNode) {
        countNode.textContent = template.replace('%d', String(files.length));
      }

      if (exportButton) {
        exportButton.disabled = files.length === 0;
      }
    }

    function csvCell(value) {
      var text = String(value == null ? '' : value);

      return '"' + text.replace(/"/g, '""') + '"';
    }

    function exportSelectedCsv() {
      var files = selectedFiles();

      if (!files.length || typeof Blob === 'undefined' || !window.URL || !window.URL.createObjectURL) {
        return;
      }

      var rows = [
        ['Path', 'Change', 'Size bytes', 'Size', 'Modified', 'SHA-256', 'Restore data']
      ];

      files.forEach(function (file) {
        rows.push([file.path, file.change, file.size, file.sizeHuman, file.modified, file.hash, file.restoreData]);
      });

      var csv = rows.map(function (row) {
        return row.map(csvCell).join(',');
      }).join('\r\n') + '\r\n';
      var blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
      var url = window.URL.createObjectURL(blob);
      var link = document.createElement('a');

      link.href = url;
      link.download = 'shield-x-restore-files-' + restoreId.replace(/[^A-Za-z0-9_-]/g, '-') + '.csv';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    }

    tools.addEventListener('click', function (event) {
      var exportTarget = event.target.closest('[data-shieldx-restore-export]');
      var actionButton = event.target.closest('[data-shieldx-restore-select-action]');

      if (exportTarget) {
        exportSelectedCsv();
        return;
      }

      if (!actionButton || actionButton.disabled) {
        return;
      }

      var action = actionButton.getAttribute('data-shieldx-restore-select-action') || '';

      if (action === 'none') {
        searchInputs().forEach(function (input) {
          input.disabled = true;
        });

        rowCheckboxes().forEach(function (checkbox) {
          checkbox.checked = false;
        });

        updateSelectionCount();
        return;
      }

      if (action === 'search') {
        searchInputs().forEach(function (input) {
          input.disabled = false;
        });

        rowCheckboxes().forEach(function (checkbox) {
          checkbox.checked = true;
        });

        updateSelectionCount();
      }
    });

    rowCheckboxes().forEach(function (checkbox) {
      checkbox.addEventListener('change', function () {
        syncHiddenForPath(checkbox.value, checkbox.checked);
        updateSelectionCount();
      });
    });

    updateSelectionCount();
  }

  function initRestoreTools(scope) {
    (scope || root).querySelectorAll('[data-shieldx-restore-select-tools]').forEach(initRestoreSelectionTools);
  }

  initRestoreTools(root);

  function disclosurePanelForToggle(toggle) {
    var panelId = toggle.getAttribute('aria-controls') || '';

    return panelId ? document.getElementById(panelId) : null;
  }

  function disclosureControlsSelector(panelId) {
    var escaped = window.CSS && window.CSS.escape ? window.CSS.escape(panelId) : panelId.replace(/[^A-Za-z0-9_-]/g, '\\$&');

    return '[data-shieldx-disclosure-toggle][aria-controls="' + escaped + '"]';
  }

  function setDisclosureOpen(toggle, open, shouldScroll) {
    var panel = disclosurePanelForToggle(toggle);
    var panelId = toggle.getAttribute('aria-controls') || '';

    if (!panel || !panelId) {
      return;
    }

    panel.hidden = !open;
    root.querySelectorAll(disclosureControlsSelector(panelId)).forEach(function (control) {
      control.setAttribute('aria-expanded', open ? 'true' : 'false');
      control.classList.toggle('is-active', open);
    });

    if (open && shouldScroll && typeof panel.scrollIntoView === 'function') {
      panel.scrollIntoView({ block: 'start', behavior: 'smooth' });
    }
  }

  function disclosureHashTargetId() {
    if (!window.location.hash || window.location.hash.length < 2) {
      return '';
    }

    try {
      return decodeURIComponent(window.location.hash.slice(1));
    } catch (error) {
      return window.location.hash.slice(1);
    }
  }

  function disclosurePanelContainsId(panel, id) {
    var escaped = window.CSS && window.CSS.escape ? window.CSS.escape(id) : id.replace(/[^A-Za-z0-9_-]/g, '\\$&');

    return panel.id === id || !!panel.querySelector('#' + escaped);
  }

  function initDisclosureToggle(toggle) {
    var panel = disclosurePanelForToggle(toggle);
    var hashId = disclosureHashTargetId();
    var shouldOpen = !!(panel && hashId !== '' && disclosurePanelContainsId(panel, hashId));

    setDisclosureOpen(toggle, shouldOpen, false);
  }

  function initDisclosureToggles(scope) {
    (scope || root).querySelectorAll('[data-shieldx-disclosure-toggle]').forEach(initDisclosureToggle);
  }

  initDisclosureToggles(root);

  root.addEventListener('click', function (event) {
    var toggle = event.target.closest('[data-shieldx-disclosure-toggle]');

    if (!toggle || !root.contains(toggle)) {
      return;
    }

    event.preventDefault();
    setDisclosureOpen(toggle, toggle.getAttribute('aria-expanded') !== 'true', true);
  });

  function syncScrollPosition(source, target) {
    var maxSourceTop = Math.max(1, source.scrollHeight - source.clientHeight);
    var maxTargetTop = Math.max(0, target.scrollHeight - target.clientHeight);
    var maxSourceLeft = Math.max(1, source.scrollWidth - source.clientWidth);
    var maxTargetLeft = Math.max(0, target.scrollWidth - target.clientWidth);

    target.scrollTop = (source.scrollTop / maxSourceTop) * maxTargetTop;
    target.scrollLeft = (source.scrollLeft / maxSourceLeft) * maxTargetLeft;
  }

  function initLinkedCodeScroll(container) {
    if (container.getAttribute('data-shieldx-linked-scroll-ready') === '1') {
      return;
    }

    container.setAttribute('data-shieldx-linked-scroll-ready', '1');
    var panes = container.querySelectorAll('pre');
    var syncing = false;

    if (panes.length < 2) {
      return;
    }

    panes.forEach(function (pane) {
      pane.addEventListener('scroll', function () {
        if (syncing) {
          return;
        }

        syncing = true;
        panes.forEach(function (target) {
          if (target !== pane) {
            syncScrollPosition(pane, target);
          }
        });

        window.requestAnimationFrame(function () {
          syncing = false;
        });
      }, { passive: true });
    });
  }

  function initLinkedCodeScrollAreas(scope) {
    (scope || root).querySelectorAll('.shieldx-diff-grid, .shieldx-file-side-by-side').forEach(initLinkedCodeScroll);
  }

  initLinkedCodeScrollAreas(root);

  function initProfiler(profiler) {
    if (profiler.getAttribute('data-shieldx-profiler-ready') === '1') {
      return;
    }

    profiler.setAttribute('data-shieldx-profiler-ready', '1');
    var rows = profiler.querySelectorAll('tr[data-shieldx-profile-key]');
    var profileButtons = profiler.querySelectorAll('[data-shieldx-profile-key].shieldx-profile-view');
    var panels = profiler.querySelectorAll('[data-shieldx-profile-panel]');
    var detailRows = profiler.querySelectorAll('[data-shieldx-profile-detail]');
    var visitRows = root.querySelectorAll('[data-shieldx-profiler-visit]');
    var countLabel = root.querySelector('[data-shieldx-profiler-count]');
    var emptyLabel = root.querySelector('[data-shieldx-profiler-empty]');
    var showAllButton = root.querySelector('[data-shieldx-profiler-show-all]');

    if (!rows.length) {
      return;
    }

    function countLabelText(count, focused) {
      var noun = count === 1 ? __(' recent request') : __(' recent requests');

      return count + noun + (focused ? __(' for selected visitor') : '');
    }

    function showAllProfiles() {
      rows.forEach(function (row) {
        row.classList.remove('is-selected');
      });

      profileButtons.forEach(function (button) {
        button.setAttribute('aria-expanded', 'false');
      });

      panels.forEach(function (panel) {
        panel.hidden = true;
        panel.classList.remove('is-active');
      });

      detailRows.forEach(function (detailRow) {
        detailRow.hidden = true;
        detailRow.classList.remove('is-active');
      });

      visitRows.forEach(function (row) {
        row.hidden = false;
      });

      if (countLabel) {
        countLabel.textContent = countLabelText(visitRows.length, false);
      }

      if (emptyLabel) {
        emptyLabel.hidden = visitRows.length !== 0;
      }

      if (showAllButton) {
        showAllButton.hidden = true;
      }
    }

    function setSelectedProfile(key) {
      var visibleVisits = 0;

      rows.forEach(function (row) {
        var selected = row.getAttribute('data-shieldx-profile-key') === key;
        row.classList.toggle('is-selected', selected);
      });

      profileButtons.forEach(function (button) {
        var selected = button.getAttribute('data-shieldx-profile-key') === key;
        button.setAttribute('aria-expanded', selected ? 'true' : 'false');
      });

      panels.forEach(function (panel) {
        var selected = panel.getAttribute('data-shieldx-profile-panel') === key;
        panel.hidden = !selected;
        panel.classList.toggle('is-active', selected);
      });

      detailRows.forEach(function (detailRow) {
        var selected = detailRow.getAttribute('data-shieldx-profile-detail') === key;
        detailRow.hidden = !selected;
        detailRow.classList.toggle('is-active', selected);
      });

      visitRows.forEach(function (row) {
        var visible = row.getAttribute('data-shieldx-profiler-visit') === key;
        row.hidden = !visible;

        if (visible) {
          visibleVisits += 1;
        }
      });

      if (countLabel) {
        countLabel.textContent = countLabelText(visibleVisits, true);
      }

      if (emptyLabel) {
        emptyLabel.hidden = visibleVisits !== 0;
      }

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

    rows.forEach(function (row) {
      row.addEventListener('click', function (event) {
        if (event.target.closest('a, button, input, select, textarea')) {
          return;
        }

        setSelectedProfile(row.getAttribute('data-shieldx-profile-key') || '');
      });
    });

    profileButtons.forEach(function (button) {
      button.addEventListener('click', function () {
        setSelectedProfile(button.getAttribute('data-shieldx-profile-key') || '');
      });
    });

    if (showAllButton) {
      showAllButton.addEventListener('click', function () {
        showAllProfiles();
      });
    }

    showAllProfiles();
  }

  function initProfilers(scope) {
    (scope || root).querySelectorAll('[data-shieldx-profiler]').forEach(function (profiler) {
      initProfiler(profiler);
    });
  }

  initProfilers(root);

  function uniqueTokenLines(value) {
    var seen = {};
    var lines = String(value || '').split(/\r?\n/);
    var tokens = [];

    lines.forEach(function (line) {
      var token = line.trim();
      var key = token.toLowerCase();

      if (token && !seen[key]) {
        seen[key] = true;
        tokens.push(token);
      }
    });

    return tokens;
  }

  function normalizeSuggestions(raw) {
    if (!Array.isArray(raw)) {
      return [];
    }

    return raw.map(function (item) {
      if (typeof item === 'string') {
        return {
          value: item,
          label: item,
          meta: ''
        };
      }

      item = item || {};

      return {
        value: String(item.value || '').trim(),
        label: String(item.label || item.value || '').trim(),
        meta: String(item.meta || '').trim()
      };
    }).filter(function (item) {
      return item.value !== '';
    });
  }

  function parseSuggestions(textarea) {
    try {
      return normalizeSuggestions(JSON.parse(textarea.getAttribute('data-shieldx-suggestions') || '[]'));
    } catch (error) {
      return [];
    }
  }

  function initTokenField(textarea) {
    var suggestions = parseSuggestions(textarea);
    var tokens = uniqueTokenLines(textarea.value);
    var labelMap = {};
    var allowCustom = textarea.getAttribute('data-shieldx-allow-custom') !== '0';
    var suggestionLimit = parseInt(textarea.getAttribute('data-shieldx-suggestion-limit') || '12', 10);
    var control = document.createElement('div');
    var chipList = document.createElement('div');
    var input = document.createElement('input');
    var toggle = document.createElement('button');
    var menu = document.createElement('div');
    var status = document.createElement('span');
    var tokenId = 'shieldx-token-' + String(textarea.name || Math.random().toString(36).slice(2)).replace(/[^a-z0-9_-]/gi, '-');
    var labelElement = textarea.parentNode ? textarea.parentNode.querySelector('span') : null;
    var accessibleLabel = labelElement ? labelElement.textContent.trim() : '';
    var activeIndex = -1;

    if (textarea.dataset.shieldxTokenReady === 'true') {
      return;
    }

    if (isNaN(suggestionLimit) || suggestionLimit < 0) {
      suggestionLimit = 12;
    }

    textarea.dataset.shieldxTokenReady = 'true';

    suggestions.forEach(function (suggestion) {
      labelMap[suggestion.value.toLowerCase()] = suggestion;
    });

    control.className = 'shieldx-token-control';
    chipList.className = 'shieldx-token-list';

    input.className = 'shieldx-token-input';
    input.type = 'text';
    input.autocomplete = 'off';
    input.placeholder = textarea.getAttribute('data-shieldx-placeholder') || __('Search or add value');
    input.setAttribute('role', 'combobox');
    input.setAttribute('aria-autocomplete', 'list');
    input.setAttribute('aria-expanded', 'false');
    input.setAttribute('aria-controls', tokenId + '-menu');
    input.setAttribute('aria-haspopup', 'listbox');
    input.setAttribute('aria-label', accessibleLabel || input.placeholder);

    toggle.className = 'shieldx-token-toggle';
    toggle.type = 'button';
    toggle.setAttribute('aria-label', __('Show suggestions'));
    toggle.setAttribute('aria-controls', tokenId + '-menu');
    toggle.setAttribute('aria-expanded', 'false');
    toggle.textContent = '+';

    status.className = 'shieldx-screen-reader-text';
    status.setAttribute('aria-live', 'polite');
    status.setAttribute('aria-atomic', 'true');

    chipList.id = tokenId + '-chips';
    menu.className = 'shieldx-token-menu';
    menu.id = tokenId + '-menu';
    menu.setAttribute('role', 'listbox');
    menu.setAttribute('aria-label', accessibleLabel ? sprintf(__('%s suggestions'), accessibleLabel) : __('Suggestions'));
    menu.hidden = true;

    control.appendChild(input);
    control.appendChild(toggle);
    control.appendChild(menu);
    textarea.parentNode.insertBefore(control, textarea.nextSibling);
    textarea.parentNode.insertBefore(chipList, control.nextSibling);
    textarea.parentNode.insertBefore(status, chipList.nextSibling);
    textarea.classList.add('shieldx-token-source--enhanced');

    function syncTextarea() {
      textarea.value = tokens.join('\n');
    }

    function displayLabel(value) {
      var suggestion = labelMap[value.toLowerCase()];

      return suggestion ? suggestion.label : value;
    }

    function hasToken(value) {
      var key = value.toLowerCase();

      return tokens.some(function (token) {
        return token.toLowerCase() === key;
      });
    }

    function addToken(value) {
      value = String(value || '').trim();

      if (!value || hasToken(value)) {
        input.value = '';
        render();
        return;
      }

      tokens.push(value);
      input.value = '';
      render();
    }

    function removeToken(value) {
      var key = value.toLowerCase();

      tokens = tokens.filter(function (token) {
        return token.toLowerCase() !== key;
      });

      render();
    }

    function matchingSuggestions() {
      var query = input.value.trim().toLowerCase();
      var matches = suggestions.filter(function (suggestion) {
        var haystack = [suggestion.value, suggestion.label, suggestion.meta].join(' ').toLowerCase();

        return !hasToken(suggestion.value) && (!query || haystack.indexOf(query) !== -1);
      });

      if (suggestionLimit > 0) {
        matches = matches.slice(0, suggestionLimit);
      }

      if (allowCustom && query && !hasToken(input.value) && !matches.some(function (suggestion) {
        return suggestion.value.toLowerCase() === query;
      })) {
        matches.push({
          value: input.value.trim(),
          label: 'Add "' + input.value.trim() + '"',
          meta: 'Custom value',
          custom: true
        });
      }

      return matches;
    }

    function closeMenu() {
      menu.hidden = true;
      control.classList.remove('is-open');
      activeIndex = -1;
      input.setAttribute('aria-expanded', 'false');
      input.removeAttribute('aria-activedescendant');
      toggle.setAttribute('aria-expanded', 'false');
    }

    function openMenu() {
      menu.hidden = false;
      control.classList.add('is-open');
      input.setAttribute('aria-expanded', 'true');
      toggle.setAttribute('aria-expanded', 'true');
      renderMenu();
    }

    function setActiveOption(index) {
      var options = menu.querySelectorAll('[role="option"]');

      if (!options.length) {
        activeIndex = -1;
        input.removeAttribute('aria-activedescendant');
        return;
      }

      if (index < 0) {
        activeIndex = -1;
        input.removeAttribute('aria-activedescendant');
        options.forEach(function (option) {
          option.classList.remove('is-active');
          option.setAttribute('aria-selected', 'false');
        });
        return;
      }

      activeIndex = (index + options.length) % options.length;

      options.forEach(function (option, optionIndex) {
        var selected = optionIndex === activeIndex;
        option.classList.toggle('is-active', selected);
        option.setAttribute('aria-selected', selected ? 'true' : 'false');

        if (selected) {
          input.setAttribute('aria-activedescendant', option.id);

          if (option.scrollIntoView) {
            option.scrollIntoView({ block: 'nearest' });
          }
        }
      });
    }

    function activeOptionValue() {
      var options = menu.querySelectorAll('[role="option"]');

      if (activeIndex < 0 || activeIndex >= options.length) {
        return '';
      }

      return options[activeIndex].getAttribute('data-value') || '';
    }

    function renderMenu() {
      var matches = matchingSuggestions();
      menu.innerHTML = '';

      if (!matches.length) {
        var empty = document.createElement('span');
        empty.className = 'shieldx-token-empty';
        empty.textContent = __('No suggestions');
        menu.appendChild(empty);
        activeIndex = -1;
        input.removeAttribute('aria-activedescendant');
        return;
      }

      if (activeIndex >= matches.length) {
        activeIndex = matches.length - 1;
      }

      matches.forEach(function (suggestion, index) {
        var option = document.createElement('div');
        var label = document.createElement('strong');

        option.id = tokenId + '-option-' + index;
        option.className = suggestion.custom ? 'shieldx-token-option shieldx-token-option--custom' : 'shieldx-token-option';
        option.dataset.value = suggestion.value;
        option.setAttribute('role', 'option');
        option.setAttribute('aria-selected', index === activeIndex ? 'true' : 'false');
        option.tabIndex = -1;
        label.textContent = suggestion.label || suggestion.value;
        option.appendChild(label);

        if (suggestion.meta) {
          var meta = document.createElement('small');
          meta.textContent = suggestion.meta;
          option.appendChild(meta);
        }

        option.addEventListener('mousedown', function (event) {
          event.preventDefault();
        });

        option.addEventListener('click', function () {
          addToken(option.dataset.value || '');
          input.focus();
          openMenu();
        });

        menu.appendChild(option);
      });

      setActiveOption(activeIndex);
    }

    function render() {
      chipList.innerHTML = '';

      tokens.forEach(function (token) {
        var chip = document.createElement('span');
        var label = document.createElement('span');
        var remove = document.createElement('button');

        chip.className = 'shieldx-token-chip';
        label.textContent = displayLabel(token);
        remove.type = 'button';
        remove.setAttribute('aria-label', sprintf(__('Remove %s'), displayLabel(token)));
        remove.textContent = 'x';
        remove.addEventListener('click', function () {
          removeToken(token);
          input.focus();
        });

        chip.appendChild(label);
        chip.appendChild(remove);
        chipList.appendChild(chip);
      });

      syncTextarea();
      status.textContent = tokens.length === 1 ? __('1 selected item.') : sprintf(__('%d selected items.'), tokens.length);

      if (!menu.hidden) {
        renderMenu();
      }
    }

    input.addEventListener('focus', openMenu);
    input.addEventListener('input', function () {
      activeIndex = -1;
      openMenu();
    });
    input.addEventListener('keydown', function (event) {
      if (event.key === 'ArrowDown') {
        event.preventDefault();

        if (menu.hidden) {
          openMenu();
        }

        setActiveOption(activeIndex + 1);
        return;
      }

      if (event.key === 'ArrowUp') {
        event.preventDefault();

        if (menu.hidden) {
          openMenu();
        }

        setActiveOption(activeIndex - 1);
        return;
      }

      if (event.key === 'Enter') {
        event.preventDefault();
        var matches = matchingSuggestions();
        var activeValue = activeOptionValue();
        var value = activeValue || (!allowCustom && matches.length ? matches[0].value : input.value);

        addToken(value);
        openMenu();
        return;
      }

      if (event.key === 'Backspace' && input.value === '' && tokens.length) {
        removeToken(tokens[tokens.length - 1]);
        return;
      }

      if (event.key === 'Escape') {
        closeMenu();
        return;
      }

      if (event.key === 'Tab') {
        closeMenu();
      }
    });

    input.addEventListener('paste', function (event) {
      var clipboard = event.clipboardData;

      if (!clipboard) {
        return;
      }

      var text = clipboard.getData('text');

      if (text.indexOf('\n') === -1) {
        return;
      }

      event.preventDefault();
      uniqueTokenLines(text).forEach(addToken);
    });

    toggle.addEventListener('click', function () {
      if (menu.hidden) {
        input.focus();
        openMenu();
        return;
      }

      closeMenu();
    });

    document.addEventListener('click', function (event) {
      if (!control.contains(event.target)) {
        closeMenu();
      }
    });

    if (textarea.form) {
      textarea.form.addEventListener('submit', syncTextarea);
    }

    render();
  }

  function initTokenFields(scope) {
    (scope || root).querySelectorAll('[data-shieldx-token-field]').forEach(function (textarea) {
      initTokenField(textarea);
    });
  }

  initTokenFields(root);

  var scanModal = root.querySelector('[data-shieldx-scan-modal]');
  var activeScanForm = null;
  var activeScanNextUrl = '';
  var activeScanTimer = 0;
  var activeScanPolls = 0;
  var activeScanToken = 0;
  var activeScanPollDelay = 750;
  var maxScanPolls = 1000;
  var activeScanProgress = null;
  var activeProgressLabels = {};
  var activeProgressRefreshSelector = '';
  var activeProgressRefreshUrl = '';
  var scanModalReturnFocus = null;
  var corePromptModal = root.querySelector('[data-shieldx-core-prompt-modal]');
  var pendingCorePromptForm = null;

  function corePromptSessionKey(form) {
    return form.getAttribute('data-shieldx-official-core-prompt-key') || 'shieldx-official-core';
  }

  function corePromptSeen(form) {
    try {
      return window.sessionStorage && window.sessionStorage.getItem(corePromptSessionKey(form)) === '1';
    } catch (error) {
      return form.dataset.shieldxCorePromptSeen === 'true';
    }
  }

  function markCorePromptSeen(form) {
    form.dataset.shieldxCorePromptSeen = 'true';

    try {
      if (window.sessionStorage) {
        window.sessionStorage.setItem(corePromptSessionKey(form), '1');
      }
    } catch (error) {
      // Session storage can be disabled; the in-memory form flag still prevents duplicate prompts.
    }
  }

  function markOfficialCoreReady() {
    root.querySelectorAll('[data-shieldx-official-core-prompt]').forEach(function (form) {
      form.removeAttribute('data-shieldx-official-core-prompt');
      markCorePromptSeen(form);
    });

    pendingCorePromptForm = null;
  }

  function shouldShowCorePrompt(form) {
    return !!(
      corePromptModal &&
      form &&
      form.getAttribute('data-shieldx-official-core-prompt') === '1' &&
      !corePromptSeen(form)
    );
  }

  function closeCorePromptModal() {
    if (!corePromptModal || corePromptModal.hidden) {
      return;
    }

    corePromptModal.hidden = true;
    document.body.classList.remove('shieldx-modal-open');

    var button = pendingCorePromptForm ? scanFormButton(pendingCorePromptForm) : null;
    if (button && typeof button.focus === 'function') {
      button.focus();
    }
  }

  function openCorePromptModal(form) {
    pendingCorePromptForm = form;
    corePromptModal.hidden = false;
    document.body.classList.add('shieldx-modal-open');

    var primary = corePromptModal.querySelector('.button-primary');
    if (primary && typeof primary.focus === 'function') {
      primary.focus();
    }
  }

  function scanFormButton(form) {
    var button = form.querySelector('[data-shieldx-scan-run-button], [data-shieldx-shadow-scan-button], [data-shieldx-backup-progress-button], [data-shieldx-core-progress-button], [data-shieldx-plugin-packages-progress-button], [data-shieldx-permission-fix-button]');

    if (!button && form.id && window.CSS && CSS.escape) {
      button = root.querySelector('[form="' + CSS.escape(form.id) + '"][data-shieldx-scan-run-button], [form="' + CSS.escape(form.id) + '"][data-shieldx-shadow-scan-button], [form="' + CSS.escape(form.id) + '"][data-shieldx-backup-progress-button], [form="' + CSS.escape(form.id) + '"][data-shieldx-core-progress-button], [form="' + CSS.escape(form.id) + '"][data-shieldx-plugin-packages-progress-button], [form="' + CSS.escape(form.id) + '"][data-shieldx-permission-fix-button]');
    }

    return button;
  }

  function scanFormProgress(form) {
    return form.querySelector('[data-shieldx-scan-progress]') || root.querySelector('[data-shieldx-shadow-progress]');
  }

  function setScanFormRunning(form, running) {
    var button = scanFormButton(form);
    var progress = scanFormProgress(form);

    form.dataset.shieldxSubmitting = running ? 'true' : 'false';
    form.classList.toggle('is-running', running);

    if (button) {
      if (!button.dataset.shieldxOriginalLabel) {
        button.dataset.shieldxOriginalLabel = button.textContent;
      }

      button.textContent = running ? (button.getAttribute('data-running-label') || __('Scanning...')) : button.dataset.shieldxOriginalLabel;
      button.disabled = running;
    }

    if (progress) {
      progress.hidden = !running;
    }
  }

  function scanModalText(name, fallback) {
    return scanModal ? (scanModal.getAttribute(name) || fallback) : fallback;
  }

  function setNodeText(selector, value) {
    var node = scanModal ? scanModal.querySelector(selector) : null;

    if (node) {
      node.textContent = value;
    }
  }

  function renderScanModalFailures(progress) {
    var detailsNode = scanModal ? scanModal.querySelector('[data-shieldx-scan-modal-details]') : null;
    var details = progress && Array.isArray(progress.failure_details) ? progress.failure_details : [];
    var title = details.length === 1
      ? scanModalText('data-failure-title', __('Failed download'))
      : scanModalText('data-failure-title-plural', __('Failed downloads'));

    if (!detailsNode) {
      return;
    }

    detailsNode.innerHTML = '';
    if (!details.length) {
      detailsNode.hidden = true;
      return;
    }

    var heading = document.createElement('strong');
    heading.textContent = title;
    detailsNode.appendChild(heading);

    var list = document.createElement('ul');
    details.slice(0, 12).forEach(function (detail) {
      var item = document.createElement('li');
      var plugin = document.createElement('span');
      var reason = document.createElement('small');

      plugin.textContent = detail && detail.plugin ? detail.plugin : __('Unknown plugin');
      reason.textContent = detail && detail.reason ? detail.reason : __('No failure reason was returned.');
      item.appendChild(plugin);
      item.appendChild(reason);
      list.appendChild(item);
    });

    detailsNode.appendChild(list);
    detailsNode.hidden = false;
  }

  function initPluginPackageUploads(scope) {
    (scope || root).querySelectorAll('[data-shieldx-plugin-package-upload]').forEach(function (input) {
      if (input.getAttribute('data-shieldx-upload-ready') === '1') {
        return;
      }

      input.setAttribute('data-shieldx-upload-ready', '1');
      input.addEventListener('change', function () {
        if (!input.files || input.files.length < 1 || !input.form) {
          return;
        }

        input.form.submit();
      });
    });
  }

  function setScanModalState(state, message) {
    if (!scanModal) {
      return;
    }

    scanModal.classList.toggle('is-complete', state === 'completed');
    scanModal.classList.toggle('is-failed', state === 'failed');

    if (state === 'completed') {
      setNodeText('[data-shieldx-scan-modal-title]', activeProgressLabels.completeTitle || scanModalText('data-complete-title', __('Scan complete')));
      setNodeText('[data-shieldx-scan-modal-intro]', activeProgressLabels.completeIntro || scanModalText('data-complete-intro', __('The scan finished. Open the results when you are ready.')));
      return;
    }

    if (state === 'failed') {
      setNodeText('[data-shieldx-scan-modal-title]', activeProgressLabels.failedTitle || scanModalText('data-failed-title', __('Scan stopped')));
      setNodeText('[data-shieldx-scan-modal-intro]', activeProgressLabels.failedIntro || message || scanModalText('data-failed-intro', __('SHIELD-X could not continue this scan session.')));
      return;
    }

    setNodeText('[data-shieldx-scan-modal-title]', activeProgressLabels.runningTitle || scanModalText('data-running-title', __('Scanning in progress')));
    setNodeText('[data-shieldx-scan-modal-intro]', activeProgressLabels.runningIntro || scanModalText('data-running-intro', __('SHIELD-X is processing this scan in small batches.')));
  }

  function openScanModal(form) {
    if (!scanModal) {
      return;
    }

    scanModalReturnFocus = scanFormButton(form);
    scanModal.hidden = false;
    document.body.classList.add('shieldx-modal-open');
    setScanModalState('running', '');

    var resultButton = scanModal.querySelector('[data-shieldx-scan-modal-result]');
    var errorNode = scanModal.querySelector('[data-shieldx-scan-modal-error]');

    if (resultButton) {
      resultButton.hidden = true;
      resultButton.href = '#';
    }

    var continueButton = scanModal.querySelector('[data-shieldx-scan-modal-continue]');
    if (continueButton) {
      continueButton.textContent = activeProgressLabels.continueLabel || scanModalText('data-continue-label', __('Continue scan now'));
      continueButton.hidden = !!activeProgressLabels.autoOnly;
      continueButton.href = '#';
    }

    if (errorNode) {
      errorNode.hidden = true;
      errorNode.textContent = '';
    }

    var closeButton = scanModal.querySelector('[data-shieldx-scan-modal-hide]');
    if (closeButton && typeof closeButton.focus === 'function') {
      closeButton.focus();
    }
  }

  function hideScanModal() {
    var keepPolling = activeProgressShouldContinueWhenHidden();

    if (!scanModal || scanModal.hidden) {
      return;
    }

    if (!keepPolling) {
      finishScanForm();
      activeScanToken += 1;
    }

    scanModal.hidden = true;
    document.body.classList.remove('shieldx-modal-open');

    if (scanModalReturnFocus && typeof scanModalReturnFocus.focus === 'function') {
      scanModalReturnFocus.focus();
    }
  }

  function activeProgressShouldContinueWhenHidden() {
    var action = progressiveFormActionName(activeScanForm);

    return action === 'shieldx_prepare_core_release' || action === 'shieldx_prepare_plugin_packages';
  }

  function updateScanModalProgress(progress) {
    var percent = Math.max(0, Math.min(100, parseInt(progress.percent || 0, 10) || 0));
    var indeterminate = !!(progress && progress.indeterminate);
    var processed = Math.max(0, parseInt(progress.files_processed || 0, 10) || 0);
    var total = Math.max(0, parseInt(progress.files_total || 0, 10) || 0);
    var batches = Math.max(0, parseInt(progress.batches || 0, 10) || 0);
    var fill = scanModal ? scanModal.querySelector('[data-shieldx-scan-modal-fill]') : null;
    var progressbar = scanModal ? scanModal.querySelector('[data-shieldx-scan-modal-progressbar]') : null;
    var stageNode = scanModal ? scanModal.querySelector('[data-shieldx-scan-modal-stage]') : null;

    if (fill) {
      fill.style.width = indeterminate ? '' : percent + '%';
    }

    if (progressbar) {
      progressbar.classList.toggle('is-indeterminate', indeterminate);
      if (indeterminate) {
        progressbar.removeAttribute('aria-valuenow');
      } else {
        progressbar.setAttribute('aria-valuenow', String(percent));
      }
      if (progress && progress.stage_label) {
        progressbar.setAttribute('aria-valuetext', progress.stage_label);
      } else {
        progressbar.removeAttribute('aria-valuetext');
      }
    }

    if (stageNode) {
      stageNode.textContent = progress.stage_label || '';
      stageNode.hidden = !progress.stage_label;
    }

    if (progress.title_label) {
      setNodeText('[data-shieldx-scan-modal-title]', progress.title_label);
    }

    if (progress.intro_label) {
      setNodeText('[data-shieldx-scan-modal-intro]', progress.intro_label);
    }

    setNodeText('[data-shieldx-scan-modal-percent-label]', progress.percent_label || 'Progress');
    setNodeText('[data-shieldx-scan-modal-files-label]', progress.files_metric_label || 'Files');
    setNodeText('[data-shieldx-scan-modal-batches-label]', progress.batches_metric_label || 'Batches');
    setNodeText('[data-shieldx-scan-modal-percent]', progress.percent_value_label || (percent + '%'));
    setNodeText('[data-shieldx-scan-modal-files]', progress.files_label || (processed + ' / ' + total));
    setNodeText('[data-shieldx-scan-modal-batches]', progress.batches_label || String(batches));
    setNodeText('[data-shieldx-scan-modal-scope]', progress.scope_label || scanModalText('data-default-scope', 'Selected scan scopes'));
    renderScanModalFailures(progress);
  }

  function activeScanIsRestorePoint() {
    return progressiveFormActionName(activeScanForm) === 'shieldx_create_restore_point'
      || progressiveFormActionName(activeScanForm) === 'shieldx_recovery_create_restore_point';
  }

  function hasMeaningfulScanProgress(progress) {
    if (!progress || typeof progress !== 'object') {
      return false;
    }

    return !!(
      progress.indeterminate
      || progress.stage_label
      || progress.percent_label
      || progress.percent_value_label
      || progress.files_metric_label
      || progress.files_label
      || progress.batches_metric_label
      || progress.batches_label
      || progress.scope_label
      || parseInt(progress.percent || 0, 10) > 0
      || parseInt(progress.files_processed || 0, 10) > 0
      || parseInt(progress.files_total || 0, 10) > 0
      || parseInt(progress.batches || 0, 10) > 0
    );
  }

  function resolvedScanProgress(progress, status) {
    var next = progress && typeof progress === 'object' ? progress : {};

    if (!activeScanIsRestorePoint()) {
      return next;
    }

    if (!hasMeaningfulScanProgress(next) && activeScanProgress && status !== 'completed' && status !== 'failed') {
      return activeScanProgress;
    }

    if (!activeScanProgress || !hasMeaningfulScanProgress(next)) {
      return next;
    }

    next = Object.assign({}, activeScanProgress, next);
    if (!Object.prototype.hasOwnProperty.call(progress, 'indeterminate')) {
      next.indeterminate = false;
    }

    return next;
  }

  function ajaxScanUrl(url) {
    if (!url) {
      return '';
    }

    if (url.indexOf('shieldx_ajax_progress=') !== -1) {
      return url;
    }

    return url + (url.indexOf('?') === -1 ? '?' : '&') + 'shieldx_ajax_progress=1';
  }

  function htmlScanUrl(url) {
    var parsed;

    if (!url) {
      return '';
    }

    try {
      parsed = new URL(url, window.location.href);
      parsed.searchParams.delete('shieldx_ajax_progress');
      return parsed.toString();
    } catch (error) {
      return url
        .replace(/([?&])shieldx_ajax_progress=1&?/g, '$1')
        .replace(/[?&]$/, '');
    }
  }

  function fetchJson(url, options) {
    return fetch(url, options).then(function (response) {
      return response.text().then(function (text) {
        var payload = null;

        try {
          payload = JSON.parse(text);
        } catch (error) {
          throw new Error(scanModalText('data-json-error', __('SHIELD-X expected a JSON scan response.')));
        }

        if (!response.ok && !payload.error) {
          payload.error = response.statusText || scanModalText('data-request-error', __('Scan request failed.'));
        }

        return payload;
      });
    });
  }

  function finishScanForm() {
    if (activeScanTimer) {
      window.clearTimeout(activeScanTimer);
      activeScanTimer = 0;
    }

    if (activeScanForm) {
      setScanFormRunning(activeScanForm, false);
    }

    activeScanForm = null;
    activeScanNextUrl = '';
    activeScanPolls = 0;
    activeScanProgress = null;
    activeProgressRefreshSelector = '';
    activeProgressRefreshUrl = '';
  }

  function deferredProgressTargetRequest(target) {
    var container = target ? target.closest('[data-shieldx-admin-page-content]') : null;
    var endpoint = container ? (container.getAttribute('data-shieldx-admin-page-url') || '') : '';
    var nonce = container ? (container.getAttribute('data-shieldx-admin-page-nonce') || '') : '';
    var page = container ? (container.getAttribute('data-shieldx-admin-page') || '') : '';
    var formData;

    if (!container || !endpoint || !nonce || !page || !window.FormData) {
      return null;
    }

    formData = new window.FormData();
    formData.append('action', 'shieldx_admin_page_content');
    formData.append('_ajax_nonce', nonce);
    formData.append('page', page);
    appendAdminPageContext(formData);

    return fetch(endpoint, {
      method: 'POST',
      credentials: 'same-origin',
      body: formData,
      headers: {
        Accept: 'application/json'
      }
    }).then(function (response) {
      return response.json().then(function (payload) {
        if (!response.ok || !payload || !payload.success || !payload.data || typeof payload.data.html !== 'string') {
          return '';
        }

        return payload.data.html;
      });
    });
  }

  function refreshProgressTarget(selector, url) {
    var target;
    var request;

    if (!selector || !url || !window.fetch || !window.DOMParser) {
      return;
    }

    target = root.querySelector(selector);
    if (!target) {
      return;
    }

    request = deferredProgressTargetRequest(target);
    if (!request) {
      request = fetch(url, {
        credentials: 'same-origin',
        headers: {
          Accept: 'text/html'
        }
      }).then(function (response) {
        return response.ok ? response.text() : '';
      });
    }

    request.then(function (html) {
      var doc;
      var replacement;

      if (!html || html.indexOf('There has been a critical error on this website') !== -1 || html.indexOf('wp-die-message') !== -1) {
        return;
      }

      doc = new window.DOMParser().parseFromString(html, 'text/html');
      replacement = doc.querySelector(selector);
      if (replacement) {
        if (target.classList.contains('is-open')) {
          replacement.setAttribute('data-shieldx-accordion-open', '');
        }
        target.replaceWith(replacement);
        initInsertedAdminContent(replacement);
      }
    }).catch(function () {
      // The modal result link remains available if a background refresh fails.
    });
  }

  function showScanError(message, redirectUrl) {
    var resultButton = scanModal ? scanModal.querySelector('[data-shieldx-scan-modal-result]') : null;
    var continueButton = scanModal ? scanModal.querySelector('[data-shieldx-scan-modal-continue]') : null;
    var errorNode = scanModal ? scanModal.querySelector('[data-shieldx-scan-modal-error]') : null;

    finishScanForm();
    setScanModalState('failed', message);

    if (errorNode) {
      errorNode.textContent = message || scanModalText('data-request-error', __('Scan request failed.'));
      errorNode.hidden = false;
    }

    if (continueButton) {
      continueButton.hidden = true;
    }

    if (resultButton && redirectUrl) {
      resultButton.textContent = activeProgressLabels.backLabel || scanModalText('data-back-label', __('Back to scanner'));
      resultButton.href = redirectUrl;
      resultButton.hidden = false;
    }
  }

  function handleScanPayload(payload, scanToken) {
    if (scanToken !== activeScanToken) {
      return;
    }

    var responseProgress = payload && payload.progress ? payload.progress : {};
    var status = payload && payload.status ? payload.status : responseProgress.status;
    var progress = resolvedScanProgress(responseProgress, status);
    var resultButton = scanModal ? scanModal.querySelector('[data-shieldx-scan-modal-result]') : null;
    var continueButton = scanModal ? scanModal.querySelector('[data-shieldx-scan-modal-continue]') : null;

    if (status !== 'completed' && status !== 'failed' && !(payload && payload.ok === false)) {
      setScanModalState('running', '');
      if (resultButton) {
        resultButton.hidden = true;
        resultButton.href = '#';
      }
    }

    updateScanModalProgress(progress);
    activeScanProgress = progress;

    if (status === 'completed') {
      var completedForm = activeScanForm;
      var refreshSelector = activeProgressRefreshSelector;
      var refreshUrl = activeProgressRefreshUrl || (payload ? payload.redirect_url : '') || window.location.href;
      finishScanForm();
      setScanModalState('completed', '');

      if (continueButton) {
        continueButton.hidden = true;
      }

      if (resultButton) {
        resultButton.textContent = activeProgressLabels.resultLabel || scanModalText('data-result-label', __('View results'));
        resultButton.href = payload.redirect_url || window.location.href;
        resultButton.hidden = false;
      }

      refreshProgressTarget(refreshSelector, refreshUrl);

      if (completedForm && completedForm.hasAttribute('data-shieldx-core-progress-form')) {
        markOfficialCoreReady();
      }

      return;
    }

    if (status === 'failed' || (payload && payload.ok === false)) {
      showScanError((payload && payload.error) || scanModalText('data-request-error', __('Scan request failed.')), payload ? payload.redirect_url : '');
      return;
    }

    activeScanNextUrl = payload && payload.next_url ? payload.next_url : '';

    if (continueButton) {
      continueButton.hidden = !!activeProgressLabels.autoOnly || !activeScanNextUrl;
      continueButton.href = activeProgressLabels.autoOnly ? '#' : (htmlScanUrl(activeScanNextUrl) || '#');
    }

    activeScanPolls += 1;
    if (activeScanPolls >= maxScanPolls) {
      showScanError(scanModalText('data-timeout-error', __('Scan took too long. Please try again.')), payload ? payload.redirect_url : '');
      return;
    }

    if (activeScanTimer) {
      window.clearTimeout(activeScanTimer);
    }

    activeScanTimer = window.setTimeout(function () {
      continueModalScan(scanToken);
    }, activeScanPollDelay);
  }

  function continueModalScan(scanToken) {
    if (scanToken !== activeScanToken || !activeScanNextUrl) {
      return;
    }

    var url = ajaxScanUrl(activeScanNextUrl);

    activeScanTimer = 0;

    fetchJson(url, {
      credentials: 'same-origin',
      headers: {
        Accept: 'application/json',
        'X-ShieldX-Progress': '1'
      }
    }).then(function (payload) {
      handleScanPayload(payload, scanToken);
    }).catch(function (error) {
      if (scanToken !== activeScanToken) {
        return;
      }

      showScanError(error && error.message ? error.message : scanModalText('data-request-error', __('Scan request failed.')), '');
    });
  }

  function initialScanModalProgress(form) {
    if (progressiveFormActionName(form) === 'shieldx_run_vulnerability_scan') {
      return {
        indeterminate: true,
        stage_label: __('Checking installed versions and vulnerability feeds. This may take a moment.'),
        title_label: __('Vulnerability scan in progress'),
        intro_label: __('SHIELD-X is checking your installed WordPress components and the advisory feed. Results will appear here automatically.'),
        percent_label: __('Status'),
        percent_value_label: __('Working'),
        files_metric_label: __('Components'),
        files_label: __('Preparing inventory'),
        batches_metric_label: __('Advisory feed'),
        batches_label: __('Checking'),
        scope_label: __('WordPress core, plugins, themes, PHP, web server, database, and runtime libraries.')
      };
    }

    if (progressiveFormActionName(form) === 'shieldx_create_restore_point') {
      var fullBackup = !!form.querySelector('input[name="restore_point_mode"][value="full"]');

      return {
        indeterminate: true,
        stage_label: fullBackup
          ? __('Creating the recoverable full-backup job before database export begins.')
          : __('Creating the restore-point job before database export begins.'),
        percent_label: __('Status'),
        percent_value_label: __('Starting'),
        files_metric_label: fullBackup ? __('Backup') : __('Restore point'),
        files_label: fullBackup ? __('Preparing database export') : __('Preparing backup policy'),
        batches_metric_label: __('Database'),
        batches_label: __('Queued'),
        scope_label: fullBackup
          ? __('Full WordPress root and complete database.')
          : __('Selected backup policy and complete database.')
      };
    }

    return {
      percent: 0,
      files_processed: 0,
      files_total: 0,
      batches: 0,
      scope_label: scanModalText('data-default-scope', __('Selected scan scopes'))
    };
  }

  function startModalScan(form, submitter) {
    var formData = new FormData(form);
    var action = form.getAttribute('action') || window.location.href;

    if (submitter && submitter.name) {
      formData.set(submitter.name, submitter.value || '');
    }

    formData.set('shieldx_ajax_progress', '1');
    activeScanToken += 1;
    var scanToken = activeScanToken;
    activeScanForm = form;
    activeScanNextUrl = '';
    activeScanPolls = 0;
    activeScanPollDelay = Math.max(100, Math.min(2000, parseInt(form.getAttribute('data-shieldx-progress-poll-delay') || '750', 10) || 750));
    activeProgressRefreshSelector = form.getAttribute('data-shieldx-progress-refresh-selector') || '';
    activeProgressRefreshUrl = form.getAttribute('data-shieldx-progress-refresh-url') || '';
    activeProgressLabels = {
      runningTitle: form.getAttribute('data-shieldx-progress-running-title') || '',
      runningIntro: form.getAttribute('data-shieldx-progress-running-intro') || '',
      failedTitle: form.getAttribute('data-shieldx-progress-failed-title') || '',
      failedIntro: form.getAttribute('data-shieldx-progress-failed-intro') || '',
      completeTitle: form.getAttribute('data-shieldx-progress-complete-title') || '',
      completeIntro: form.getAttribute('data-shieldx-progress-complete-intro') || '',
      resultLabel: form.getAttribute('data-shieldx-progress-result-label') || '',
      continueLabel: form.getAttribute('data-shieldx-progress-continue-label') || '',
      backLabel: form.getAttribute('data-shieldx-progress-back-label') || '',
      autoOnly: form.getAttribute('data-shieldx-progress-auto-only') === '1'
    };
    setScanFormRunning(form, true);
    openScanModal(form);
    activeScanProgress = initialScanModalProgress(form);
    updateScanModalProgress(activeScanProgress);

    fetchJson(action, {
      method: (form.getAttribute('method') || 'post').toUpperCase(),
      body: formData,
      credentials: 'same-origin',
      headers: {
        Accept: 'application/json',
        'X-ShieldX-Progress': '1'
      }
    }).then(function (payload) {
      handleScanPayload(payload, scanToken);
    }).catch(function (error) {
      if (scanToken !== activeScanToken) {
        return;
      }

      showScanError(error && error.message ? error.message : scanModalText('data-request-error', __('Scan request failed.')), '');
    });
  }

  var progressiveActionNames = {
    shieldx_run_scan: true,
    shieldx_run_vulnerability_scan: true,
    shieldx_scan_log_rotation: true,
    shieldx_create_database_backup: true,
    shieldx_create_restore_point: true,
    shieldx_recovery_create_restore_point: true,
    shieldx_prepare_core_release: true,
    shieldx_prepare_plugin_packages: true
  };

  function progressiveFormActionName(form) {
    var input = form ? form.querySelector('input[name="action"]') : null;

    return input ? input.value : '';
  }

  function isPermissionFixSubmitter(submitter) {
    return !!(
      submitter &&
      (submitter.hasAttribute('data-shieldx-permission-fix-button') ||
        (submitter.name === 'lockdown_submit' && submitter.value === 'permission_fix'))
    );
  }

  function canUseProgressModal(form, submitter) {
    if (progressiveActionNames[progressiveFormActionName(form)]) {
      return true;
    }

    return !!(form && form.hasAttribute('data-shieldx-permission-fix-form') && isPermissionFixSubmitter(submitter));
  }

  function initProgressForms(scope) {
    (scope || root).querySelectorAll('[data-shieldx-scan-run-form], [data-shieldx-shadow-scan-form], [data-shieldx-backup-progress-form], [data-shieldx-core-progress-form], [data-shieldx-plugin-packages-progress-form], [data-shieldx-permission-fix-form]').forEach(function (form) {
      if (form.getAttribute('data-shieldx-progress-form-ready') === '1') {
        return;
      }

      form.setAttribute('data-shieldx-progress-form-ready', '1');
      form.querySelectorAll('button[type="submit"], input[type="submit"]').forEach(function (button) {
        button.addEventListener('click', function () {
          form.shieldxSubmitter = button;
        });
      });

      form.addEventListener('submit', function (event) {
        var submitter = event.submitter || form.shieldxSubmitter || null;

        if (shouldShowCorePrompt(form)) {
          event.preventDefault();
          openCorePromptModal(form);
          return;
        }

        if (!canUseProgressModal(form, submitter)) {
          return;
        }

        if (!window.fetch || !window.FormData || !scanModal) {
          setScanFormRunning(form, true);
          return;
        }

        event.preventDefault();

        if (form.dataset.shieldxSubmitting === 'true') {
          return;
        }

        if (corePromptModal && corePromptModal.contains(form)) {
          closeCorePromptModal();
        }

        startModalScan(form, submitter);
      });
    });
  }

  function initShadowBulkForms(scope) {
    (scope || root).querySelectorAll('[data-shieldx-shadow-bulk-form]').forEach(function (form) {
      if (form.getAttribute('data-shieldx-shadow-bulk-ready') === '1') {
        return;
      }

      form.setAttribute('data-shieldx-shadow-bulk-ready', '1');
      form.addEventListener('submit', function (event) {
        var button = form.querySelector('button[type="submit"]');
        var message = form.getAttribute('data-shieldx-submit-confirm') || '';

        if (form.dataset.shieldxSubmitting === 'true') {
          event.preventDefault();
          return;
        }

        if (message && !window.confirm(message)) {
          event.preventDefault();
          return;
        }

        form.dataset.shieldxSubmitting = 'true';
        if (button) {
          button.disabled = true;
          button.textContent = button.getAttribute('data-running-label') || __('Accepting files...');
        }
      });
    });
  }

  function initBulkScanAvailability(scope) {
    (scope || root).querySelectorAll('form.shieldx-bulk-toolbar').forEach(function (form) {
      var select = form.querySelector('select[name="bulk_scan_action"]');
      var missingNotice = form.querySelector('[data-shieldx-bulk-missing-selection]');
      var fileActionValues = ['recheck', 'trust_current', 'quarantine'];

      if (!select || form.getAttribute('data-shieldx-bulk-availability-ready') === '1') {
        return;
      }

      form.setAttribute('data-shieldx-bulk-availability-ready', '1');

      function hasMissingSelection() {
        return Array.prototype.some.call(
          document.querySelectorAll('input[name="bulk_threat_ids[]"][data-shieldx-file-available="0"]'),
          function (input) {
            return input.form === form && input.checked;
          }
        );
      }

      function sync() {
        var missingSelected = hasMissingSelection();

        fileActionValues.forEach(function (value) {
          var option = select.querySelector('option[value="' + value + '"]');
          if (option) {
            option.disabled = missingSelected;
          }
        });

        if (missingSelected && fileActionValues.indexOf(select.value) !== -1) {
          select.value = 'ignore_once';
        }

        if (missingNotice) {
          missingNotice.hidden = !missingSelected;
        }
      }

      document.querySelectorAll('input[name="bulk_threat_ids[]"]').forEach(function (input) {
        if (input.form === form) {
          input.addEventListener('change', sync);
        }
      });
      select.addEventListener('change', sync);
      sync();
    });
  }

  function initWafModeDisclosure(scope) {
    (scope || root).querySelectorAll('[data-shieldx-waf-mode-band]').forEach(function (band) {
      var inputs = Array.prototype.slice.call(band.querySelectorAll('input[name="waf_mode"]'));
      var label = band.querySelector('[data-shieldx-waf-mode-label]');

      if (inputs.length === 0 || band.getAttribute('data-shieldx-waf-mode-ready') === '1') {
        return;
      }

      function syncSelectedMode() {
        var selected = null;

        inputs.some(function (input) {
          if (!input.checked) {
            return false;
          }

          selected = input;
          return true;
        });

        if (!selected) {
          return;
        }

        band.setAttribute('data-shieldx-waf-mode', selected.value);
        if (label) {
          var title = selected.parentNode ? selected.parentNode.querySelector('strong') : null;
          label.textContent = title ? title.textContent : selected.value;
        }
      }

      band.setAttribute('data-shieldx-waf-mode-ready', '1');
      inputs.forEach(function (input) {
        input.addEventListener('change', syncSelectedMode);
      });
      syncSelectedMode();
    });
  }

  function initHardeningBrowserPreflight(scope) {
    (scope || root).querySelectorAll('[data-shieldx-hardening-form]').forEach(function (form) {
      var endpoint;
      var nonce;
      var status;
      var submitButton;

      if (form.getAttribute('data-shieldx-hardening-preflight-ready') === '1') {
        return;
      }

      form.setAttribute('data-shieldx-hardening-preflight-ready', '1');
      endpoint = form.getAttribute('data-shieldx-hardening-preflight-url') || '';
      nonce = form.getAttribute('data-shieldx-hardening-preflight-nonce') || '';
      status = form.querySelector('[data-shieldx-hardening-preflight-status]');
      submitButton = form.querySelector('button[type="submit"], input[type="submit"]');

      function message(name, fallback) {
        return form.getAttribute(name) || fallback;
      }

      function setStatus(text, isError) {
        if (!status) {
          return;
        }

        status.textContent = text;
        status.hidden = !text;
        status.classList.toggle('shieldx-form-status--error', !!isError);
      }

      function nativeSubmit() {
        form.setAttribute('data-shieldx-hardening-preflight-submitting', '1');
        if (submitButton) {
          submitButton.disabled = true;
        }
        window.HTMLFormElement.prototype.submit.call(form);
      }

      function submitPreparedJob(jobId) {
        var jobField = form.querySelector('input[name="shieldx_htaccess_browser_job"]');

        if (!jobField) {
          jobField = document.createElement('input');
          jobField.type = 'hidden';
          jobField.name = 'shieldx_htaccess_browser_job';
          form.appendChild(jobField);
        }
        jobField.value = jobId;
        nativeSubmit();
      }

      function cancelJob(jobId) {
        var cancelData;

        if (!jobId || !window.fetch || !window.FormData) {
          return;
        }

        cancelData = new window.FormData();
        cancelData.append('action', 'shieldx_prepare_hardening_preflight');
        cancelData.append('_ajax_nonce', nonce);
        cancelData.append('cancel_job_id', jobId);
        window.fetch(endpoint, {
          method: 'POST',
          credentials: 'same-origin',
          cache: 'no-store',
          body: cancelData
        }).catch(function () {});
      }

      function reportFailedJob(jobId, diagnostic) {
        var reportData;

        if (!jobId || !window.fetch || !window.FormData || !window.Promise) {
          return window.Promise.reject(new Error('Browser diagnostic reporting is unavailable.'));
        }

        diagnostic = diagnostic || {};
        reportData = new window.FormData();
        reportData.append('action', 'shieldx_prepare_hardening_preflight');
        reportData.append('_ajax_nonce', nonce);
        reportData.append('report_job_id', jobId);
        reportData.append('probe_label', String(diagnostic.label || ''));
        reportData.append('probe_http_code', String(diagnostic.httpCode || 0));
        reportData.append('probe_server', String(diagnostic.server || ''));
        reportData.append('probe_cf_ray', String(diagnostic.cfRay || ''));
        reportData.append('probe_cf_cache_status', String(diagnostic.cfCacheStatus || ''));
        reportData.append('probe_cf_mitigated', String(diagnostic.cfMitigated || ''));
        reportData.append('probe_content_type', String(diagnostic.contentType || ''));
        reportData.append('probe_cloudflare', diagnostic.cloudflare ? '1' : '0');

        return window.fetch(endpoint, {
          method: 'POST',
          credentials: 'same-origin',
          cache: 'no-store',
          referrer: window.location.href,
          referrerPolicy: 'same-origin',
          body: reportData
        }).then(function (response) {
          return response.json().then(function (payload) {
            if (!response.ok || !payload || !payload.success) {
              throw new Error('Browser diagnostic reporting failed.');
            }

            return payload.data || {};
          });
        });
      }

      function sameOriginProbeUrl(url) {
        var parsed;

        if (!window.URL) {
          return url;
        }

        parsed = new window.URL(url, window.location.href);
        return window.location.origin + parsed.pathname + parsed.search;
      }

      function reloadWithHardeningErrorNotice() {
        var nextUrl;

        if (!window.URL) {
          window.location.reload();
          return;
        }

        nextUrl = new window.URL(window.location.href);
        nextUrl.searchParams.set('shieldx_hardening_error', '1');
        window.location.assign(nextUrl.toString());
      }

      function verifyProbe(probe) {
        var probeUrl = sameOriginProbeUrl(String(probe.url || ''));
        var expectedToken = String(probe.token || '');
        var probeLabel = String(probe.label || '');

        if (!probeUrl || !expectedToken) {
          return Promise.reject(new Error(message(
            'data-shieldx-hardening-preflight-error',
            'SHIELD-X could not verify the selected .htaccess rules in this browser.'
          )));
        }

        return window.fetch(probeUrl, {
          method: 'GET',
          credentials: 'same-origin',
          cache: 'no-store',
          redirect: 'follow',
          referrer: window.location.href,
          referrerPolicy: 'same-origin'
        }).then(function (response) {
          var server = response.headers.get('server') || '';
          var cfRay = response.headers.get('cf-ray') || '';
          var cfCacheStatus = response.headers.get('cf-cache-status') || '';
          var cfMitigated = response.headers.get('cf-mitigated') || '';
          var contentType = response.headers.get('content-type') || '';

          return response.text().then(function (body) {
            var lowerBody = body.toLowerCase();
            var tokenMatched = body.indexOf(expectedToken) !== -1;
            var expectedPhpBlock = probeLabel === 'data' && response.status === 403 && tokenMatched;
            var cloudflareEdge = !!cfRay || server.toLowerCase().indexOf('cloudflare') !== -1;
            var cloudflarePage = cfMitigated.toLowerCase() === 'challenge' || (
              cloudflareEdge &&
              (contentType === '' || contentType.toLowerCase().indexOf('text/html') !== -1) &&
              (
                lowerBody.indexOf('attention required! | cloudflare') !== -1 ||
                lowerBody.indexOf('cloudflare ray id') !== -1 ||
                lowerBody.indexOf('sorry, you have been blocked') !== -1 ||
                lowerBody.indexOf('<title>just a moment...</title>') !== -1 ||
                lowerBody.indexOf('/cdn-cgi/challenge-platform/') !== -1
              )
            );
            var cloudflareFailure = cloudflarePage;

            if ((response.ok && tokenMatched) || expectedPhpBlock) {
              return;
            }

            var probeError = new Error(message(
              cloudflareFailure
                ? 'data-shieldx-hardening-preflight-cloudflare'
                : 'data-shieldx-hardening-preflight-error',
              'SHIELD-X could not verify the selected .htaccess rules in this browser.'
            ));
            probeError.shieldxProbeDiagnostic = {
              label: probeLabel,
              httpCode: response.status,
              server: server,
              cfRay: cfRay,
              cfCacheStatus: cfCacheStatus,
              cfMitigated: cfMitigated,
              contentType: contentType,
              cloudflare: cloudflareFailure
            };
            throw probeError;
          });
        }).catch(function (error) {
          var networkError;

          if (error && error.shieldxProbeDiagnostic) {
            throw error;
          }

          networkError = new Error(error && error.message
            ? error.message
            : message(
              'data-shieldx-hardening-preflight-error',
              'SHIELD-X could not verify the selected .htaccess rules in this browser.'
            ));
          networkError.shieldxProbeDiagnostic = {
            label: probeLabel,
            httpCode: 0,
            server: '',
            cfRay: '',
            cfCacheStatus: '',
            cfMitigated: '',
            contentType: '',
            cloudflare: false
          };
          throw networkError;
        });
      }

      form.addEventListener('submit', function (event) {
        var formData;
        var preparedJobId = '';

        if (form.getAttribute('data-shieldx-hardening-preflight-submitting') === '1') {
          return;
        }
        if (!endpoint || !nonce || !window.fetch || !window.FormData || !window.Promise) {
          return;
        }

        event.preventDefault();
        setStatus(message(
          'data-shieldx-hardening-preflight-working',
          'Testing the selected .htaccess rules...'
        ), false);
        if (submitButton) {
          submitButton.disabled = true;
        }

        formData = new window.FormData(form);
        formData.set('action', 'shieldx_prepare_hardening_preflight');
        formData.set('_ajax_nonce', nonce);
        formData.delete('_wpnonce');
        formData.delete('shieldx_htaccess_browser_job');

        window.fetch(endpoint, {
          method: 'POST',
          credentials: 'same-origin',
          cache: 'no-store',
          body: formData
        }).then(function (response) {
          return response.json().then(function (payload) {
            if (!response.ok || !payload || !payload.success || !payload.data) {
              var preparationError = new Error(
                payload && payload.data && payload.data.message
                  ? String(payload.data.message)
                  : ''
              );
              preparationError.shieldxPreparationFailed = !!(
                payload &&
                payload.data &&
                payload.data.status
              );
              throw preparationError;
            }

            return payload.data;
          });
        }).then(function (prepared) {
          var probes = Array.isArray(prepared.probes) ? prepared.probes : [];

          preparedJobId = String(prepared.job_id || '');
          if (!preparedJobId || !probes.length) {
            nativeSubmit();
            return null;
          }

          return Promise.all(probes.map(verifyProbe)).then(function () {
            submitPreparedJob(preparedJobId);
          });
        }).catch(function (error) {
          if (!preparedJobId) {
            if (error && error.shieldxPreparationFailed) {
              reloadWithHardeningErrorNotice();
              return;
            }
            nativeSubmit();
            return;
          }

          reportFailedJob(preparedJobId, error && error.shieldxProbeDiagnostic)
            .then(function (recorded) {
              var retryProbe = recorded && recorded.retry_probe;

              if (!retryProbe) {
                reloadWithHardeningErrorNotice();
                return null;
              }

              setStatus(message(
                'data-shieldx-hardening-preflight-working',
                'Testing the selected .htaccess rules...'
              ), false);

              return verifyProbe(retryProbe).then(function () {
                submitPreparedJob(preparedJobId);
              }).catch(function (retryError) {
                return reportFailedJob(
                  preparedJobId,
                  retryError && retryError.shieldxProbeDiagnostic
                ).then(function () {
                  reloadWithHardeningErrorNotice();
                }).catch(function () {
                  cancelJob(preparedJobId);
                  setStatus(
                    retryError && retryError.message
                      ? retryError.message
                      : message(
                        'data-shieldx-hardening-preflight-error',
                        'SHIELD-X could not verify the selected .htaccess rules in this browser.'
                      ),
                    true
                  );
                  if (submitButton) {
                    submitButton.disabled = false;
                  }
                });
              });
            })
            .catch(function () {
              cancelJob(preparedJobId);
              setStatus(
                error && error.message
                  ? error.message
                  : message(
                    'data-shieldx-hardening-preflight-error',
                    'SHIELD-X could not verify the selected .htaccess rules in this browser.'
                  ),
                true
              );
              if (submitButton) {
                submitButton.disabled = false;
              }
            });
        });
      });
    });
  }

  function initScanModalControls() {
    if (!scanModal || scanModal.getAttribute('data-shieldx-scan-modal-ready') === '1') {
      return;
    }

    scanModal.setAttribute('data-shieldx-scan-modal-ready', '1');
    scanModal.querySelectorAll('[data-shieldx-scan-modal-hide]').forEach(function (button) {
      button.addEventListener('click', function (event) {
        event.preventDefault();
        hideScanModal();
      });
    });

    var manualContinue = scanModal.querySelector('[data-shieldx-scan-modal-continue]');
    if (manualContinue) {
      manualContinue.addEventListener('click', function (event) {
        if (!activeScanNextUrl) {
          return;
        }

        event.preventDefault();

        if (activeScanTimer) {
          window.clearTimeout(activeScanTimer);
          activeScanTimer = 0;
        }

        continueModalScan(activeScanToken);
      });
    }
  }

  function initCorePromptModalControls() {
    corePromptModal = root.querySelector('[data-shieldx-core-prompt-modal]');
    if (!corePromptModal || corePromptModal.getAttribute('data-shieldx-core-prompt-ready') === '1') {
      return;
    }

    corePromptModal.setAttribute('data-shieldx-core-prompt-ready', '1');
    corePromptModal.querySelectorAll('[data-shieldx-core-prompt-close]').forEach(function (button) {
      button.addEventListener('click', function (event) {
        event.preventDefault();
        closeCorePromptModal();
        pendingCorePromptForm = null;
      });
    });

    var scanAnyway = corePromptModal.querySelector('[data-shieldx-core-prompt-scan-anyway]');
    if (scanAnyway) {
      scanAnyway.addEventListener('click', function (event) {
        var form = pendingCorePromptForm;

        event.preventDefault();

        if (!form) {
          closeCorePromptModal();
          return;
        }

        markCorePromptSeen(form);
        closeCorePromptModal();
        pendingCorePromptForm = null;

        if (window.fetch && window.FormData && scanModal) {
          startModalScan(form);
          return;
        }

        form.submit();
      });
    }
  }

  initProgressForms(root);
  initHardeningBrowserPreflight(root);
  initScanModalControls();
  initCorePromptModalControls();

  function fallbackCopy(text) {
    var textarea = document.createElement('textarea');
    textarea.value = text;
    textarea.setAttribute('readonly', 'readonly');
    textarea.style.position = 'fixed';
    textarea.style.left = '-9999px';
    document.body.appendChild(textarea);
    textarea.select();

    try {
      document.execCommand('copy');
    } finally {
      document.body.removeChild(textarea);
    }
  }

  function markCopied(button) {
    if (!button.dataset.shieldxOriginalLabel) {
      button.dataset.shieldxOriginalLabel = button.textContent;
    }

    button.textContent = __('Copied');

    window.setTimeout(function () {
      button.textContent = button.dataset.shieldxOriginalLabel || __('Copy');
    }, 1600);
  }

  function markDownloaded(button) {
    if (!button.dataset.shieldxOriginalLabel) {
      button.dataset.shieldxOriginalLabel = button.textContent;
    }

    button.textContent = button.getAttribute('data-shieldx-downloaded-label') || __('Downloaded');

    window.setTimeout(function () {
      button.textContent = button.dataset.shieldxOriginalLabel || button.getAttribute('data-shieldx-download-label') || __('Download codes');
    }, 1800);
  }

  function downloadTextFile(filename, text) {
    var anchor = document.createElement('a');
    var objectUrl = '';

    if (window.Blob && window.URL && window.URL.createObjectURL) {
      objectUrl = window.URL.createObjectURL(new Blob([text], { type: 'text/plain;charset=utf-8' }));
      anchor.href = objectUrl;
    } else {
      anchor.href = 'data:text/plain;charset=utf-8,' + encodeURIComponent(text);
    }

    anchor.download = filename;
    anchor.style.display = 'none';
    document.body.appendChild(anchor);
    anchor.click();
    document.body.removeChild(anchor);

    if (objectUrl) {
      window.setTimeout(function () {
        window.URL.revokeObjectURL(objectUrl);
      }, 0);
    }
  }

  function initRecoveryCodeDownloads(scope) {
    (scope || root).querySelectorAll('[data-shieldx-download-recovery-codes]').forEach(function (button) {
      if (button.getAttribute('data-shieldx-download-ready') === '1') {
        return;
      }

      button.setAttribute('data-shieldx-download-ready', '1');
      button.addEventListener('click', function () {
        var panel = button.closest('.shieldx-recovery-codes');
        var codes = [];

        if (!panel) {
          return;
        }

        panel.querySelectorAll('.shieldx-code-grid code').forEach(function (code) {
          var value = code.textContent.trim();

          if (value) {
            codes.push(value);
          }
        });

        if (!codes.length) {
          return;
        }

        downloadTextFile('shield-x-recovery-codes.txt', [
          button.getAttribute('data-shieldx-download-title') || 'SHIELD-X Recovery Codes',
          'Generated: ' + new Date().toISOString(),
          '',
          button.getAttribute('data-shieldx-download-note') || '',
          '',
          codes.join('\n')
        ].join('\n'));
        markDownloaded(button);
      });
    });
  }

  initRecoveryCodeDownloads(root);

  function syncRecoveryCliCommand(select) {
    var selected = select.options[select.selectedIndex];
    var command = selected ? selected.getAttribute('data-shieldx-command') || '' : '';
    var block = select.closest('.shieldx-recovery-command');
    var output = block ? block.querySelector('code') : null;
    var copy = block ? block.querySelector('[data-shieldx-copy]') : null;

    if (!command || !block || !output || !copy) {
      return;
    }

    output.textContent = command;
    copy.setAttribute('data-shieldx-copy', command);
  }

  function initRecoveryCliSelects(scope) {
    (scope || root).querySelectorAll('[data-shieldx-cli-user-select]').forEach(function (select) {
      if (select.getAttribute('data-shieldx-cli-ready') === '1') {
        return;
      }

      select.setAttribute('data-shieldx-cli-ready', '1');
      syncRecoveryCliCommand(select);
      select.addEventListener('change', function () {
        syncRecoveryCliCommand(select);
      });
    });
  }

  initRecoveryCliSelects(root);

  var modal = root.querySelector('[data-shieldx-modal]');
  var modalReturnFocus = null;
  var formModalReturnFocus = null;

  function setText(element, value) {
    if (element) {
      element.textContent = value || '';
    }
  }

  function activeFormModal() {
    return root.querySelector('[data-shieldx-form-modal]:not([hidden])');
  }

  function focusableElements(container) {
    if (!container) {
      return [];
    }

    return Array.prototype.slice.call(container.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'))
      .filter(function (element) {
        return element.offsetParent !== null;
      });
  }

  function setLicenseDialogLabels(formModal, step) {
    var dialog = formModal ? formModal.querySelector('[role="dialog"]') : null;

    if (!dialog) {
      return;
    }

    if (step === 'support') {
      dialog.setAttribute('aria-labelledby', 'shieldx-license-support-title');
      dialog.setAttribute('aria-describedby', 'shieldx-license-support-intro');
      return;
    }

    dialog.setAttribute('aria-labelledby', 'shieldx-license-title');
    dialog.setAttribute('aria-describedby', 'shieldx-license-intro');
  }

  function resetLicenseSupportStep(formModal) {
    var supportIntro = formModal ? formModal.querySelector('[data-shieldx-license-support-intro]') : null;
    var activationStep = formModal ? formModal.querySelector('[data-shieldx-license-activation-step]') : null;

    if (!supportIntro || !activationStep) {
      return;
    }

    supportIntro.hidden = false;
    activationStep.hidden = true;
    setLicenseDialogLabels(formModal, 'support');
  }

  function revealLicenseActivationStep(button) {
    var formModal = button ? button.closest('[data-shieldx-form-modal]') : null;
    var supportIntro = formModal ? formModal.querySelector('[data-shieldx-license-support-intro]') : null;
    var activationStep = formModal ? formModal.querySelector('[data-shieldx-license-activation-step]') : null;
    var licenseInput;

    if (!supportIntro || !activationStep) {
      return;
    }

    supportIntro.hidden = true;
    activationStep.hidden = false;
    setLicenseDialogLabels(formModal, 'activation');
    licenseInput = activationStep.querySelector('input[name="license_key"]');

    if (licenseInput && typeof licenseInput.focus === 'function') {
      licenseInput.focus();
    }
  }

  function closeFormModal(formModal) {
    var target = formModal || activeFormModal();

    if (!target || target.hidden) {
      return;
    }

    resetLicenseSupportStep(target);
    target.hidden = true;
    document.body.classList.remove('shieldx-modal-open');

    if (formModalReturnFocus && typeof formModalReturnFocus.focus === 'function') {
      formModalReturnFocus.focus();
    }

    formModalReturnFocus = null;
  }

  function openFormModalElement(formModal, returnFocus) {
    if (!formModal) {
      return;
    }

    formModalReturnFocus = returnFocus || null;
    resetLicenseSupportStep(formModal);
    formModal.hidden = false;
    document.body.classList.add('shieldx-modal-open');

    var firstInput = formModal.querySelector('[data-shieldx-modal-initial-focus]:not([disabled])');

    if (!firstInput || firstInput.closest('[hidden]')) {
      firstInput = formModal.querySelector('[data-shieldx-license-support-next]:not([disabled])');
    }

    if (!firstInput || firstInput.closest('[hidden]')) {
      firstInput = formModal.querySelector('input[name="license_key"]:not([disabled])');
    }

    if (!firstInput || firstInput.closest('[hidden]')) {
      firstInput = formModal.querySelector('button:not([disabled]), a[href]');
    }

    if (!firstInput || firstInput.closest('[hidden]')) {
      var focusable = focusableElements(formModal);
      firstInput = focusable.length ? focusable[0] : null;
    }

    if (firstInput && typeof firstInput.focus === 'function') {
      firstInput.focus();
    }
  }

  function openFormModal(button) {
    var modalId = button ? button.getAttribute('aria-controls') || '' : '';
    var formModal = modalId ? document.getElementById(modalId) : null;

    openFormModalElement(formModal, button);
  }

  function openHashFormModal(target) {
    if (!target || !target.hasAttribute('data-shieldx-form-modal')) {
      return false;
    }

    openFormModalElement(target, null);

    return true;
  }

  function notificationProfileEvents(button) {
    try {
      var parsed = JSON.parse(button.getAttribute('data-shieldx-events') || '[]');
      return Array.isArray(parsed) ? parsed : [];
    } catch (error) {
      return [];
    }
  }

  function applyNotificationProfile(button) {
    var form = button ? button.closest('form') : null;

    if (!form) {
      return;
    }

    var selected = {};
    notificationProfileEvents(button).forEach(function (eventKey) {
      selected[eventKey] = true;
    });

    form.querySelectorAll('[data-shieldx-notification-event]').forEach(function (checkbox) {
      checkbox.checked = !!selected[checkbox.value];
    });

    var profileInput = form.querySelector('[data-shieldx-notification-profile-input]');
    if (profileInput) {
      profileInput.value = button.getAttribute('data-shieldx-notification-profile') || 'normal';
    }

    form.querySelectorAll('[data-shieldx-notification-profile]').forEach(function (profileButton) {
      var active = profileButton === button;
      profileButton.classList.toggle('is-active', active);
      profileButton.setAttribute('aria-pressed', active ? 'true' : 'false');
    });
  }

  function initNotificationProfiles(scope) {
    (scope || root).querySelectorAll('[data-shieldx-notification-profile]').forEach(function (button) {
      var form = button.closest('form');
      var profileInput = form ? form.querySelector('[data-shieldx-notification-profile-input]') : null;
      var active = profileInput && profileInput.value === button.getAttribute('data-shieldx-notification-profile');
      button.classList.toggle('is-active', !!active);
      button.setAttribute('aria-pressed', active ? 'true' : 'false');
    });
  }

  initNotificationProfiles(root);

  function syncNotificationDigestCadence(select) {
    var form = select ? select.closest('form') : null;
    var custom = form ? form.querySelector('[data-shieldx-notification-digest-custom]') : null;
    var showCustom = select && select.value === 'every';

    if (!custom) {
      return;
    }

    custom.hidden = !showCustom;
    custom.style.display = showCustom ? '' : 'none';
    custom.setAttribute('aria-hidden', showCustom ? 'false' : 'true');
  }

  function initNotificationDigestCadence(scope) {
    (scope || root).querySelectorAll('[data-shieldx-notification-digest-cadence]').forEach(function (select) {
      syncNotificationDigestCadence(select);
      if (select.getAttribute('data-shieldx-digest-cadence-ready') === '1') {
        return;
      }

      select.setAttribute('data-shieldx-digest-cadence-ready', '1');
      select.addEventListener('change', function () {
        syncNotificationDigestCadence(select);
      });
    });
  }

  initNotificationDigestCadence(root);

  function modalStepsFromButton(button) {
    try {
      var parsed = JSON.parse(button.getAttribute('data-shieldx-modal-steps') || '[]');
      return Array.isArray(parsed) ? parsed : [];
    } catch (error) {
      return [];
    }
  }

  function modalCommandsFromButton(button) {
    try {
      var parsed = JSON.parse(button.getAttribute('data-shieldx-modal-commands') || '[]');
      return Array.isArray(parsed) ? parsed : [];
    } catch (error) {
      return [];
    }
  }

  function appendRecoveryCommand(container, commandConfig) {
    var command = commandConfig && typeof commandConfig.command === 'string' ? commandConfig.command : '';
    var userOptions = commandConfig && Array.isArray(commandConfig.user_options) ? commandConfig.user_options : [];
    var block = document.createElement('div');
    var label = document.createElement('span');
    var code = document.createElement('code');
    var button = document.createElement('button');

    if (!command && userOptions.length && userOptions[0].command) {
      command = userOptions[0].command;
    }

    if (!command) {
      return;
    }

    block.className = 'shieldx-recovery-command';
    label.textContent = commandConfig.label || __('CLI command');
    block.appendChild(label);

    if (userOptions.length) {
      var selectLabel = document.createElement('label');
      var selectText = document.createElement('span');
      var select = document.createElement('select');

      selectLabel.className = 'shieldx-recovery-command-user';
      selectText.textContent = __('Administrator to reset');
      select.setAttribute('data-shieldx-cli-user-select', '');

      userOptions.forEach(function (option) {
        if (!option || !option.id || !option.command) {
          return;
        }

        var item = document.createElement('option');
        item.value = option.id;
        item.textContent = option.label || option.id;
        item.setAttribute('data-shieldx-command', option.command);
        select.appendChild(item);
      });

      selectLabel.appendChild(selectText);
      selectLabel.appendChild(select);
      block.appendChild(selectLabel);
    }

    code.textContent = command;
    block.appendChild(code);

    button.type = 'button';
    button.className = 'button button-small';
    button.setAttribute('data-shieldx-copy', command);
    button.textContent = __('Copy command');
    block.appendChild(button);

    if (commandConfig.note) {
      var note = document.createElement('small');
      note.textContent = commandConfig.note;
      block.appendChild(note);
    }

    container.appendChild(block);

    var selectControl = block.querySelector('[data-shieldx-cli-user-select]');
    if (selectControl) {
      syncRecoveryCliCommand(selectControl);
      selectControl.addEventListener('change', function () {
        syncRecoveryCliCommand(selectControl);
      });
    }
  }

  function renderRecoveryModalCommands(container, commands) {
    if (!container) {
      return;
    }

    container.textContent = '';
    container.hidden = !commands.length;

    commands.forEach(function (commandConfig) {
      appendRecoveryCommand(container, commandConfig || {});
    });
  }

  function closeModal() {
    if (!modal || modal.hidden) {
      return;
    }

    modal.hidden = true;
    document.body.classList.remove('shieldx-modal-open');

    if (modalReturnFocus && typeof modalReturnFocus.focus === 'function') {
      modalReturnFocus.focus();
    }

    modalReturnFocus = null;
  }

  function openRecoveryModal(button) {
    if (!modal || !button) {
      return;
    }

    var stepsList = modal.querySelector('[data-shieldx-modal-steps]');
    var action = modal.querySelector('[data-shieldx-modal-action]');
    var commandsContainer = modal.querySelector('[data-shieldx-modal-commands-container]');
    var steps = modalStepsFromButton(button);
    var commands = modalCommandsFromButton(button);

    setText(modal.querySelector('[data-shieldx-modal-kicker]'), button.getAttribute('data-shieldx-modal-kicker') || '');
    setText(modal.querySelector('[data-shieldx-modal-title]'), button.getAttribute('data-shieldx-modal-title') || '');
    setText(modal.querySelector('[data-shieldx-modal-intro]'), button.getAttribute('data-shieldx-modal-intro') || '');

    if (stepsList) {
      stepsList.textContent = '';
      steps.forEach(function (step) {
        var item = document.createElement('li');
        item.textContent = step;
        stepsList.appendChild(item);
      });
    }

    renderRecoveryModalCommands(commandsContainer, commands);

    if (action) {
      action.textContent = button.getAttribute('data-shieldx-modal-action-label') || __('Open settings');
      action.href = button.getAttribute('data-shieldx-modal-action-url') || '#';
    }

    modalReturnFocus = button;
    modal.hidden = false;
    document.body.classList.add('shieldx-modal-open');

    var closeButton = modal.querySelector('button[data-shieldx-modal-close]');
    if (closeButton && typeof closeButton.focus === 'function') {
      closeButton.focus();
    }
  }

  function focusableModalElements() {
    if (!modal || modal.hidden) {
      return [];
    }

    return Array.prototype.slice.call(modal.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'))
      .filter(function (element) {
        return element.offsetParent !== null;
      });
  }

  if (modal) {
    modal.querySelectorAll('[data-shieldx-modal-close]').forEach(function (button) {
      button.addEventListener('click', closeModal);
    });

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

      if (event.key !== 'Tab' || modal.hidden) {
        return;
      }

      var focusable = focusableModalElements();
      var first = focusable[0];
      var last = focusable[focusable.length - 1];

      if (!first || !last) {
        return;
      }

      if (event.shiftKey && document.activeElement === first) {
        event.preventDefault();
        last.focus();
        return;
      }

      if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    });
  }

  document.addEventListener('keydown', function (event) {
    var formModal = activeFormModal();

    if (!formModal) {
      return;
    }

    if (event.key === 'Escape') {
      closeFormModal(formModal);
      return;
    }

    if (event.key !== 'Tab') {
      return;
    }

    var focusable = focusableElements(formModal);
    var first = focusable[0];
    var last = focusable[focusable.length - 1];

    if (!first || !last) {
      return;
    }

    if (event.shiftKey && document.activeElement === first) {
      event.preventDefault();
      last.focus();
      return;
    }

    if (!event.shiftKey && document.activeElement === last) {
      event.preventDefault();
      first.focus();
    }
  });

  function initInsertedAdminContent(scope) {
    var target;

    (scope || root).querySelectorAll('details.shieldx-accordion-panel:not([data-shieldx-accordion-open])').forEach(function (panel) {
      panel.open = false;
    });

    initAutoRedirects();
    initSectionAccordions();
    equalizeScopeGridCards();
    initMetricTitles(scope || root);
    initOverviewCharts();
    initOverviewCards(scope || root);
    initShadowHistory();
    initManualBackupsList();
    initRestorePointsList();
    initWafLatestHitsList();
    initLogFilesList();
    initPageTabSelectors(scope || root);
    initToggleGroups(scope || root);
    initSelectConditionals(scope || root);
    initRestoreTools(scope || root);
    initDisclosureToggles(scope || root);
    initLinkedCodeScrollAreas(scope || root);
    initProfilers(scope || root);
    initTokenFields(scope || root);
    initProgressForms(scope || root);
    initShadowBulkForms(scope || root);
    initBulkScanAvailability(scope || root);
    initWafModeDisclosure(scope || root);
    initHardeningBrowserPreflight(scope || root);
    initPluginPackageUploads(scope || root);
    initScanModalControls();
    initCorePromptModalControls();
    initRecoveryCodeDownloads(scope || root);
    initRecoveryCliSelects(scope || root);
    initNotificationProfiles(scope || root);
    initNotificationDigestCadence(scope || root);
    initToastNotices();

    target = hashTarget();
    if (openHashFormModal(target)) {
      return;
    }

    if (target && typeof target.scrollIntoView === 'function') {
      onNextFrame(function () {
        target.scrollIntoView({ block: 'start' });
      });
    }
  }

  window.addEventListener('hashchange', function () {
    openHashFormModal(hashTarget());
  });

  root.addEventListener('click', function (event) {
    var confirmTarget = event.target.closest('[data-shieldx-confirm]');

    if (confirmTarget && root.contains(confirmTarget) && !window.confirm(confirmTarget.getAttribute('data-shieldx-confirm') || '')) {
      event.preventDefault();
      event.stopPropagation();
      return;
    }

    var notificationProfileButton = event.target.closest('[data-shieldx-notification-profile]');

    if (notificationProfileButton) {
      event.preventDefault();
      applyNotificationProfile(notificationProfileButton);
      return;
    }

    var licenseSupportButton = event.target.closest('[data-shieldx-license-support-next]');

    if (licenseSupportButton) {
      event.preventDefault();
      revealLicenseActivationStep(licenseSupportButton);
      return;
    }

    var formOpenButton = event.target.closest('[data-shieldx-form-modal-open]');

    if (formOpenButton) {
      event.preventDefault();
      openFormModal(formOpenButton);
      return;
    }

    var formCloseButton = event.target.closest('[data-shieldx-form-modal-close]');

    if (formCloseButton) {
      event.preventDefault();
      closeFormModal(formCloseButton.closest('[data-shieldx-form-modal]'));
      return;
    }

    var modalButton = event.target.closest('[data-shieldx-recovery-modal]');

    if (modalButton) {
      event.preventDefault();
      openRecoveryModal(modalButton);
      return;
    }

    var button = event.target.closest('[data-shieldx-copy]');

    if (!button) {
      return;
    }

    event.preventDefault();

    var text = button.getAttribute('data-shieldx-copy') || '';

    if (!text) {
      return;
    }

    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(text).then(function () {
        markCopied(button);
      }, function () {
        fallbackCopy(text);
        markCopied(button);
      });
      return;
    }

    fallbackCopy(text);
    markCopied(button);
  });
})();
