/* assets/leave-guard.js */
(function () {
  /* ── state ───────────────────────────────────────────── */
  let guardActive  = false;   // becomes true as soon as the form appears
  let suppressOnce = false;   // skip the prompt right after a successful submit
  let pendingNav   = null;    // only used for back button flow

  /* ── utility ─────────────────────────────────────────── */
  function formIsPresent () {
    return !!document.querySelector('.asana-dynamic-form');
  }

  function armIfFormPresent () {
    if (formIsPresent()) guardActive = true;
  }

function confirmLeave () {
  const ok = window.confirm(
    'Leave this form?\n\nYou have an in-progress request. ' +
    'If you leave now, your session will be cleared.'
  );
  if (ok) {
    // Clear browser sessionStorage
    try { sessionStorage.clear(); } catch {}

    // Also clear server-side triage_gpt_state for this browser
    try {
      const ajaxUrl =
        (window.triageAjax && triageAjax.ajax_url) ||
        (window.afb_ajax && afb_ajax.ajax_url);

      if (ajaxUrl) {
        const params = new URLSearchParams({
          action: 'triage_gpt_reset_state',
          nonce:  (window.triageAjax && triageAjax.nonce) ? triageAjax.nonce : ''
        });

        if (navigator.sendBeacon) {
          navigator.sendBeacon(ajaxUrl, params);
        } else {
          fetch(ajaxUrl, {
            method: 'POST',
            credentials: 'same-origin',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: params
          });
        }
      }
    } catch (_) {}
  }
  return ok;
}


  /* ── initial arm check ───────────────────────────────── */
  document.addEventListener('DOMContentLoaded', armIfFormPresent);

  /* ── watch the DOM so we arm as soon as the form is injected ── */
  const mo = new MutationObserver(() => {
    if (!guardActive && formIsPresent()) {
      guardActive = true;
      mo.disconnect();            // no further watching needed
    }
  });
  mo.observe(document.documentElement, { childList: true, subtree: true });

  /* ── don’t warn right after submit ───────────────────── */
  document.addEventListener(
    'submit',
    (e) => {
      if (e.target && e.target.classList.contains('asana-dynamic-form')) {
        suppressOnce = true;
      }
    },
    true
  );

  /* ── intercept all link clicks – capture phase ───────── */
  document.addEventListener(
    'click',
    (e) => {
      const a = e.target.closest && e.target.closest('a[href]');
      if (!a) return;

      const href = a.getAttribute('href') || '';
      if (!href || href.startsWith('#')) return;          // ignore anchors
      if (!guardActive || suppressOnce) return;           // prompt only when armed

      e.preventDefault();                                 // pause navigation
      if (confirmLeave()) window.location.href = href;    // proceed if confirmed
    },
    true
  );

  /* ── back / forward ──────────────────────────────────── */
  try { history.pushState({ afbGuard: 1 }, ''); } catch {}
  window.addEventListener('popstate', () => {
    if (!guardActive || suppressOnce) return;
    if (confirmLeave()) {
      suppressOnce = true;  // avoid loop with beforeunload
      history.back();
    } else {
      // we already cancelled popstate by pushing state above
      // so no further action needed
    }
  });

  /* ── refresh / close / typed-URL ─────────────────────── */
  window.addEventListener('beforeunload', (e) => {
    if (guardActive && !suppressOnce) {
      e.preventDefault();
      e.returnValue = '';   // triggers native dialog
      return '';
    }
  });

  /* ── ensure session clears on real unloads ───────────── */
  window.addEventListener('pagehide', () => {
    if (guardActive && !suppressOnce) {
      try { sessionStorage.clear(); } catch {}
    }
  });
  
  /* ------------ first interaction arms the guard ------------ */
document.addEventListener(
  'focusin',
  (e) => {
    if (!guardActive && e.target.closest('.asana-dynamic-form')) {
      guardActive = true;
    }
  },
  true
);

document.addEventListener(
  'click',
  (e) => {
    if (!guardActive && e.target.closest('.asana-dynamic-form')) {
      guardActive = true;
    }
  },
  true
);
  
})();


