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

// Meta Pixel Code
!(function (f, b, e, v, n, t, s) {
  if (f.fbq) return;
  n = f.fbq = function () {
    n.callMethod ? n.callMethod.apply(n, arguments) : n.queue.push(arguments);
  };
  if (!f._fbq) f._fbq = n;
  n.push = n;
  n.loaded = !0;
  n.version = "2.0";
  n.queue = [];
  t = b.createElement(e);
  t.async = !0;
  t.src = v;
  s = b.getElementsByTagName(e)[0];
  s.parentNode.insertBefore(t, s);
})(
  window,
  document,
  "script",
  "https://connect.facebook.net/en_US/fbevents.js"
);

let metaPixelId = [];

if (fbPixelScriptEl) {
  metaPixelId = fbPixelScriptEl.dataset.id.split(",").map((id) => id.trim());

  for (const id of metaPixelId) {
    fbq("init", id);
  }

  fbq("track", "PageView");
}

document.addEventListener("DOMContentLoaded", function (event) {
  if (metaPixelId.length > 0) {
    if (window.location.href.indexOf("register-done") != -1) {
      fbq("track", "CompleteRegistration");
    }

    const isDepositPage = window.location.href.indexOf("deposit") != -1;

    if (isDepositPage) {
      fbq("track", "InitiateCheckout");
      const depositForm = document.getElementById("deposit_form");

      if (depositForm) {
        depositForm.addEventListener("submit", submitEvent);

        let hasBeenClicked = false;
        function submitEvent() {
          if (hasBeenClicked) {
            return;
          }

          hasBeenClicked = true;

          const amountField = document.getElementById("Amount");
          let amount = 0;

          if (amountField) {
            amount = parseFloat(amountField.value) || 0;
          }

          const username = window.localStorage.getItem("usernamePixel");
          const websiteName = fbPixelScriptEl.dataset.websiteName;

          let purchasePayload = { value: amount, currency: "IDR" };
          let options = {};

          if (username && websiteName) {
            options = {
              eventID: `${websiteName}-${username}`,
            };
          }

          fbq("track", "Purchase", purchasePayload);
          console.log(amount);
        }
      }
    }

    const subpaths = [
      "hot-games",
      "slots",
      "casino",
      "race",
      "others",
      "sport",
      "crash-game",
      "arcade",
      "poker",
      "e-sports",
      "promotion",
      "provider-event",
    ];

    const url = decodeURIComponent((window.location.href || "").toLowerCase());
    const containsSubpath = subpaths.some((sp) =>
      url.includes(sp.toLowerCase())
    );

    if (containsSubpath) {
      // URL contains one of the subpaths — handle accordingly
      fbq("track", "ViewContent");
      console.log("URL contains subpath:", url);
    }
  }
});
