$(document).ready(function () {
  const userAgent = navigator.userAgent;
  const isiOS = userAgent.includes("iPhone") || userAgent.includes("iPad");
  const isMobile = isiOS || userAgent.includes("Android");
  const usernameContainer =
    document.querySelector(".username-container > span") ||
    document.querySelector(".username");
  const usernameLoggedIn = usernameContainer?.textContent ?? "";
  const loggedInMenu = document.querySelector(".user-menu");
  const isLoggedIn = usernameLoggedIn || loggedInMenu;
  const isPromoPage = window.location.href.includes("promotion");

  function addPromoBanner() {
    let url = "/register";

    if (!isMobile) {
      const isRegisterModalExists = $("#register_modal").length > 0;
      let image = "https://js.analyticpro.online/promo-banner-register.png";

      if (isLoggedIn) {
        image = "https://js.analyticpro.online/promo-banner-deposit.png";
        url = "/deposit";
      }

      let anchor = `<a id="promo-banner" href="${url}"><img style="width: 100%" src="${image}" /><a>`;

      if (isRegisterModalExists) {
        anchor = `<a id="promo-banner" href="#" data-toggle="modal" data-target="#register_modal"><img style="width: 100%" src="${image}" /><a>`;
      }

      const promoBanner = `<div style="margin-bottom: 15px">${anchor}</div>`;
      const promotionList = $(".promotion-list");
      if (
        promotionList.closest(".standard-container-with-sidebar").length > 0
      ) {
        promotionList.prepend(promoBanner);
      } else {
        promotionList.parent().prepend(promoBanner);
      }
    } else {
      let image =
        "https://js.analyticpro.online/promo-banner-register-mobile.png";

      if (isLoggedIn) {
        image = "https://js.analyticpro.online/promo-banner-deposit-mobile.png";
        url = "/deposit";
      }

      const promoBanner = `<div style="margin-bottom: 15px"><a id="promo-banner" href="${url}"><img style="width: 100%" src="${image}" /><a></div>`;
      $(promoBanner).insertBefore(".promotion-selection");
    }

    $("#promo-banner").click(async function (e) {
      const existingQueryParams = window.localStorage.getItem("queryParams");
      let queryParams = new URLSearchParams(existingQueryParams);
      if (!existingQueryParams) {
        queryParams = new URLSearchParams();
      }
      queryParams.set("utm_content", "promobanner");
      window.localStorage.setItem("queryParams", queryParams.toString());

      let eventName = "promoBannerClickRegister";
      if (isLoggedIn) {
        eventName = "promoBannerClickDeposit";
      }
      registerEvent(eventName);
    });
  }

  if (isPromoPage) {
    addPromoBanner();
  }
});
