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

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

  // Wait for DOM ready
  function ready(fn) {
    if (document.readyState !== 'loading') { fn(); }
    else document.addEventListener('DOMContentLoaded', fn);
  }

  ready(function () {
    // Only run on the plugin settings page (optional extra guard)
    var pageParam = new URLSearchParams(location.search).get('page');
    if (!pageParam || pageParam !== 'rss-newssync') return;

    // NEW: if the page already contains the server-rendered clear-cache form/button,
    // do not inject the topbar button to avoid duplicates.
    // We check common selectors: server form button class OR a hidden input action for newssync_clear_cache.
    if (document.querySelector('.rsp-clear-cache-btn') || document.querySelector('form input[name="action"][value="newssync_clear_cache"]')) {
      return;
    }

    // Find the language selector or header area to attach to.
    // Try a few common selectors used in admin UIs.
    var target = document.querySelector('#wpbody-content .wrap h1') // page title area
              || document.querySelector('.wrap .nav-tab-wrapper')    // tabs area
              || document.querySelector('.wrap');                    // fallback

    if (!target) return;

    // Create container to align to the right
    var container = document.createElement('div');
    container.style.cssText = 'display:flex; align-items:center; justify-content:flex-end; gap:10px; margin-bottom:10px;';

    // Create button
    var btn = document.createElement('button');
    btn.type = 'button';
    btn.id = 'rsp-top-clear-cache-btn';
    btn.className = 'button button-secondary';
    btn.textContent = RSPAdminData.i18n.clear_label || 'Clear Cache Now';
    btn.setAttribute('data-tab', RSPAdminData.current_tab || 'general');

    // Status node
    var status = document.createElement('span');
    status.id = 'rsp-top-clear-cache-status';
    status.style.marginLeft = '8px';

    container.appendChild(btn);
    container.appendChild(status);

    // Insert container after the target (so it's visually at top-right)
    // We insert before the target's next sibling to appear right under title/tabs
    if (target.parentNode) {
      target.parentNode.insertBefore(container, target.nextSibling);
    } else {
      document.body.insertBefore(container, document.body.firstChild);
    }

    // Click handler: confirm then POST to admin-post.php
    btn.addEventListener('click', function () {
      if (!confirm(RSPAdminData.i18n.confirm)) return;
      btn.disabled = true;
      status.textContent = RSPAdminData.i18n.clearing;

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

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