(function (window, document) {
  "use strict";

  const config = window.ArraySubsCheckoutSessionGuard || {};
  const refreshParam = config.refreshParam || "arraysubs_checkout_session_refresh";
  const storageKey = "arraysubs.checkoutSessionRefresh";

  const hasLoginPrompt = () => {
    const text = document.body?.innerText || "";
    return /\bLog in\b/.test(text) && text.includes("Contact information");
  };

  const hasCheckoutLoader = () =>
    document.querySelector(
      '.wc-block-components-spinner, .components-spinner, [aria-busy="true"]',
    );

  const hasLoadedCheckout = () =>
    document.body?.innerText?.includes("Place Order") ||
    document.body?.innerText?.includes("Payment options");

  const pageCurrentUserId = () => {
    const settingsUserId = Number(window.wcSettings?.currentUserId || 0);

    if (settingsUserId > 0) {
      return settingsUserId;
    }

    return document.body?.classList?.contains("logged-in")
      ? Number(config.currentUserId || 0)
      : 0;
  };

  const shouldReload = (state) => {
    if (!state?.loggedIn) {
      return false;
    }

    if (pageCurrentUserId() <= 0 || hasLoginPrompt()) {
      return true;
    }

    return Boolean(hasCheckoutLoader() && !hasLoadedCheckout());
  };

  const refreshCheckout = () => {
    const currentUrl = new URL(window.location.href);
    const currentRefresh = currentUrl.searchParams.get(refreshParam);
    const alreadyRefreshed =
      currentRefresh === "1" || window.sessionStorage?.getItem(storageKey) === "1";

    if (alreadyRefreshed) {
      return;
    }

    try {
      window.sessionStorage?.setItem(storageKey, "1");
    } catch (error) {
      // sessionStorage can be unavailable in hardened browsers.
    }

    currentUrl.searchParams.set(refreshParam, "1");
    currentUrl.searchParams.set("_", String(Date.now()));
    window.location.replace(currentUrl.toString());
  };

  const checkSessionState = async () => {
    if (!config.ajaxUrl) {
      return;
    }

    const response = await window.fetch(config.ajaxUrl, {
      method: "POST",
      credentials: "same-origin",
      cache: "no-store",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
      },
      body: new URLSearchParams({
        action: "arraysubs_checkout_session_state",
        _: String(Date.now()),
      }),
    });

    if (!response.ok) {
      return;
    }

    const payload = await response.json();
    const state = payload?.success ? payload.data : payload;

    if (shouldReload(state)) {
      refreshCheckout();
    }
  };

  const start = () => {
    checkSessionState().catch(() => {});
    window.setTimeout(() => {
      checkSessionState().catch(() => {});
    }, 3000);
  };

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", start);
  } else {
    start();
  }
})(window, document);
