/**
 * assets/js/loader.js
 * Global button loading states, form submission overlay, and toast notifications.
 * Include on every admin/checker page via _layout.php.
 */

(function () {
  'use strict';

  // ── Page loader overlay ───────────────────────────────────────
  function getPageLoader() {
    let el = document.getElementById('page-loader');
    if (!el) {
      el = document.createElement('div');
      el.id = 'page-loader';
      el.innerHTML = '<div class="pl-ring"></div><div class="pl-text" id="pl-text">Processing…</div>';
      document.body.appendChild(el);
    }
    return el;
  }

  function showPageLoader(text) {
    const el = getPageLoader();
    const txt = el.querySelector('#pl-text');
    if (txt) txt.textContent = text || 'Processing…';
    el.classList.add('active');
  }

  function hidePageLoader() {
    const el = document.getElementById('page-loader');
    if (el) el.classList.remove('active');
  }

  // Expose globally
  window.showPageLoader = showPageLoader;
  window.hidePageLoader = hidePageLoader;

  // ── Toast notifications ───────────────────────────────────────
  function getToastContainer() {
    let el = document.getElementById('toast-container');
    if (!el) {
      el = document.createElement('div');
      el.id = 'toast-container';
      document.body.appendChild(el);
    }
    return el;
  }

  window.showToast = function(message, type, duration) {
    type     = type     || 'info';    // 'success' | 'error' | 'info'
    duration = duration || 3500;

    const container = getToastContainer();
    const toast     = document.createElement('div');
    toast.className = 'toast toast-' + type;
    toast.innerHTML = '<div class="toast-dot"></div><span>' + escHtml(message) + '</span>';
    container.appendChild(toast);

    requestAnimationFrame(() => {
      requestAnimationFrame(() => toast.classList.add('show'));
    });

    setTimeout(() => {
      toast.classList.remove('show');
      setTimeout(() => toast.remove(), 350);
    }, duration);
  };

  function escHtml(s) {
    return String(s || '').replace(/[&<>"']/g, c =>
      ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
  }

  // ── Button loading state ──────────────────────────────────────
  window.btnLoading = function(btn, text) {
    if (!btn) return;
    btn.dataset.origText = btn.innerHTML;
    btn.dataset.origWidth = btn.offsetWidth + 'px';
    btn.style.minWidth = btn.dataset.origWidth;
    if (text) btn.setAttribute('data-loading-text', text);
    btn.classList.add('is-loading');
    btn.disabled = true;
  };

  window.btnReset = function(btn) {
    if (!btn) return;
    btn.classList.remove('is-loading');
    btn.disabled = false;
    if (btn.dataset.origText) btn.innerHTML = btn.dataset.origText;
    btn.style.minWidth = '';
  };

  // ── Auto-attach to all regular form submits ───────────────────
  // Shows page loader on any <form> that doesn't have data-no-loader
  // and disables the submit button to prevent double-submit.
  document.addEventListener('submit', function(e) {
    const form = e.target;
    if (form.dataset.noLoader !== undefined) return;
    if (form.dataset.ajax    !== undefined) return; // AJAX forms handle their own state

    const submitBtn = form.querySelector('[type="submit"]:not([data-no-loader])');
    const loaderText = (submitBtn && submitBtn.dataset.loaderText)
      ? submitBtn.dataset.loaderText
      : 'Processing…';

    showPageLoader(loaderText);
    if (submitBtn) btnLoading(submitBtn);
  }, true);

  // ── Auto-attach to all <a> buttons that trigger navigation ────
  // Adds spinner to links with class .btn that navigate away
  document.addEventListener('click', function(e) {
    const link = e.target.closest('a.btn');
    if (!link) return;
    if (link.dataset.noLoader !== undefined) return;
    if (link.target === '_blank') return;   // external links — don't show loader
    if (link.href && !link.href.startsWith('#')) {
      btnLoading(link);
    }
  });

  // ── Hide loader when browser navigates back (bfcache) ─────────
  window.addEventListener('pageshow', function(e) {
    if (e.persisted) {
      hidePageLoader();
      document.querySelectorAll('.btn.is-loading').forEach(btn => btnReset(btn));
    }
  });

  // Also hide if page finishes loading (in case of fast navigation)
  window.addEventListener('load', hidePageLoader);

})();
