(function () {
  'use strict';

  function smoothScrollToTarget(targetId) {
    if (!targetId) return;

    var target = document.getElementById(targetId);
    if (!target) return;

    var detailsParent = target.closest ? target.closest('details') : null;
    if (detailsParent && !detailsParent.open) {
      detailsParent.open = true;
    }

    var rect = target.getBoundingClientRect();
    var top = window.pageYOffset + rect.top - 24;

    window.scrollTo({
      top: Math.max(0, top),
      behavior: 'smooth'
    });

    target.classList.remove('custausu-scroll-target-flash');

    window.setTimeout(function () {
      target.classList.add('custausu-scroll-target-flash');
    }, 180);

    window.setTimeout(function () {
      target.classList.remove('custausu-scroll-target-flash');
    }, 2200);
  }

  function casGetExportFilename(disposition) {
    if (!disposition) {
      return '';
    }

    var utf8Match = disposition.match(/filename\*=UTF-8''([^;]+)/i);
    if (utf8Match && utf8Match[1]) {
      try {
        return decodeURIComponent(utf8Match[1].replace(/["']/g, ''));
      } catch (e) {
        return utf8Match[1].replace(/["']/g, '');
      }
    }

    var plainMatch = disposition.match(/filename="?([^"]+)"?/i);
    if (plainMatch && plainMatch[1]) {
      return plainMatch[1].replace(/["']/g, '');
    }

    return '';
  }

  function casSetExportNote(note, state, text) {
    if (!note) {
      return;
    }

    note.classList.remove('is-loading', 'is-done', 'is-error');
    note.classList.add('is-' + state);
    note.textContent = text;
  }

  document.addEventListener('click', function (event) {
    var btn = event.target && event.target.closest
      ? event.target.closest('.custausu-scrollto')
      : null;

    if (!btn) return;

    var targetId = btn.getAttribute('data-target') || '';
    if (!targetId) return;

    event.preventDefault();
    smoothScrollToTarget(targetId);
  });

  document.addEventListener('click', function (event) {
    var runBtn = event.target && event.target.closest
      ? event.target.closest('[data-custausu-health-run="1"], .custausu-health-run-btn, #custausu-health-run')
      : null;

    if (!runBtn) {
      return;
    }

    var card = runBtn.closest('#custausu-section-health-check');

    if (!card) {
      return;
    }

    event.preventDefault();
    event.stopPropagation();

    if (runBtn.disabled) {
      return;
    }

    var cfg = window.CUSTAUSU_ADMIN_TOP_PANEL || {};
    var ajaxUrl = cfg.ajax_url || window.ajaxurl || '';
    var nonce = cfg.nonce || '';

    if (!ajaxUrl || !nonce) {
      card.open = true;
      return;
    }

    var originalText = runBtn.textContent;
    var loadingText = cfg.running_label || 'Checking...';

    runBtn.disabled = true;
    runBtn.classList.add('is-disabled');
    runBtn.setAttribute('aria-busy', 'true');
    runBtn.textContent = loadingText;

    var fd = new FormData();
    fd.append('action', 'custausu_health_check');
    fd.append('nonce', nonce);

    fetch(ajaxUrl, {
      method: 'POST',
      credentials: 'same-origin',
      body: fd
    })
      .then(function (response) {
        return response.json();
      })
      .then(function (json) {
        if (!json || !json.success || !json.data || !json.data.html) {
          throw new Error('Invalid health check response');
        }

        var wrapper = document.createElement('div');
        wrapper.innerHTML = String(json.data.html);

        var fresh = wrapper.querySelector('#custausu-section-health-check');

        if (!fresh) {
          throw new Error('Health check markup missing');
        }

        card.replaceWith(fresh);
        fresh.open = true;

        window.setTimeout(function () {
          fresh.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
          });
        }, 60);
      })
      .catch(function () {
        alert(cfg.error_label || cfg.network_error_label || 'Health check failed');

        runBtn.disabled = false;
        runBtn.classList.remove('is-disabled');
        runBtn.removeAttribute('aria-busy');
        runBtn.textContent = originalText;
        card.open = true;
      });
  }, true);

  /*
   * Doctor support reports are admin-post.php downloads.
   *
   * Do not intercept them with fetch(): browser-native navigation/download is
   * more reliable for files because WordPress can stream headers, redirects,
   * nonces, and Content-Disposition directly.
   */
  document.addEventListener('click', function (event) {
    var link = event.target && event.target.closest
      ? event.target.closest('a[href*="action=custausu_export_support_report"]')
      : null;

    if (!link) {
      return;
    }

    // Let the browser follow the href and download the report natively.
    return;
  }, true);


})();