(function () {
  if (typeof WPSN_MEDIA === 'undefined') return;

  const ajaxUrl = WPSN_MEDIA.ajaxUrl;
  const nonce = WPSN_MEDIA.nonce;
  const strings = WPSN_MEDIA.strings || {};

  function post(action, data) {
    const form = new FormData();
    form.append('action', action);
    form.append('nonce', nonce);
    Object.keys(data || {}).forEach((k) => {
      form.append(k, data[k]);
    });

    return fetch(ajaxUrl, {
      method: 'POST',
      credentials: 'same-origin',
      body: form,
    }).then((r) => r.json());
  }

  // ----------------
  // Generate drafts
  // ----------------

  let genSession = null;
  let genRunning = false;
  let genTotal = 0;

  const genBtn = document.getElementById('wpsn-media-ajax-generate-now');
  const genCancelBtn = document.getElementById('wpsn-media-ajax-generate-cancel');
  const genSpinner = document.getElementById('wpsn-media-ajax-generate-spinner');
  const genProgressWrap = document.getElementById('wpsn-media-ajax-generate-progress');
  const genBar = document.getElementById('wpsn-media-ajax-generate-bar');
  const genStatus = document.getElementById('wpsn-media-ajax-generate-status');

  function setGenStatus(text) {
    if (genStatus) genStatus.textContent = text || '';
  }

  function setGenProgress(pct) {
    if (genBar) genBar.style.width = String(Math.max(0, Math.min(100, pct))) + '%';
  }

  function showGenProgress(show) {
    if (genProgressWrap) genProgressWrap.style.display = show ? 'block' : 'none';
  }

  function setGenBusy(busy) {
    if (genSpinner) genSpinner.style.visibility = busy ? 'visible' : 'hidden';
    if (genBtn) genBtn.disabled = busy;
    genRunning = busy;
  }

  function genLoop(delaySeconds) {
    if (!genRunning || !genSession) return;

    const delayMs = Math.max(0, (delaySeconds || 0) * 1000);

    window.setTimeout(() => {
      post('wpsn_media_generate_step', {
        session: genSession,
        chunk: 5,
      })
        .then((res) => {
          if (!res || !res.success) {
            const msg = (res && res.data && res.data.message) ? res.data.message : (res && res.message ? res.message : '');
            setGenStatus((strings.error || 'Error:') + ' ' + msg);
            setGenBusy(false);
            return;
          }

          const d = res.data || {};
          const processed = d.processed || 0;
          const total = d.total || genTotal || 0;
          const pct = total ? Math.round((processed / total) * 100) : 100;

          setGenProgress(pct);

          let line = (strings.processing || 'Processing…') + ' ' + processed + ' / ' + total;
          if (typeof d.generated !== 'undefined') line += ' · generated: ' + d.generated;
          if (typeof d.skipped !== 'undefined') line += ' · skipped: ' + d.skipped;
          if (typeof d.failed !== 'undefined') line += ' · failed: ' + d.failed;

          if (d.rate_limited) {
            const wait = d.retry_after || 0;
            const reason = d.rate_limit_message ? (' (' + d.rate_limit_message + ')') : '';
            line += ' · ' + (strings.rate_limited || 'Rate limited. Waiting…') + ' ' + wait + 's' + reason;
          }

          setGenStatus(line);

          if (d.done) {
            setGenBusy(false);
            setGenStatus((strings.done || 'Done.') + ' ' + processed + ' / ' + total);
            // Refresh page so the drafts table updates.
            window.setTimeout(() => window.location.reload(), 600);
            return;
          }

          if (d.rate_limited) {
            genLoop(d.retry_after || 5);
          } else {
            genLoop(0);
          }
        })
        .catch((e) => {
          setGenStatus((strings.error || 'Error:') + ' ' + (e && e.message ? e.message : String(e)));
          setGenBusy(false);
        });
    }, delayMs);
  }

  if (genBtn) {
    genBtn.addEventListener('click', function (e) {
      e.preventDefault();
      if (genRunning) return;

      showGenProgress(true);
      setGenProgress(0);
      setGenStatus(strings.starting || 'Starting…');
      setGenBusy(true);

      const source = document.getElementById('wpsn-media-generate-source')?.value || 'local';
      const onlyIfEmpty = document.getElementById('wpsn-media-only-if-empty')?.checked ? '1' : '';
      const overwrite = document.getElementById('wpsn-media-overwrite-suggestions')?.checked ? '1' : '';
      const missingAltOnly = document.getElementById('wpsn-media-missing-alt-only')?.checked ? '1' : '';

      const useVision = document.getElementById('wpsn-media-openai-vision')?.checked ? '1' : '';
      const visionDetail = document.getElementById('wpsn-media-vision-detail')?.value || 'low';

      const backoff = document.getElementById('wpsn-media-backoff-seconds')?.value || '10';
      const limit = document.getElementById('wpsn-media-generate-limit')?.value || '500';

      post('wpsn_media_generate_start', {
        source: source,
        only_if_empty: onlyIfEmpty,
        overwrite_suggestions: overwrite,
        missing_alt_only: missingAltOnly,
        use_vision: useVision,
        vision_detail: visionDetail,
        backoff_seconds: backoff,
        limit: limit,
      })
        .then((res) => {
          if (!res || !res.success) {
            const msg = (res && res.data && res.data.message) ? res.data.message : (res && res.message ? res.message : '');
            setGenStatus((strings.error || 'Error:') + ' ' + msg);
            setGenBusy(false);
            return;
          }

          genSession = res.data.session;
          genTotal = res.data.total || 0;

          if (!genTotal) {
            setGenStatus((strings.done || 'Done.') + ' ' + '0');
            setGenBusy(false);
            return;
          }

          genLoop(0);
        })
        .catch((e) => {
          setGenStatus((strings.error || 'Error:') + ' ' + (e && e.message ? e.message : String(e)));
          setGenBusy(false);
        });
    });
  }

  if (genCancelBtn) {
    genCancelBtn.addEventListener('click', function (e) {
      e.preventDefault();
      if (!genSession) {
        setGenStatus(strings.cancelled || 'Cancelled.');
        setGenBusy(false);
        return;
      }

      post('wpsn_media_generate_cancel', { session: genSession })
        .then(() => {
          setGenStatus(strings.cancelled || 'Cancelled.');
          setGenBusy(false);
          genSession = null;
        })
        .catch(() => {
          setGenStatus(strings.cancelled || 'Cancelled.');
          setGenBusy(false);
          genSession = null;
        });
    });
  }

  // -------------
  // Apply all
  // -------------

  let applySession = null;
  let applyRunning = false;
  let applyTotal = 0;

  const applyBtn = document.getElementById('wpsn-media-ajax-apply-all');
  const applyCancelBtn = document.getElementById('wpsn-media-ajax-cancel');
  const applySpinner = document.getElementById('wpsn-media-ajax-spinner');
  const applyProgressWrap = document.getElementById('wpsn-media-ajax-progress');
  const applyBar = document.getElementById('wpsn-media-ajax-bar');
  const applyStatus = document.getElementById('wpsn-media-ajax-status');

  function setApplyStatus(text) {
    if (applyStatus) applyStatus.textContent = text || '';
  }

  function setApplyProgress(pct) {
    if (applyBar) applyBar.style.width = String(Math.max(0, Math.min(100, pct))) + '%';
  }

  function showApplyProgress(show) {
    if (applyProgressWrap) applyProgressWrap.style.display = show ? 'block' : 'none';
  }

  function setApplyBusy(busy) {
    if (applySpinner) applySpinner.style.visibility = busy ? 'visible' : 'hidden';
    if (applyBtn) applyBtn.disabled = busy;
    applyRunning = busy;
  }

  function getApplyFilters() {
    const s = document.getElementById('wpsn-media-suggestions-search')?.value || '';
    const source = document.getElementById('wpsn-media-filter-source')?.value || '';
    return { s: s, source: source };
  }

  function applyLoop(delaySeconds) {
    if (!applyRunning || !applySession) return;

    const delayMs = Math.max(0, (delaySeconds || 0) * 1000);

    window.setTimeout(() => {
      post('wpsn_media_apply_all_step', {
        session: applySession,
        chunk: 10,
      })
        .then((res) => {
          if (!res || !res.success) {
            const msg = (res && res.data && res.data.message) ? res.data.message : (res && res.message ? res.message : '');
            setApplyStatus((strings.error || 'Error:') + ' ' + msg);
            setApplyBusy(false);
            return;
          }

          const d = res.data || {};
          const processed = d.processed || 0;
          const total = d.total || applyTotal || 0;
          const pct = total ? Math.round((processed / total) * 100) : 100;

          setApplyProgress(pct);

          let line = (strings.processing || 'Processing…') + ' ' + processed + ' / ' + total;
          if (typeof d.applied !== 'undefined') line += ' · applied: ' + d.applied;

          setApplyStatus(line);

          if (d.done) {
            setApplyBusy(false);
            setApplyStatus((strings.done || 'Done.') + ' ' + processed + ' / ' + total);
            window.setTimeout(() => window.location.reload(), 600);
            return;
          }

          applyLoop(0);
        })
        .catch((e) => {
          setApplyStatus((strings.error || 'Error:') + ' ' + (e && e.message ? e.message : String(e)));
          setApplyBusy(false);
        });
    }, delayMs);
  }

  if (applyBtn) {
    applyBtn.addEventListener('click', function (e) {
      e.preventDefault();
      if (applyRunning) return;

      showApplyProgress(true);
      setApplyProgress(0);
      setApplyStatus(strings.starting || 'Starting…');
      setApplyBusy(true);

      const limit = document.getElementById('wpsn-media-apply-limit')?.value || '500';
      const applyOnlyChanged = document.getElementById('wpsn-media-apply-only-changed')?.checked ? '1' : '';
      const filters = getApplyFilters();

      post('wpsn_media_apply_all_start', {
        limit: limit,
        apply_only_changed: applyOnlyChanged,
        s: filters.s,
        source: filters.source,
      })
        .then((res) => {
          if (!res || !res.success) {
            const msg = (res && res.data && res.data.message) ? res.data.message : (res && res.message ? res.message : '');
            setApplyStatus((strings.error || 'Error:') + ' ' + msg);
            setApplyBusy(false);
            return;
          }

          applySession = res.data.session;
          applyTotal = res.data.total || 0;

          if (!applyTotal) {
            setApplyStatus((strings.done || 'Done.') + ' 0');
            setApplyBusy(false);
            return;
          }

          applyLoop(0);
        })
        .catch((e) => {
          setApplyStatus((strings.error || 'Error:') + ' ' + (e && e.message ? e.message : String(e)));
          setApplyBusy(false);
        });
    });
  }

  if (applyCancelBtn) {
    applyCancelBtn.addEventListener('click', function (e) {
      e.preventDefault();
      if (!applySession) {
        setApplyStatus(strings.cancelled || 'Cancelled.');
        setApplyBusy(false);
        return;
      }

      post('wpsn_media_apply_all_cancel', { session: applySession })
        .then(() => {
          setApplyStatus(strings.cancelled || 'Cancelled.');
          setApplyBusy(false);
          applySession = null;
        })
        .catch(() => {
          setApplyStatus(strings.cancelled || 'Cancelled.');
          setApplyBusy(false);
          applySession = null;
        });
    });
  }

  // -------------
  // Filename: Generate
  // -------------

  let fnGenSession = null;
  let fnGenRunning = false;
  let fnGenTotal = 0;

  const fnGenBtn = document.getElementById('wpsn-media-fn-ajax-generate-now');
  const fnGenCancelBtn = document.getElementById('wpsn-media-fn-ajax-generate-cancel');
  const fnGenSpinner = document.getElementById('wpsn-media-fn-ajax-generate-spinner');
  const fnGenProgressWrap = document.getElementById('wpsn-media-fn-ajax-generate-progress');
  const fnGenBar = document.getElementById('wpsn-media-fn-ajax-generate-bar');
  const fnGenStatus = document.getElementById('wpsn-media-fn-ajax-generate-status');

  function setFnGenStatus(text) {
    if (fnGenStatus) fnGenStatus.textContent = text || '';
  }

  function setFnGenProgress(pct) {
    if (fnGenBar) fnGenBar.style.width = String(Math.max(0, Math.min(100, pct))) + '%';
  }

  function showFnGenProgress(show) {
    if (fnGenProgressWrap) fnGenProgressWrap.style.display = show ? 'block' : 'none';
  }

  function setFnGenBusy(busy) {
    if (fnGenSpinner) fnGenSpinner.style.visibility = busy ? 'visible' : 'hidden';
    if (fnGenBtn) fnGenBtn.disabled = busy;
    fnGenRunning = busy;
  }

  function getFnGenerateFilters() {
    return {
      limit: document.getElementById('wpsn-media-fn-generate-limit')?.value || '200',
      overwrite_suggestions: document.getElementById('wpsn-media-fn-overwrite-suggestions')?.checked ? '1' : '',
      only_if_dirty: document.getElementById('wpsn-media-fn-only-if-dirty')?.checked ? '1' : '',
      max_base_len: document.getElementById('wpsn-media-fn-max-base-len')?.value || '80',
    };
  }

  function fnGenLoop() {
    if (!fnGenRunning || !fnGenSession) return;

    post('wpsn_media_filename_generate_step', {
      session: fnGenSession,
      chunk: 10,
    })
      .then((res) => {
        if (!res || !res.success) {
          const msg = (res && res.data && res.data.message) ? res.data.message : (res && res.message ? res.message : '');
          setFnGenStatus((strings.error || 'Error:') + ' ' + msg);
          setFnGenBusy(false);
          return;
        }

        const d = res.data || {};
        const processed = d.processed || 0;
        const total = d.total || fnGenTotal || 0;
        const pct = total ? Math.round((processed / total) * 100) : 100;

        setFnGenProgress(pct);

        let line = (strings.processing || 'Processing…') + ' ' + processed + ' / ' + total;
        if (typeof d.generated !== 'undefined') line += ' · generated: ' + d.generated;
        if (typeof d.skipped !== 'undefined') line += ' · skipped: ' + d.skipped;
        if (typeof d.failed !== 'undefined' && d.failed) line += ' · failed: ' + d.failed;
        setFnGenStatus(line);

        if (d.done) {
          setFnGenStatus((strings.done || 'Done.') + ' ' + (d.generated || 0));
          setFnGenBusy(false);
          fnGenSession = null;
          return;
        }

        fnGenLoop();
      })
      .catch((e) => {
        setFnGenStatus((strings.error || 'Error:') + ' ' + (e && e.message ? e.message : String(e)));
        setFnGenBusy(false);
      });
  }

  if (fnGenBtn) {
    fnGenBtn.addEventListener('click', function (e) {
      e.preventDefault();
      if (fnGenRunning) return;

      showFnGenProgress(true);
      setFnGenProgress(0);
      setFnGenStatus(strings.starting || 'Starting…');
      setFnGenBusy(true);

      const filters = getFnGenerateFilters();

      post('wpsn_media_filename_generate_start', filters)
        .then((res) => {
          if (!res || !res.success) {
            const msg = (res && res.data && res.data.message) ? res.data.message : (res && res.message ? res.message : '');
            setFnGenStatus((strings.error || 'Error:') + ' ' + msg);
            setFnGenBusy(false);
            return;
          }

          fnGenSession = res.data.session;
          fnGenTotal = res.data.total || 0;

          if (!fnGenTotal) {
            setFnGenStatus((strings.done || 'Done.') + ' 0');
            setFnGenBusy(false);
            return;
          }

          fnGenLoop();
        })
        .catch((e) => {
          setFnGenStatus((strings.error || 'Error:') + ' ' + (e && e.message ? e.message : String(e)));
          setFnGenBusy(false);
        });
    });
  }

  if (fnGenCancelBtn) {
    fnGenCancelBtn.addEventListener('click', function (e) {
      e.preventDefault();
      if (!fnGenSession) {
        setFnGenStatus(strings.cancelled || 'Cancelled.');
        setFnGenBusy(false);
        return;
      }

      post('wpsn_media_filename_generate_cancel', { session: fnGenSession })
        .then(() => {
          setFnGenStatus(strings.cancelled || 'Cancelled.');
          setFnGenBusy(false);
          fnGenSession = null;
        })
        .catch(() => {
          setFnGenStatus(strings.cancelled || 'Cancelled.');
          setFnGenBusy(false);
          fnGenSession = null;
        });
    });
  }

  // -------------
  // Filename: Apply all
  // -------------

  let fnApplySession = null;
  let fnApplyRunning = false;
  let fnApplyTotal = 0;

  const fnApplyBtn = document.getElementById('wpsn-media-fn-ajax-apply-all');
  const fnApplyCancelBtn = document.getElementById('wpsn-media-fn-ajax-cancel');
  const fnApplySpinner = document.getElementById('wpsn-media-fn-ajax-spinner');
  const fnApplyProgressWrap = document.getElementById('wpsn-media-fn-ajax-progress');
  const fnApplyBar = document.getElementById('wpsn-media-fn-ajax-bar');
  const fnApplyStatus = document.getElementById('wpsn-media-fn-ajax-status');

  function setFnApplyStatus(text) {
    if (fnApplyStatus) fnApplyStatus.textContent = text || '';
  }

  function setFnApplyProgress(pct) {
    if (fnApplyBar) fnApplyBar.style.width = String(Math.max(0, Math.min(100, pct))) + '%';
  }

  function showFnApplyProgress(show) {
    if (fnApplyProgressWrap) fnApplyProgressWrap.style.display = show ? 'block' : 'none';
  }

  function setFnApplyBusy(busy) {
    if (fnApplySpinner) fnApplySpinner.style.visibility = busy ? 'visible' : 'hidden';
    if (fnApplyBtn) fnApplyBtn.disabled = busy;
    fnApplyRunning = busy;
  }

  function getFnApplyFilters() {
    const s = document.getElementById('wpsn-media-fn-suggestions-search')?.value || '';
    const source = document.getElementById('wpsn-media-fn-filter-source')?.value || '';
    return { s: s, source: source };
  }

  function getFnApplyOptions() {
    const replace = document.getElementById('wpsn-media-fn-replace-in-content')?.checked ? '1' : '';
    const limit = document.getElementById('wpsn-media-fn-apply-limit')?.value || '200';
    const pts = Array.from(document.querySelectorAll('input.wpsn-media-fn-replace-pt:checked')).map((el) => el.value).join(',');
    return { replace_in_content: replace, replace_post_types: pts, limit: limit };
  }

  function fnApplyLoop() {
    if (!fnApplyRunning || !fnApplySession) return;

      post('wpsn_media_filename_apply_all_step', {
      session: fnApplySession,
      chunk: 3,
    })
      .then((res) => {
        if (!res || !res.success) {
          const msg = (res && res.data && res.data.message) ? res.data.message : (res && res.message ? res.message : '');
          setFnApplyStatus((strings.error || 'Error:') + ' ' + msg);
          setFnApplyBusy(false);
          return;
        }

        const d = res.data || {};
        const processed = d.processed || 0;
        const total = d.total || fnApplyTotal || 0;
        const pct = total ? Math.round((processed / total) * 100) : 100;

        setFnApplyProgress(pct);

        let line = (strings.processing || 'Processing…') + ' ' + processed + ' / ' + total;
        if (typeof d.applied !== 'undefined') line += ' · applied: ' + d.applied;
        if (typeof d.failed !== 'undefined' && d.failed) line += ' · failed: ' + d.failed;
        setFnApplyStatus(line);

        if (d.done) {
          setFnApplyStatus((strings.done || 'Done.') + ' ' + (d.applied || 0));
          setFnApplyBusy(false);
          fnApplySession = null;
          return;
        }

        fnApplyLoop();
      })
      .catch((e) => {
        setFnApplyStatus((strings.error || 'Error:') + ' ' + (e && e.message ? e.message : String(e)));
        setFnApplyBusy(false);
      });
  }

  if (fnApplyBtn) {
    fnApplyBtn.addEventListener('click', function (e) {
      e.preventDefault();
      if (fnApplyRunning) return;

      showFnApplyProgress(true);
      setFnApplyProgress(0);
      setFnApplyStatus(strings.starting || 'Starting…');
      setFnApplyBusy(true);

      const filters = getFnApplyFilters();
      const opts = getFnApplyOptions();

      post('wpsn_media_filename_apply_all_start', {
        limit: opts.limit,
        s: filters.s,
        source: filters.source,
        replace_in_content: opts.replace_in_content,
        replace_post_types: opts.replace_post_types,
      })
        .then((res) => {
          if (!res || !res.success) {
            const msg = (res && res.data && res.data.message) ? res.data.message : (res && res.message ? res.message : '');
            setFnApplyStatus((strings.error || 'Error:') + ' ' + msg);
            setFnApplyBusy(false);
            return;
          }

          fnApplySession = res.data.session;
          fnApplyTotal = res.data.total || 0;

          if (!fnApplyTotal) {
            setFnApplyStatus((strings.done || 'Done.') + ' 0');
            setFnApplyBusy(false);
            return;
          }

          fnApplyLoop();
        })
        .catch((e) => {
          setFnApplyStatus((strings.error || 'Error:') + ' ' + (e && e.message ? e.message : String(e)));
          setFnApplyBusy(false);
        });
    });
  }

  if (fnApplyCancelBtn) {
    fnApplyCancelBtn.addEventListener('click', function (e) {
      e.preventDefault();
      if (!fnApplySession) {
        setFnApplyStatus(strings.cancelled || 'Cancelled.');
        setFnApplyBusy(false);
        return;
      }

      post('wpsn_media_filename_apply_all_cancel', { session: fnApplySession })
        .then(() => {
          setFnApplyStatus(strings.cancelled || 'Cancelled.');
          setFnApplyBusy(false);
          fnApplySession = null;
        })
        .catch(() => {
          setFnApplyStatus(strings.cancelled || 'Cancelled.');
          setFnApplyBusy(false);
          fnApplySession = null;
        });
    });
  }

  const fnReplaceToggle = document.getElementById('wpsn-media-fn-replace-in-content');
  if (fnReplaceToggle) {
    const toggle = () => {
      const enabled = fnReplaceToggle.checked;
      document.querySelectorAll('input.wpsn-media-fn-replace-pt').forEach((el) => {
        el.disabled = !enabled;
      });
    };
    fnReplaceToggle.addEventListener('change', toggle);
    toggle();
  }

  // -------------
  // Filename: Clear drafts
  // -------------

  let fnClearSession = null;
  let fnClearRunning = false;
  let fnClearTotal = 0;

  const fnClearBtn = document.getElementById('wpsn-media-fn-ajax-clear-drafts');
  const fnClearCancelBtn = document.getElementById('wpsn-media-fn-ajax-clear-cancel');
  const fnClearSpinner = document.getElementById('wpsn-media-fn-ajax-clear-spinner');
  const fnClearProgressWrap = document.getElementById('wpsn-media-fn-ajax-clear-progress');
  const fnClearBar = document.getElementById('wpsn-media-fn-ajax-clear-bar');
  const fnClearStatus = document.getElementById('wpsn-media-fn-ajax-clear-status');

  function setFnClearStatus(text) {
    if (fnClearStatus) fnClearStatus.textContent = text || '';
  }

  function setFnClearProgress(pct) {
    if (fnClearBar) fnClearBar.style.width = String(Math.max(0, Math.min(100, pct))) + '%';
  }

  function showFnClearProgress(show) {
    if (fnClearProgressWrap) fnClearProgressWrap.style.display = show ? 'block' : 'none';
  }

  function setFnClearBusy(busy) {
    if (fnClearSpinner) fnClearSpinner.style.visibility = busy ? 'visible' : 'hidden';
    if (fnClearBtn) fnClearBtn.disabled = busy;
    fnClearRunning = busy;
  }

  function getFnClearFilters() {
    const s = document.getElementById('wpsn-media-fn-suggestions-search')?.value || '';
    const source = document.getElementById('wpsn-media-fn-filter-source')?.value || '';
    return { s: s, source: source };
  }

  function fnClearLoop() {
    if (!fnClearRunning || !fnClearSession) return;

    post('wpsn_media_filename_clear_drafts_step', {
      session: fnClearSession,
      chunk: 50,
    })
      .then((res) => {
        if (!res || !res.success) {
          const msg = (res && res.data && res.data.message) ? res.data.message : (res && res.message ? res.message : '');
          setFnClearStatus((strings.error || 'Error:') + ' ' + msg);
          setFnClearBusy(false);
          return;
        }

        const d = res.data || {};
        const processed = d.processed || 0;
        const total = d.total || fnClearTotal || 0;
        const pct = total ? Math.round((processed / total) * 100) : 100;

        setFnClearProgress(pct);

        let line = (strings.processing || 'Processing…') + ' ' + processed + ' / ' + total;
        if (typeof d.cleared !== 'undefined') line += ' · cleared: ' + d.cleared;
        setFnClearStatus(line);

        if (d.done) {
          setFnClearStatus((strings.done || 'Done.') + ' ' + (d.cleared || 0));
          setFnClearBusy(false);
          fnClearSession = null;
          window.setTimeout(() => window.location.reload(), 400);
          return;
        }

        fnClearLoop();
      })
      .catch((e) => {
        setFnClearStatus((strings.error || 'Error:') + ' ' + (e && e.message ? e.message : String(e)));
        setFnClearBusy(false);
      });
  }

  if (fnClearBtn) {
    fnClearBtn.addEventListener('click', function (e) {
      e.preventDefault();
      if (fnClearRunning) return;

      showFnClearProgress(true);
      setFnClearProgress(0);
      setFnClearStatus(strings.starting || 'Starting…');
      setFnClearBusy(true);

      const limit = document.getElementById('wpsn-media-fn-clear-limit')?.value || '500';
      const filters = getFnClearFilters();

      post('wpsn_media_filename_clear_drafts_start', {
        limit: limit,
        s: filters.s,
        source: filters.source,
      })
        .then((res) => {
          if (!res || !res.success) {
            const msg = (res && res.data && res.data.message) ? res.data.message : (res && res.message ? res.message : '');
            setFnClearStatus((strings.error || 'Error:') + ' ' + msg);
            setFnClearBusy(false);
            return;
          }

          fnClearSession = res.data.session;
          fnClearTotal = res.data.total || 0;

          if (!fnClearTotal) {
            setFnClearStatus((strings.done || 'Done.') + ' 0');
            setFnClearBusy(false);
            return;
          }

          fnClearLoop();
        })
        .catch((e) => {
          setFnClearStatus((strings.error || 'Error:') + ' ' + (e && e.message ? e.message : String(e)));
          setFnClearBusy(false);
        });
    });
  }

  if (fnClearCancelBtn) {
    fnClearCancelBtn.addEventListener('click', function (e) {
      e.preventDefault();
      if (!fnClearSession) {
        setFnClearStatus(strings.cancelled || 'Cancelled.');
        setFnClearBusy(false);
        return;
      }

      post('wpsn_media_filename_clear_drafts_cancel', { session: fnClearSession })
        .then(() => {
          setFnClearStatus(strings.cancelled || 'Cancelled.');
          setFnClearBusy(false);
          fnClearSession = null;
        })
        .catch(() => {
          setFnClearStatus(strings.cancelled || 'Cancelled.');
          setFnClearBusy(false);
          fnClearSession = null;
        });
    });
  }
})();
