var base_url = "https://v2.pricepanda.app";

jQueryCode = function () {
  jQuery(document).ready(function ($) {
    var shop_name = Shopify.shop;

    if (
      (typeof ShopifyAnalytics !== "undefined" &&
        ShopifyAnalytics.meta &&
        ShopifyAnalytics.meta.page &&
        ShopifyAnalytics.meta.page.pageType == "product") ||
      (window && window.location.pathname.indexOf("/products/") !== -1)
    ) {
      var urlParams = new URLSearchParams(window.location.search);
      var selectedVariant = "";

      var varArr = Array();
      var varArrPublicTitle = Array();

      if (
        typeof ShopifyAnalytics !== "undefined" &&
        ShopifyAnalytics?.meta?.product?.variants?.[0]?.price
      ) {
        if (ShopifyAnalytics.meta.product.variants) {
          ShopifyAnalytics.meta.product.variants.map(function (value) {
            varArr[value.id] = parseFloat(value.price / 100).toFixed(2);
            varArrPublicTitle[value.public_title] = value.id;
          });

          if (urlParams.get("variant") != null) {
            selectedVariant = urlParams.get("variant");
          } else if (
            typeof ShopifyAnalytics !== "undefined" &&
            varArr[ShopifyAnalytics.meta.selectedVariantId]
          ) {
            selectedVariant = ShopifyAnalytics.meta.selectedVariantId;
          } else {
            if (typeof ShopifyAnalytics !== "undefined") {
              selectedVariant = ShopifyAnalytics.meta.product.variants[0].id;
            } else {
              selectedVariant = Object.keys(varArr)[0];
            }
          }

          call_format(selectedVariant, varArr[selectedVariant], "product_page");
        }
      } else {
        $.ajax({
          type: "GET",
          url: window.location.href.split("?")[0] + ".json",
          success: function (res) {
            if (
              res &&
              res.product.variants &&
              res.product.variants.length > 0
            ) {
              res.product.variants.map(function (value) {
                varArr[value.id] = parseFloat(value.price).toFixed(2);
                varArrPublicTitle[value.title] = value.id;
              });

              if (urlParams.get("variant") != null) {
                selectedVariant = urlParams.get("variant");
              } else if (
                typeof ShopifyAnalytics !== "undefined" &&
                varArr[ShopifyAnalytics.meta.selectedVariantId]
              ) {
                selectedVariant = ShopifyAnalytics.meta.selectedVariantId;
              } else {
                if (typeof ShopifyAnalytics !== "undefined") {
                  selectedVariant =
                    ShopifyAnalytics.meta.product.variants[0].id;
                } else {
                  selectedVariant = Object.keys(varArr)[0];
                }
              }

              call_format(
                selectedVariant,
                varArr[selectedVariant],
                "product_page"
              );
            }
          },
        });
      }

      if ($(".current_option_name")[0]) {
        var current_option_name = $(".current_option_name").html();
      }

      window.ppu_productpage_render = function (variantId = null) {
        var urlParams = new URLSearchParams(window.location.search);

        let selectedVariant = variantId;
        if (!selectedVariant && urlParams.get("variant")) {
          selectedVariant = urlParams.get("variant");
        }

        if (selectedVariant && varArr?.[selectedVariant]) {
          call_format(selectedVariant, varArr[selectedVariant], "product_page");
        }
      };

      setInterval(function () {
        urlParams = new URLSearchParams(window.location.search);

        if ($(".current_option_name")[0]) {
          if (current_option_name != $(".current_option_name").html()) {
            current_option_name = $(".current_option_name").html();
            if (varArrPublicTitle[current_option_name]) {
              selectedVariant = varArrPublicTitle[current_option_name];
              call_format(
                selectedVariant,
                varArr[selectedVariant],
                "product_page"
              );
            }
          }
        } else {
          if (urlParams.get("variant") != null) {
            //console.log(Object.keys(varArr).length);
            if (
              selectedVariant != urlParams.get("variant") &&
              varArr[urlParams.get("variant")]
            ) {
              selectedVariant = urlParams.get("variant");

              call_format(
                selectedVariant,
                varArr[selectedVariant],
                "product_page"
              );
            }
          } else {
            if (
              typeof ShopifyAnalytics !== "undefined" &&
              ShopifyAnalytics.meta.selectedVariantId &&
              varArr[ShopifyAnalytics.meta.selectedVariantId] &&
              selectedVariant != ShopifyAnalytics.meta.selectedVariantId
            ) {
              selectedVariant = ShopifyAnalytics.meta.selectedVariantId;

              call_format(
                selectedVariant,
                varArr[selectedVariant],
                "product_page"
              );
            }
          }
        }
      }, 50);
    }

    //Collection script start
    var path = window.location.pathname + window.location.search;
    var divlength = $(".appattic_price_app_coll").length;

    setInterval(function () {
      if (path != window.location.pathname + window.location.search) {
        path = window.location.pathname + window.location.search;
        collection_change();
      }

      if ($(".appattic_price_app_coll").length != divlength) {
        divlength = $(".appattic_price_app_coll").length;
        collection_change();
      }
    }, 50);

    const collection_change = () => {
      $(".appattic_price_app_coll").each(function (index, el) {
        if ($(this).html().trim() == "") {
          let variant_id = $(this).attr("data-id");
          const product_id = $(this).attr("data-app_product_id") || null;
          const cheapestVariant =
            $(this).attr("data-cheapest_variant") === "true" ? true : false;
          let price = $(this).attr("data-price");
          call_format(
            variant_id,
            price,
            "collection_page",
            product_id,
            cheapestVariant
          );
        }
      });
    };

    window.collection_change = collection_change;

    //collection page variants change start

    document.body.addEventListener("click", function (event) {
      if (
        $(event.target)
          .parent()
          .parent()
          .parent()
          .prev()
          .prev()
          .attr("class") &&
        $(event.target)
          .parent()
          .parent()
          .parent()
          .prev()
          .prev()
          .attr("class")
          .split(" ")[0] == "appattic_price_app_coll"
      ) {
        coll_variant_change(
          $($(event.target).parent()[0]).attr("data-var_id"),
          Number($($(event.target).parent()[0]).attr("data-price") / 100),
          $(event.target)
            .parent()
            .parent()
            .parent()
            .prev()
            .prev()
            .attr("class")
            .split(" ")[1],
          $($(event.target).parent()[0]).attr("data-app_product_id"),
          $($(event.target).parent()[0]).attr("data-cheapest_variant")
        );
      }
    });

    //collection page variants change start

    collection_change();

    const coll_variant_change = (
      variantId,
      price,
      className,
      productId = null,
      cheapestVariant = false
    ) => {
      $.ajax({
        type: "POST",
        url: base_url + "/api/preview-product?shop=" + shop_name,
        data: {
          variantId,
          price,
          productId,
          cheapestVariant: cheapestVariant === "true" ? true : false,
        },
        cache: false,
        async: true,
        dataType: "json",
        success: function (response) {
          if (response.status == 200) {
            $("." + className).html(response.data);
          }
        },
      });
    };

    window.coll_variant_change = coll_variant_change;

    //Collection script end

    function call_format(
      variantId,
      price,
      page,
      productId = null,
      cheapestVariant = false
    ) {
      $.ajax({
        type: "POST",
        url: base_url + "/api/preview-product?shop=" + shop_name,
        data: {
          variantId,
          price: Number(price),
          productId,
          cheapestVariant,
        },
        cache: false,
        async: true,
        dataType: "json",
        success: function (response) {
          if (response.status == 200) {
            if (page == "product_page") {
              //product page

              setTimeout(function () {
                $(".appattic_price_app_div").remove();

                //manuall div
                if ($(".appattic_price_span")[0]) {
                  console.log("Manual div");

                  $(".appattic_price_span").html(
                    '<div id="appattic_price_app_div" class="appattic_price_app_div"><span>' +
                      response.data +
                      "</span></div>"
                  );
                } else if ($(".price__unit")[0]) {
                  $($(".price__unit")[0]).after(
                    '<div id="appattic_price_app_div" class="appattic_price_app_div"><span>' +
                      response.data +
                      "</span></div>"
                  );
                  console.log(1);
                } else if ($(".product-single__prices")[0]) {
                  console.log(2);
                  $($(".product-single__prices")[0]).after(
                    '<div id="appattic_price_app_div" class="appattic_price_app_div"><span>' +
                      response.data +
                      "</span></div>"
                  );
                } else if ($(".product-single__price")[0]) {
                  console.log(3);

                  $($(".product-single__price")[0]).after(
                    '<div id="appattic_price_app_div" class="appattic_price_app_div"><span>' +
                      response.data +
                      "</span></div>"
                  );
                } else if ($(".product-price__price")[0]) {
                  console.log(4);
                  $($(".product-price__price")[0]).after(
                    '<div id="appattic_price_app_div" class="appattic_price_app_div"><span>' +
                      response.data +
                      "</span></div>"
                  );
                } else if ($(".product__price")[0]) {
                  console.log(5);
                  $($(".product__price")[0]).after(
                    '<div id="appattic_price_app_div" class="appattic_price_app_div"><span>' +
                      response.data +
                      "</span></div>"
                  );
                } else if ($(".product-pricing")[0]) {
                  console.log(6);
                  $($(".product-pricing")[0]).after(
                    '<div id="appattic_price_app_div" class="appattic_price_app_div"><span>' +
                      response.data +
                      "</span></div>"
                  );
                } else if ($(".product-price-wrap")[0]) {
                  console.log(7);
                  $($(".product-price-wrap")[0]).after(
                    '<div id="appattic_price_app_div" class="appattic_price_app_div"><span>' +
                      response.data +
                      "</span></div>"
                  );
                } else if ($(".product-price")[0]) {
                  console.log(8);
                  $($(".product-price")[0]).after(
                    '<div id="appattic_price_app_div" class="appattic_price_app_div"><span>' +
                      response.data +
                      "</span></div>"
                  );
                } else if ($(".Price")[0]) {
                  console.log(9);
                  $($(".Price")[0]).after(
                    '<div id="appattic_price_app_div" class="appattic_price_app_div"><span>' +
                      response.data +
                      "</span></div>"
                  );
                } else if ($(".price")[0]) {
                  console.log(15);
                  $($(".price")[0]).after(
                    '<div id="appattic_price_app_div" class="appattic_price_app_div"><span>' +
                      response.data +
                      "</span></div>"
                  );
                } else if ($(".price__sale")[0]) {
                  console.log(10);
                  $($(".price__sale")[0]).after(
                    '<div id="appattic_price_app_div" class="appattic_price_app_div"><span>' +
                      response.data +
                      "</span></div>"
                  );
                } else if ($('[data-product-type="price"]')[0]) {
                  console.log(11);
                  $($('[data-product-type="price"]')[0]).after(
                    '<div id="appattic_price_app_div" class="appattic_price_app_div"><span>' +
                      response.data +
                      "</span></div>"
                  );
                } else if ($(".price-per-unit-insert-product-page")[0]) {
                  console.log(12);
                  $($(".price-per-unit-insert-product-page")[0]).after(
                    '<div id="appattic_price_app_div" class="appattic_price_app_div"><span>' +
                      response.data +
                      "</span></div>"
                  );
                } else if ($(".product-single__price-container")[0]) {
                  console.log(13);
                  $($(".product-single__price-container")[0]).after(
                    '<div id="appattic_price_app_div" class="appattic_price_app_div"><span>' +
                      response.data +
                      "</span></div>"
                  );
                } else if ($(".product__price-container")[0]) {
                  console.log(14);
                  $($(".product__price-container")[0]).after(
                    '<div id="appattic_price_app_div" class="appattic_price_app_div"><span>' +
                      response.data +
                      "</span></div>"
                  );
                } else if ($(".product-meta")[0]) {
                  console.log(16);
                  $($(".product-meta")[0]).after(
                    '<div id="appattic_price_app_div" class="appattic_price_app_div"><span>' +
                      response.data +
                      "</span></div>"
                  );
                } else if ($(".new-price")[0]) {
                  console.log(17);
                  $($(".new-price")[0]).after(
                    '<div id="appattic_price_app_div" class="appattic_price_app_div"><span>' +
                      response.data +
                      "</span></div>"
                  );
                } else {
                  if (!$(".easylockdown-price-link")[0]) {
                    $("form").each(function () {
                      if ($(this).attr("action").includes("/cart/add")) {
                        $(this).before(
                          '<div id="appattic_price_app_div" class="appattic_price_app_div"><span>' +
                            response.data +
                            "</span></div>"
                        );
                        return false;
                      }
                    });
                  }
                }
              }, 500);
            } else {
              //collection page
              $(".appattic_price_app_coll-" + variantId).html(response.data);
            }
          }
        },
      });
    }
  });
};

if (window.jQuery) {
  jQueryCode();
} else {
  var script = document.createElement("script");
  document.head.appendChild(script);
  script.type = "text/javascript";
  script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js";

  script.onload = jQueryCode;
}
