(function () {
  if (typeof newssyncAdminData === 'undefined' && typeof RSPAdminData === 'undefined') return;

  var RSPAdmin = window.newssyncAdminData || window.RSPAdminData || {};

  var btn = document.getElementById('rsp-clear-cache-btn');
  var status = document.getElementById('rsp-clear-cache-status');

  if (!btn) return;

  btn.addEventListener('click', function () {
    if (!confirm(RSPAdmin.i18n.confirm)) return;

    btn.disabled = true;
    status.textContent = RSPAdmin.i18n.clearing;

    var body = new URLSearchParams();
    body.append('action', 'newssync_clear_cache');
    body.append('newssync_clear_cache_nonce', RSPAdmin.nonce);
    body.append('newssync_current_tab', btn.getAttribute('data-tab') || RSPAdmin.current_tab);

    fetch(RSPAdmin.admin_post_url, {
      method: 'POST',
      credentials: 'same-origin',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
      body: body.toString()
    }).then(function () {
      // Redirect back to the settings page + current tab
      var redirectUrl = RSPAdmin.admin_page_url + '?page=rss-newssync&tab=' + encodeURIComponent(btn.getAttribute('data-tab') || RSPAdmin.current_tab);
      window.location.href = redirectUrl;
    }).catch(function (err) {
      console.error(err);
      status.textContent = RSPAdmin.i18n.error;
      btn.disabled = false;
    });
  }, false);
})();