window.dataLayer = window.dataLayer || [];
function gtag() {
  dataLayer.push(arguments);
}
gtag("js", new Date());

document.addEventListener("DOMContentLoaded", function (event) {
  const searchParamsStorage = window.localStorage.getItem("queryParams");
  if (!searchParamsStorage) console.log("ANALYTICPRO: No utm detected");

  const searchParams = new URLSearchParams(searchParamsStorage);
  const utmMedium =
    searchParams.get("utm_medium") ?? searchParams.get("UTM_MEDIUM");
  const utmSource =
    searchParams.get("utm_source") ?? searchParams.get("UTM_SOURCE");

  let purchase = {
    transaction_id: username,
    currency: "USD",
    value: 10,
    items: [
      {
        item_id: username,
        item_name: username,
      },
    ],
  };

  if (utmMedium === "ADS") {
    switch (utmSource) {
      case "OP": {
        const gaid = searchParams.get("gaid");

        if (gaid) {
          purchase = {
            ...purchase,
            coupon: gaid,
          };
        }

        break;
      }
      case "PLR":
      case "ROI":
      case "HA": {
        const clickId = searchParams.get("clickid");

        if (clickId) {
          purchase = {
            ...purchase,
            coupon: clickId,
          };
        }

        break;
      }
      default: {
        const adsToken =
          searchParams.get("clickid") || searchParams.get("gaid");

        if (adsToken) {
          purchase = {
            ...purchase,
            coupon: adsToken,
          };
        }
      }
    }
  }

  if (
    window.location.href.indexOf("register-done") != -1 &&
    username !== null
  ) {
    gtag("set", {
      user_id: username,
    });
    gtag("event", "purchase", purchase);
    window.localStorage.removeItem("username");
  }

  waitForElementRetry("#form-state", { timeout: 99999, maxRetries: 3, root: document.getElementById('_rht_toaster') }).then((el) => {
    if (el.dataset.value === 'register-done' && username !== null) {
      gtag("set", {
        user_id: username,
      });
      gtag("event", "purchase", purchase);
      window.localStorage.removeItem("username");
    }
  }).catch((err) => {
    console.log(err);
  })
});
