(function () {
  const AUTH_BTN_SELECTOR = ".auth-btn";
  const GP_STORE_BTN_SELECTOR = ".gp-btn";
  const APP_STORE_BTN_SELECTOR = ".as-btn";
  const AF_QR_CONTAINER_SELECTOR = ".af-qr";
  const AF_QR_ITEM_CONTAINER_ID = "af-qr-container";
  const AF_QR_ITEM_CONTAINER_SELECTOR = `#${AF_QR_ITEM_CONTAINER_ID}`;

  const STORE_IOS_ENABLED = true;
  const STORE_ANDROID_ENABLED = true;

  const AF_URL_ALL = "https://olympmatix.onelink.me/O5dQ";
  const AF_URL_IOS = "https://olympmatix-ios.onelink.me/3Dae";
  const AF_URL_ANDROID = "https://olympmatix-android.onelink.me/jZ1v";

  const AF_URL_NA_ALL = "https://olympmatix.onelink.me/O5dQ/1e1ymyqd";
  const AF_URL_NA_IOS = "https://olympmatix-ios.onelink.me/3Dae/fa7e0sxf";
  const AF_URL_NA_ANDROID = "https://olympmatix-android.onelink.me/jZ1v/5ermf26t";

  const waitFor = (predicateFunc, timeoutLimit) => {
    return new Promise((resolve, reject) => {
      let timeout;
      let interval;

      const check = () => {
        if (!predicateFunc()) {
          return;
        }

        clearInterval(interval);
        clearTimeout(timeout);
        resolve({});
      };

      interval = setInterval(check, 100);
      check();

      if (!timeoutLimit) {
        return;
      }

      timeout = setTimeout(() => {
        clearInterval(interval);
        reject();
      }, timeoutLimit);
    });
  };

  const waitForContainer = (selector, timeoutLimit) => {
    return waitFor(() => Boolean(document.querySelector(selector)), timeoutLimit);
  };

  const initLinks = (selector, url) => {
    const links = document.querySelectorAll(selector);
    links.forEach((l) => {
      l.setAttribute("href", url);
      l.setAttribute("target", "_blank");
      l.setAttribute("rel", "noreferrer nofollow noopener");
    });
  };

  const createQrContainer = () => {
    const existing = document.querySelectorAll(AF_QR_ITEM_CONTAINER_SELECTOR);
    existing.forEach((c) => c.remove());

    const root = document.querySelector(AF_QR_CONTAINER_SELECTOR);
    const container = document.createElement("div");
    container.setAttribute("id", AF_QR_ITEM_CONTAINER_ID);
    root.append(container);
  };

  const initAuthBtns = () => {
    const btns = Array.from(document.querySelectorAll(AUTH_BTN_SELECTOR));
    btns.map((btn) => {
      btn.addEventListener("click", (e) => {
        e.preventDefault();
        window.AuthModule.onOpen();
      });
    });
  };

  const initStoreBtn = async () => {
    const [iosLink, androidLink] = await Promise.all([
      window.AuthModule.AppsflyerClient.getPlatformSmartScriptClickUrl("ios"),
      window.AuthModule.AppsflyerClient.getPlatformSmartScriptClickUrl("android"),
    ]);
    if (STORE_IOS_ENABLED) {
      initLinks(`${APP_STORE_BTN_SELECTOR} a`, iosLink);
    }
    if (STORE_ANDROID_ENABLED) {
      initLinks(`${GP_STORE_BTN_SELECTOR} a`, androidLink);
    }
  };

  const initStoreQr = async () => {
    createQrContainer();
    await waitForContainer(AF_QR_ITEM_CONTAINER_SELECTOR);
    await window.AuthModule.AppsflyerClient.generateQrCode(AF_QR_ITEM_CONTAINER_ID, {
      codeColor: "#000",
    });
  };

  const initAppsflyer = async () => {
    await waitFor(() => Boolean(window.AuthModule && window.AuthModule.AppsflyerClient));

    await window.AuthModule.AppsflyerClient.init(
      {
        oneLink: {
          common: AF_URL_ALL,
          ios: AF_URL_IOS,
          android: AF_URL_ANDROID,
          noAttribution: {
            common: AF_URL_NA_ALL,
            ios: AF_URL_NA_IOS,
            android: AF_URL_NA_ANDROID,
          },
        },
        appAvailable: {
          ios: STORE_IOS_ENABLED,
          android: STORE_ANDROID_ENABLED,
          androidGooglePlay: true,
        },
      },
      "/js/smart-script.js"
    );

    await initStoreBtn();
    await initStoreQr();
  };

  const hideHeader = () => {
    const search = new URLSearchParams(window.location.search);
    if (search.get("legal") !== "true") {
      return;
    }

    const header = document.querySelector("#t-header, .uc-header");
    if (header) {
      header.style.display = "none";
    }

    const footer = document.querySelector("#t-footer, .uc-footer");
    if (footer) {
      footer.style.display = "none";
    }
  };

  const run = async () => {
    const scripts = [hideHeader, initAuthBtns, initAppsflyer];

    scripts.map(async (s) => {
      try {
        await s();
      } catch (e) {
        console.log('Running "%s" script error:', s.name, e);
      }
    });
  };

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