(function () {
  const config = window.RPCASessionBeacon || {};
  if (!config.ajaxUrl || !config.nonce) {
    return;
  }

  const startedAt = Date.now();
  let maxScroll = 0;
  let disclaimerVisibleSince = 0;
  let disclaimerVisibleMs = 0;
  const disclaimer =
    document.querySelector(".rpca-product-content-disclaimer") ||
    document.querySelector(".rpca-product-banner") ||
    document.querySelector(".rpca-payment-platform-note");

  function updateScroll() {
    const height = Math.max(
      document.documentElement.scrollHeight - window.innerHeight,
      1
    );
    maxScroll = Math.max(maxScroll, Math.round((window.scrollY / height) * 100));
  }

  if (disclaimer && "IntersectionObserver" in window) {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting && !disclaimerVisibleSince) {
          disclaimerVisibleSince = Date.now();
        }
        if (!entry.isIntersecting && disclaimerVisibleSince) {
          disclaimerVisibleMs += Date.now() - disclaimerVisibleSince;
          disclaimerVisibleSince = 0;
        }
      });
    });
    observer.observe(disclaimer);
  }

  function descriptorText() {
    const text = document.body ? document.body.innerText || "" : "";
    const match = text.match(/(billing|statement)\s+descriptor[^\n]{0,120}/i);
    return match ? match[0].slice(0, 160) : "";
  }

  function sendBeacon() {
    updateScroll();
    const visibleNow = disclaimerVisibleSince
      ? Date.now() - disclaimerVisibleSince
      : 0;
    const data = new URLSearchParams();
    data.set("action", "rpca_session_beacon");
    data.set("nonce", config.nonce);
    data.set("productId", String(config.productId || 0));
    data.set("landingUrl", window.location.href);
    data.set(
      "viewport",
      `${Math.max(0, Math.round(window.innerWidth || 0))}x${Math.max(
        0,
        Math.round(window.innerHeight || 0)
      )}`
    );
    data.set("scrollDepth", String(maxScroll));
    data.set("timeOnPageMs", String(Date.now() - startedAt));
    data.set("timeOnDisclaimerMs", String(disclaimerVisibleMs + visibleNow));
    data.set("billingDescriptor", descriptorText());
    data.set(
      "renderCaptureHash",
      disclaimer
        ? String(disclaimer.innerText || "").trim().slice(0, 500)
        : ""
    );

    if (navigator.sendBeacon) {
      navigator.sendBeacon(config.ajaxUrl, data);
      return;
    }

    fetch(config.ajaxUrl, {
      method: "POST",
      credentials: "same-origin",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: data.toString(),
    }).catch(() => {});
  }

  window.addEventListener("scroll", updateScroll, { passive: true });
  window.addEventListener("beforeunload", sendBeacon);
  window.setTimeout(sendBeacon, 4000);
})();
