const getTargetPath = () =>
  window.arraySubsRetentionNav?.pagePath || "/analytics/arraysubs-retention";

const getCurrentPath = () => {
  try {
    const currentUrl = new URL(window.location.href);
    return currentUrl.searchParams.get("path") || "";
  } catch (error) {
    return "";
  }
};

const getLinkPath = (link) => {
  if (!(link instanceof HTMLAnchorElement)) {
    return "";
  }

  try {
    const url = new URL(link.href, window.location.origin);
    return url.searchParams.get("path") || "";
  } catch (error) {
    return "";
  }
};

const isAnalyticsPath = (path) =>
  typeof path === "string" && path.indexOf("/analytics") === 0;

const matchesRetentionLink = (link) => {
  if (!(link instanceof HTMLAnchorElement)) {
    return false;
  }

  const href = link.getAttribute("href") || "";
  const targetPath = getTargetPath();
  const encodedPath = encodeURIComponent(targetPath);

  return (
    href.includes(`path=${encodedPath}`) ||
    href.includes(`path=${targetPath}`) ||
    href.includes(targetPath)
  );
};

const shouldForceReload = (link) => {
  const currentPath = getCurrentPath();
  const nextPath = getLinkPath(link);
  const targetPath = getTargetPath();

  if (!nextPath || !isAnalyticsPath(nextPath)) {
    return false;
  }

  if (matchesRetentionLink(link)) {
    return true;
  }

  return currentPath === targetPath && nextPath !== targetPath;
};

const shouldHandleEvent = (event) => {
  if (event.defaultPrevented) {
    return false;
  }

  if (event.button !== 0) {
    return false;
  }

  return !(event.metaKey || event.ctrlKey || event.shiftKey || event.altKey);
};

const handleRetentionNavigation = (event) => {
  const link = event.target?.closest?.("a[href]");

  if (!shouldHandleEvent(event) || !shouldForceReload(link)) {
    return;
  }

  const nextUrl = link.href || link.getAttribute("href");

  if (!nextUrl) {
    return;
  }

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

  if (typeof event.stopImmediatePropagation === "function") {
    event.stopImmediatePropagation();
  }

  window.location.assign(nextUrl);
};

document.addEventListener("click", handleRetentionNavigation, true);
