const scriptEl = document.querySelector('[data-script="pixel"]');

!(function(p,l,o,w,i,n,g){if(!p[i]){p.GlobalSnowplowNamespace=p.GlobalSnowplowNamespace||[];p.GlobalSnowplowNamespace.push(i);p[i]=function(){(p[i].q=p[i].q||[]).push(arguments)};p[i].q=p[i].q||[];n=l.createElement(o);g=l.getElementsByTagName(o)[0];n.async=1;n.src=w;g.parentNode.insertBefore(n,g)}})(window,document,"script","//res-odx.op-mobile.opera.com/sp.js","otag");
!(function (p, l, o, w, i, n, g) {
  if (!p[i]) {
    p.GlobalSnowplowNamespace = p.GlobalSnowplowNamespace || [];
    p.GlobalSnowplowNamespace.push(i);
    p[i] = function () {
      (p[i].q = p[i].q || []).push(arguments);
    };
    p[i].q = p[i].q || [];
    n = l.createElement(o);
    g = l.getElementsByTagName(o)[0];
    n.async = 1;
    n.src = w;
    g.parentNode.insertBefore(n, g);
  }
})(window, document, "script", "//res-odx.op-mobile.opera.com/sp.js", "otag2");
var pixelId = "adv9216414380992";

var pixelid2;
if (scriptEl) {
  pixelId = scriptEl.dataset.id ?? "adv9216414380992";
  pixelid2 = scriptEl.dataset.id2;
}

otag("init", pixelId);
if (pixelid2) {
  otag2("init", pixelid2);
}

document.addEventListener("DOMContentLoaded", function (event) {
  const depositForm = document.getElementById("deposit_form");
  if (depositForm) {
    depositForm.addEventListener("submit", submitEvent);
    let hasBeenClicked = false;
    function submitEvent() {
      if (hasBeenClicked) {
        return;
      }
      hasBeenClicked = true;
      registerEvent("deposit");
    }
  }

  if (window.location.href.indexOf("register-done") != -1) {
    registerEvent("registration");
  }

  waitForElementRetry("#form-state", { timeout: 99999, maxRetries: 3, root: document.getElementById('_rht_toaster') }).then((el) => {
    if (el.dataset.value === 'register-done') {
      registerEvent("registration");
    }
  }).catch((err) => {
    console.log(err);
  })
});



async function registerEvent(type) {
  let siteName = "";
  if (scriptEl) {
    siteName = scriptEl.dataset.siteName;
    console.log({ siteName });
  }
  console.log(`ANALYTICPRO: event ${type} triggered`);
  let username = window.localStorage.getItem("usernamePixel");

  //const usernameHeader = document.querySelectorAll('.username-container span')[0].innerHTML;
  //console.log(`usernameHeader: ${usernameHeader}`);

  //if (usernameHeader && username != usernameHeader) username = usernameHeader;

  if (!username && ["registration", "deposit"].includes(type)) {
    console.log("ANALYTICPRO: No username found");
    return;
  }

  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");
  const utmCampaign =
    searchParams.get("utm_campaign") ?? searchParams.get("UTM_CAMPAIGN");
  const utmContent =
    searchParams.get("utm_content") ?? searchParams.get("UTM_CONTENT");
  const gaId = searchParams.get("gaid");
  const documentReferrer = window.localStorage.getItem("documentReferrer");
  const uniqueToken = generateUniqueToken(siteName);

  const domainName = window.location.hostname;
  const result = await fetch(
    "https://analyticpro.online/pixel/register?eventName=" + type,
    {
      method: "POST",
      headers: {
        accept: "application/json",
        "content-type": "application/json",
      },
      body: JSON.stringify({
        username,
        domainName,
        siteName,
        utmCampaign,
        utmMedium,
        utmSource,
        utmContent,
        documentReferrer,
        siteName,
        uniqueToken,
        gaId,
      }),
    }
  );
  const data = await result.json();

  if (data.data) {
    otag("event", type);
    if (pixelid2) {
      otag2("event", type);
    }
    console.log(`ANALYTICPRO: ${type} otag event triggered`);
  } else {
    console.log(`ANALYTICPRO: ${type} otag event not triggered `);
  }
}

function generateUniqueToken(siteName) {
  let uniqueToken = window.localStorage.getItem("widgetUniqueToken");

  if (!uniqueToken) {
    uniqueToken =
      siteName +
      Math.floor(new Date().getTime() / 1000) +
      generateRandomString(10);
    window.localStorage.setItem("widgetUniqueToken", uniqueToken);
  }

  return uniqueToken;
}

function generateRandomString(length) {
  const characters =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let result = "";
  const charactersLength = characters.length;
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }

  return result;
}
