// source --> https://umbrelepro.ro/wp-content/themes/hello-elementor-child/assets/js/main.js?ver=6.9.4 
jQuery(document).ready(function () {
  // mobile detection
  var isMobile = false; //initiate as false
  // device detection
  if (
    /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(
      navigator.userAgent,
    ) ||
    /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(
      navigator.userAgent.slice(0, 4),
    )
  ) {
    isMobile = true;
  }

  let isRO = jQuery("html").attr("lang").includes("ro");

  // Shop tabs
  if (jQuery(".tab").length) {
    let tab = new URL(window.location.href).searchParams?.get("tab");
    if (tab) {
      console.log({ tab });
      jQuery(".tab").removeClass("tab_active");
      jQuery(`#tab-${tab}`).addClass("tab_active");

      jQuery(".tab_content").removeClass("tab_content_active");
      jQuery(`.tab_content[data-name="${tab}"]`).addClass("tab_content_active");
    }

    jQuery(".tab").on("click", function () {
      let name = jQuery(this)
        .find(".elementor-heading-title")
        .text()
        .toLowerCase()
        .replaceAll(" ", "-");

      jQuery(".tab").removeClass("tab_active");
      jQuery(this).addClass("tab_active");

      jQuery(".tab_content").removeClass("tab_content_active");
      jQuery(`.tab_content[data-name="${name}"]`).addClass(
        "tab_content_active",
      );
    });
  }
  if (jQuery(".shop_products .more").length) {
    jQuery(".shop_products .more").on("click", function () {
      jQuery(this).parent().find(".product_details").toggleClass("visible");
      if (jQuery(this).parent().find(".product_details").hasClass("visible")) {
        jQuery(this).addClass("expanded");
        jQuery(this).text("Close technical details");
      } else {
        jQuery(this).removeClass("expanded");
        jQuery(this).text("More technical details");
      }
    });
  }

  // Mobile Menu
  const menuTrigger = jQuery(".menu-trigger");
  const menuContent = jQuery(".menu-inner-content");
  if (menuTrigger.length && menuContent.length) {
    menuTrigger.on("click", function () {
      menuContent.toggleClass("active");

      if (menuContent.hasClass("active")) {
        jQuery("body").css("overflow-y", "hidden");
        jQuery(".menu-trigger-open").hide();
        jQuery(".menu-trigger-close").show();
      } else {
        jQuery("body").css("overflow-y", "visible");
        jQuery(".menu-trigger-open").show();
        jQuery(".menu-trigger-close").hide();
      }
    });
  }

  // Slider
  if (Swiper) {
    const homeSlider = new Swiper(".home_slider", {
      direction: "horizontal",
      loop: true,
      navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev",
      },
      pagination: {
        clickable: true,
        el: ".swiper-pagination",
      },
      speed: 1000,
      spaceBetween: 25,
      autoplay: false,
      breakpoints: {
        767: {
          spaceBetween: 10,
        },
      },
    });

    // Single Product slider
    const singleProductSliderThumbnails = jQuery("#single_product_slider").data(
      "thumbnails",
    );
    const singleProductSlider = new Swiper("#single_product_slider .swiper", {
      direction: "horizontal",
      loop: true,
      navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev",
      },
      pagination: {
        clickable: true,
        el: ".swiper-pagination",
        renderBullet: function (index, className) {
          return `<span class="${className}"><img src="${singleProductSliderThumbnails[index]}" alt="image thumbnail ${index}" /></span>`;
        },
      },
      speed: 1000,
      spaceBetween: 0,
      autoplay: false,
    });
  }

  // WooCommerce
  jQuery(document).on("change", ".qty", function () {
    jQuery("[name='update_cart']").removeAttr("disabled");
    jQuery("[name='update_cart']").trigger("click");
  });
  jQuery("#single-product-accordion").accordionjs({
    slideSpeed: 400,
    closeAble: true,
  });

  // Change single page elements on variation change
  jQuery(".single-product-wrapper").on(
    "show_variation",
    function (event, variation) {
      // console.log(variation);
      jQuery(".astreea_variation_title").text(
        variation.attributes["attribute_choose-model"],
      );
      jQuery(".astreea_variation_price").html(
        `<div class="elementor-widget-container">Price/unit: <span style="font-size: 1.25rem"><strong>€${variation.display_price}</strong></span><sup>.00</sup></div>`,
      );
    },
  );

  // Header submenu container
  function scrollDetect() {
    if (!jQuery(".header-submenu-container").length) {
      return;
    }
    let lastScroll = 0;

    window.onscroll = function () {
      let currentScroll =
        document.documentElement.scrollTop || document.body.scrollTop; // Get Current Scroll Value

      if (currentScroll > 0 && lastScroll <= currentScroll) {
        lastScroll = currentScroll;
        jQuery("body").addClass("scrolled");
        jQuery(".header-submenu-container").css("z-index", "51");
      } else {
        lastScroll = currentScroll;
        jQuery("body").removeClass("scrolled");
        setTimeout(function () {
          jQuery(".header-submenu-container").css("z-index", "49");
        }, 500);
      }
    };
  }
  scrollDetect();

  // Add to cart
  jQuery(".add_to_cart").on("click", function (e) {
    e.preventDefault();

    const variation_id_or_else_product_id = !!jQuery(this).attr(
      "data-product-variation-id",
    )
      ? jQuery(this).attr("data-product-variation-id")
      : jQuery(this).attr("data-product-id");
    const quantity = jQuery('input[name="qty"]').val();

    const data = {
      quantity,
      product_id: variation_id_or_else_product_id,
    };

    console.log({ data });

    jQuery.ajax({
      type: "POST",
      url: wc_add_to_cart_params.wc_ajax_url
        .toString()
        .replace("%%endpoint%%", "add_to_cart"),
      data: data,
      dataType: "json",
      success: function (res) {
        // console.log({ res });
        jQuery(document.body).trigger("added_to_cart", [
          res.fragments,
          res.cart_hash,
        ]);
      },
      error: function (err) {
        console.log({ err });
      },
    });
  });

  // Custom product variation selection
  if (
    jQuery(".custom_product_attributes").length &&
    jQuery(".add_to_cart").length
  ) {
    function formatDefaultVariation(obj) {
      let formatted_default_variation = {};
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          formatted_default_variation["attribute_" + key] = obj[key];
        }
      }
      return formatted_default_variation;
    }

    function getDefaultOrSelectedVariationId(variations, default_variation) {
      for (let variation of variations) {
        if (
          JSON.stringify(variation.attributes) ==
          JSON.stringify(default_variation)
        ) {
          jQuery(".add_to_cart").attr(
            "data-product-variation-id",
            variation.variation_id,
          );
          jQuery(".licco_warranty_popup_open").attr(
            "data-id",
            variation.variation_id,
          );
          console.log({ selectedVarId: variation.variation_id });

          jQuery(".single-product-wrapper .amount").replaceWith(
            variation.display_formatted_price,
          );
          console.log(variation.display_formatted_price);
        }
      }
    }

    const variations =
      jQuery(".add_to_cart").data("product_variations") || null;

    if (variations) {
      const default_variation = jQuery(".add_to_cart").data(
        "product_default_variation",
      )
        ? formatDefaultVariation(
            jQuery(".add_to_cart").data("product_default_variation"),
          )
        : variations[0]?.attributes;

      getDefaultOrSelectedVariationId(variations, default_variation);

      // let selected_variation_id = getDefaultOrSelectedVariationId(variations);
      // let selected_attributes = default_variation;

      // console.log({ default_variation, selected_variation_id });

      jQuery(".custom_product_attribute").each(function () {
        let attribute_name = jQuery(this).data("attribute-name");
        let attribute_value = jQuery(this).data("attribute-value");

        if (jQuery(this).find("select")) {
          jQuery(this)
            .find("select")
            .on("change", function () {
              default_variation[attribute_name] = jQuery(this).val();
              console.log({ default_variation });
              getDefaultOrSelectedVariationId(variations, default_variation);
            });
        }
      });
    }
  }
  jQuery(".custom_product")
    .find("select")
    .on("change", function (e) {
      window.location = e.target.value;
    });

  // Mobile menu
  jQuery(document).on(
    "click",
    "#masthead .hndsm_menu_wrapper .menu-item-has-children > a",
    function (e) {
      e.preventDefault();
      let isActive = jQuery(this)
        .closest(".menu-item-has-children")
        .hasClass("visible");
      jQuery(
        "#masthead .hndsm_menu_wrapper .menu-item-has-children",
      ).removeClass("visible");
      if (isActive) {
        jQuery(this).closest(".menu-item-has-children").removeClass("visible");
      } else {
        jQuery("#masthead .contact_map").removeClass("visible");
        jQuery(this).closest(".menu-item-has-children").addClass("visible");
      }
    },
  );

  // Mobile footer menu
  if (isMobile) {
    jQuery(document).on("click", ".footer-menu-heading", function (e) {
      e.preventDefault();
      jQuery(this).closest(".footer-menu-container").toggleClass("visible");
    });
  }

  if (jQuery(".hndsm_menu_wrapper").length) {
    jQuery(".hndsm_menu_trigger").on("click", function () {
      jQuery(".main-header").toggleClass("mobile-menu-visible");
      jQuery(".hndsm_menu_wrapper").toggleClass("visible");
    });
  }

  if (typeof tippy !== "undefined") {
    tippy("[data-tippy-content]", {
      placement: "bottom",
    });
  }

  // Map popup
  function clickOnClose(e) {
    e.preventDefault();
    jQuery(".contact_map text").each(function () {
      jQuery(this)[0].classList.remove("selected");
    });

    jQuery(".contact_map path").each(function () {
      jQuery(this)[0].classList.remove("selected");
    });

    jQuery(".contact_map polygon").each(function () {
      jQuery(this)[0].classList.remove("selected");
    });
    jQuery(".contact_map_content_wrapper")
      .removeClass("selected")
      .find(".contact_map_content")
      .html("");
  }
  jQuery(document).on("click", ".contact_map svg", function (e) {
    if (e.target.tagName === "path" || e.target.tagName === "polygon") {
      const svg = jQuery(".contact_map svg");
      const name = e.target.dataset.name;

      let title = "";

      if (isRO) {
        title =
          name.toLowerCase === "bucurești"
            ? `Comenzi pt ${name}`
            : `Comenzi pt județul ${name}`;
      } else {
        title =
          name.toLowerCase === "bucurești"
            ? `Orders for ${name}`
            : `Orders for ${name} county`;
      }

      let phone = "";

      const region1 = "".split(", ");
      const region2 =
        "Botoșani, Suceava, Iași, Neamț, Vaslui, Bacău, Vrancea, Galați".split(
          ", ",
        );
      const region3 =
        "Mehedinți, Dolj, Olt, Argeș, Dâmbovița, Teleorman, Prahova, Giurgiu, Ilfov, Călărași, Ialomița, Buzău, Brăila, Tulcea, Constanța, București, Caraș-Severin, Cluj, Bihor, Arad, Timiș".split(
          ", ",
        );
      const region4 =
        "Sibiu, Brașov, Covasna, Harghita, Mureș, Gorj, Vâlcea, Alba, Hunedoara, Bistrița, Sălaj, Maramureș, Satu Mare".split(
          ", ",
        );

      if (
        region1.includes(name) ||
        region2.includes(name) ||
        region4.includes(name)
      ) {
        phone = "0732 668 463";
      }
      if (region3.includes(name)) {
        phone = "0723 479 726";
      }

      const text = `<h6>${title}:</h6><a href='tel:${phone}'>${phone}</a><div class="close">&times;</div>`;
      const isSelected = jQuery(svg)
        .find(`${e.target.tagName}[data-name='${name}']`)[0]
        .classList.contains("selected");
      console.log({ isSelected });

      jQuery(".contact_map text").each(function () {
        jQuery(this)[0].classList.remove("selected");
      });

      jQuery(".contact_map path").each(function () {
        jQuery(this)[0].classList.remove("selected");
      });

      jQuery(".contact_map polygon").each(function () {
        jQuery(this)[0].classList.remove("selected");
      });

      if (isSelected) {
        jQuery(svg)
          .find(`${e.target.tagName}[data-name='${name}']`)[0]
          .classList.remove("selected");
        jQuery(svg)
          .find(`text[data-name='${name}']`)[0]
          .classList.remove("selected");
      } else {
        jQuery(svg)
          .find(`${e.target.tagName}[data-name='${name}']`)[1]
          .classList.add("selected");
        console.log("---");
        console.log(jQuery(svg));
        console.log(
          jQuery(svg).find(`${e.target.tagName}[data-name='${name}']`),
        );
        jQuery(svg)
          .find(`text[data-name='${name}']`)[1]
          .classList.add("selected");
      }
      jQuery(".contact_map_content_wrapper")
        .addClass("selected")
        .find(".contact_map_content")
        .html(text);
    }
  });

  jQuery(document).on("click", ".contact_map_content .close", function (e) {
    clickOnClose(e);
  });

  const contactMapWrapper = jQuery(".contact_map_content_wrapper.selected");
  jQuery(document).on("click", contactMapWrapper, function (e) {
    if (e.target.classList.contains("contact_map_content_wrapper")) {
      clickOnClose(e);
    }
  });

  jQuery(".comenzi-telefonice-mobil").on("click", function () {
    jQuery("#masthead .contact_map").toggleClass("visible");
  });

  // GDPR trigger
  if (jQuery("[data-href]").length) {
    jQuery("[data-href]").on("click", function (e) {
      e.preventDefault();
    });
  }
  if (jQuery(".moove-gdpr-tab-main .tab-title").length) {
    jQuery(".moove-gdpr-tab-main .tab-title").on("click", function () {
      jQuery(this).closest(".moove-gdpr-tab-main").toggleClass("visible");
    });
  }

  // CV upload form
  if (jQuery(".cv").length) {
    jQuery(".cv").on("click", function (e) {
      e.preventDefault();
      jQuery(this).toggleClass("visible");
      jQuery(this)
        .closest(".e-con-inner")
        .find(".cv-container")
        .toggleClass("visible");
    });
    jQuery(".cv-label").on("click", function (e) {
      e.preventDefault();
      jQuery(".cv-container input[type=file]").click();
    });
    jQuery(".cv-container input[type=file]").on("change", function (e) {
      let fileName = e.target.files[0].name;
      jQuery(".cv-file-name").text(fileName);
    });
    jQuery(document).on(
      "wpcf7mailsent",
      function () {
        jQuery(".cv-file-name").text("");
      },
      false,
    );
  }

  if (
    jQuery(".solicita-oferta-trigger").length ||
    jQuery(".solicita-oferta-pergole-trigger").length ||
    jQuery(".solicita-oferta-generala-trigger").length
  ) {
    function produse_selectate_state(value, lang = "") {
      let produse_selectate =
        JSON.parse(sessionStorage.getItem("produse_selectate")) || [];
      if (value) {
        if (produse_selectate.includes(value)) {
          produse_selectate = produse_selectate.filter((el) => el !== value);
        } else {
          produse_selectate.push(value);
        }

        sessionStorage.setItem(
          "produse_selectate",
          JSON.stringify(produse_selectate),
        );
      }

      let produse_selectate_lista = "";
      produse_selectate.map((produs) => {
        produse_selectate_lista += `<li><span class="close" role="button">&times;</span><span class="text">${produs}</span></li>`;
      });

      let produseSelectateText = isRO
        ? "PRODUSE SELECTATE"
        : "SELECTED PRODUCTS";

      let html =
        produse_selectate.length &&
        `<div class="formular-solicita-oferta-produse-selectate">
      <strong>${produseSelectateText}:</strong>
      <ul>
        ${produse_selectate_lista}
      </ul>
    </div>`;

      // Set the value of the "select" element to include the new string in the email
      let selectValue = produse_selectate.reduce(
        (acc, produs) => (acc.length > 0 ? acc + ", " + produs : acc + produs),
        "",
      );

      let formWrapper = jQuery(
        ".formular-solicita-oferta-generala:not(.lang-ro)",
      );
      if (lang.length && lang.includes("ro")) {
        formWrapper = jQuery(".formular-solicita-oferta-generala.lang-ro");
      }

      console.log({ formWrapper });

      if (formWrapper.find(".wpforms-field select option.hidden").length) {
        formWrapper
          .find(".wpforms-field select option.hidden")
          .attr("value", selectValue)
          .text(selectValue);
      } else {
        let newOption = jQuery("<option>")
          .attr("value", selectValue)
          .addClass("hidden")
          .text(selectValue);
        formWrapper.find(".wpforms-field select").append(newOption);
      }

      // console.log(formWrapper.find(".wpforms-field select").val());
      formWrapper
        .find(".wpforms-field select option.hidden")
        .prop("selected", true)
        .attr("selected", true);
      // console.log({
      //   currentValue: formWrapper.find(".wpforms-field select").val(),
      // });

      formWrapper.find(".formular-solicita-oferta-produse-selectate").remove();
      if (produse_selectate_lista.length > 0) {
        formWrapper.find('.wpforms-field[data-field-id="9"]').append(html);
      }
    }

    // Clear selected products after popup close
    jQuery(document).on("pumAfterClose", function (event, popup) {
      jQuery(".formular-solicita-oferta-produse-selectate").remove();
      sessionStorage.setItem("produse_selectate", JSON.stringify([]));
    });

    jQuery(document).on(
      "change",
      ".formular-solicita-oferta-generala .wpforms-field select",
      function () {
        let value = jQuery(this).find(":selected").text();
        let lang = jQuery("html").attr("lang");
        produse_selectate_state(value, lang);
        console.log({ value, lang });
      },
    );

    jQuery(document).on(
      "click",
      ".formular-solicita-oferta-produse-selectate li span.close",
      function () {
        let value = jQuery(this).closest("li").find(".text").text();
        let lang = jQuery("html").attr("lang");
        produse_selectate_state(value, lang);
      },
    );

    jQuery(document).on("click", ".solicita-oferta-trigger", function (e) {
      e.preventDefault();
      let product_id = String(jQuery(this).data("product-id"));
      if (product_id === "undefined") {
        return;
      }

      let options_data = jQuery(this).data("options");
      let options = "";
      for (let option in options_data) {
        options += `<option value="${options_data[option]}" ${
          product_id && option == product_id ? "selected" : ""
        }>${options_data[option]}</option>`;
      }
      jQuery(".formular-solicita-oferta .wpforms-field select").html(options);
      // let lang = jQuery("html").attr("lang");
      // produse_selectate_state(null, lang);
      if (isRO) {
        PUM.open(13554);
      } else {
        PUM.open(12654);
      }
    });

    // Solicita oferta Pergole
    jQuery(document).on(
      "click",
      ".solicita-oferta-pergole-trigger",
      function (e) {
        e.preventDefault();
        let product_id = String(jQuery(this).data("product-id"));
        if (product_id === "undefined") {
          return;
        }

        let options_data = jQuery(this).data("options");
        let options = "";
        for (let option in options_data) {
          options += `<option value="${options_data[option]}" ${
            product_id && option == product_id ? "selected" : ""
          }>${options_data[option]}</option>`;
        }
        jQuery(".formular-solicita-oferta .wpforms-field select").html(options);
        // produse_selectate_state();

        if (isRO) {
          PUM.open(13547);
        } else {
          PUM.open(13457);
        }
      },
    );

    // Solicita oferta generala
    jQuery(document).on(
      "click",
      ".solicita-oferta-generala-trigger",
      function (e) {
        e.preventDefault();

        let options_data = jQuery(
          ".formular-solicita-oferta-generala form",
        ).data("options");
        let options = "";
        for (let option in options_data) {
          options += `<option value="${options_data[option]}">${options_data[option]}</option>`;
        }
        jQuery(".formular-solicita-oferta-generala .wpforms-field select").html(
          options,
        );

        let lang = jQuery("html").attr("lang");
        produse_selectate_state(null, lang);
        if (isRO) {
          PUM.open(12754);
        } else {
          PUM.open(13551);
        }
      },
    );
  }

  if (jQuery('[data-link="phone_numbers"]').length) {
    jQuery('[data-link="phone_numbers"]').on("click", function () {
      if (isRO) {
        PUM.open(15626);
      } else {
        PUM.open(15635);
      }
    });
  }

  // Lang switcher
  if (jQuery(".licco_lang_switcher").length) {
    jQuery(".licco_lang_switcher_header").on("click", function () {
      jQuery(this).closest(".licco_lang_switcher").toggleClass("active");
    });
    jQuery(document).on("click", function (e) {
      let ifClickedOutsideSwitcher = !jQuery(e.target).closest(
        ".licco_lang_switcher",
      ).length;
      if (ifClickedOutsideSwitcher) {
        jQuery(".licco_lang_switcher").removeClass("active");
      }
    });
  }

  // Accessories popup
  // if (jQuery(".licco_warranty_popup_warranty").length) {
  // Change quantity
  jQuery(document).on(
    "change keyup",
    ".licco_warranty_popup_warranty input",
    function (e) {
      if (Number(e.target.value) > 0) {
        jQuery(this)
          .closest(".licco_warranty_popup_warranty")
          .find("button")
          .prop("disabled", false);
      } else {
        jQuery(this)
          .closest(".licco_warranty_popup_warranty")
          .find("button")
          .prop("disabled", true);
      }
    },
  );
  // Change attribute
  jQuery(document).on(
    "change keyup",
    ".licco_warranty_popup_warranty select",
    function (e) {
      let price = JSON.parse(jQuery(this).find(":selected").data("price"));
      console.log(price);
      jQuery(this)
        .closest(".licco_warranty_popup_warranty")
        .find(".licco_warranty_popup_warranty_price strong")
        .html(price);
    },
  );
  // Add accessory to cart
  jQuery(document).on(
    "click",
    "button.licco_warranty_add_button:not(:disabled)",
    function (e) {
      e.preventDefault();

      let current_language = jQuery("html").attr("lang").split("-")[0];
      let product_id = jQuery(this)
        .closest(".licco_warranty_popup_warranty")
        .data("id");
      let accessory_quantity = jQuery(this)
        .closest(".licco_warranty_popup_warranty")
        .find("input")
        .val();
      let accessory_id = jQuery(this)
        .closest(".licco_warranty_popup_warranty")
        .find("[name='accessory_id']")
        .val();

      const post_data = {
        current_language,
        product_id,
        accessory_id,
        accessory_quantity,
      };
      console.log(post_data);

      var data = {
        action: "update_order_review",
        security: custom_wc_checkout_params.update_order_review_nonce,
        post_data: jQuery.param(post_data),
      };

      const popup = jQuery(this).closest(".licco_warranty_popup_overlay");
      popup.addClass("loading");
      jQuery(".xoo-wsc-modal").addClass("xoo-wsc-loading");

      jQuery.post(
        custom_wc_checkout_params.ajax_url,
        data,
        function (response) {
          console.log(response);

          // refresh content of side cart
          let newSideCardContent = jQuery(
            response.fragments["div.xoo-wsc-container"],
          );
          jQuery(".xoo-wsc-container").replaceWith(newSideCardContent);

          if (jQuery('[name="update_cart"]').length) {
            jQuery(".woocommerce-cart-form__cart-item select").each(
              function () {
                let name = jQuery(this).attr("name");

                let start = name.indexOf("[") + 1;
                let end = name.indexOf("]");
                let cart_item_key = name.substring(start, end);

                let updated_quantity = jQuery(
                  `.xoo-wsc-container .xoo-wsc-product[data-key="${cart_item_key}"] .xoo-wsc-qty`,
                ).val();
                jQuery(this).val(updated_quantity);
              },
            );
            jQuery('[name="update_cart"]').removeAttr("disabled");
            setTimeout(function () {
              jQuery('[name="update_cart"]').trigger("click");
              popup.removeClass("active");
            }, 200);
          } else {
            popup.removeClass("active");
            jQuery(document.body).trigger("wc_fragment_refresh");
          }

          // reset popup qty input field
          jQuery(
            ".licco_warranty_popup_warranty input[name='product_quantity']",
          ).val(1);
          jQuery(".licco_warranty_popup_warranty button").prop(
            "disabled",
            false,
          );

          popup.removeClass("loading");
          jQuery(".xoo-wsc-modal").removeClass("xoo-wsc-loading");
        },
      );
    },
  );
  // }

  // Format accessory label
  function licco_format_accessory_label() {
    if (jQuery(".fee").length) {
      jQuery(".fee th").each(function () {
        const text = jQuery(this).text();
        const substring = text.indexOf("For");
        const name1 = text.slice(0, substring);
        const name2 = text.slice(substring);
        const newName = `${name1} <span>${name2}</span>`;
        // console.log(newName);
        jQuery(this).html(newName);
      });
    }
  }
  licco_format_accessory_label();
  jQuery(document).on("update_checkout updated_cart_totals", function () {
    licco_format_accessory_label();
  });

  // Remove accessory fee
  jQuery(document).on(
    "click",
    ".licco_side_cart_item_warranty_remove",
    function (e) {
      e.preventDefault();

      let current_language = jQuery("html").attr("lang").split("-")[0];
      let product_id = jQuery(this).attr("data-id");
      let accessory_id = jQuery(this).attr("data-accessory-id");

      let accessory_quantity = jQuery(this)
        .closest(".licco_side_cart_item_warranty")
        .attr("data-quantity");

      const post_data = {
        current_language,
        remove_fee: true,
        product_id,
        accessory_id,
        accessory_quantity,
      };
      console.log(post_data);

      var data = {
        action: "update_order_review",
        security: custom_wc_checkout_params.update_order_review_nonce,
        post_data: jQuery.param(post_data),
      };

      jQuery(".xoo-wsc-modal").addClass("xoo-wsc-loading");
      jQuery.post(
        custom_wc_checkout_params.ajax_url,
        data,
        function (response) {
          console.log(response);

          // refresh content of side cart
          let newSideCardContent = jQuery(
            response.fragments["div.xoo-wsc-container"],
          );
          jQuery(".xoo-wsc-container").replaceWith(newSideCardContent);

          if (jQuery('[name="update_cart"]').length) {
            jQuery('[name="update_cart"]').removeAttr("disabled");
            setTimeout(function () {
              jQuery('[name="update_cart"]').trigger("click");
            }, 200);
          } else {
            jQuery(document.body).trigger("wc_fragment_refresh");
          }
          jQuery(".xoo-wsc-modal").removeClass("xoo-wsc-loading");
        },
      );
    },
  );
  function open_licco_warranty_popup(_this, productId) {
    jQuery(_this)
      .parent()
      .parent()
      .find(".licco_warranty_popup_overlay")
      .addClass("active");

    jQuery(".licco_warranty_popup_warranty").attr("data-id", productId);
  }

  function close_licco_warranty_popup() {
    jQuery(".licco_warranty_popup_overlay").removeClass("active");
  }

  jQuery(document).on("click", ".licco_warranty_popup_open", function () {
    const _this = jQuery(this);
    const productId = jQuery(this).attr("data-id");
    console.log({ this: _this, productId });
    open_licco_warranty_popup(_this, productId);
  });

  // jQuery(document).on("click", ".licco_warranty_popup_cancel", () => {
  //   close_licco_warranty_popup();
  // });

  jQuery(document).on("click", ".licco_warranty_popup_close", () => {
    close_licco_warranty_popup();
  });

  jQuery(document).on("click", ".licco_warranty_popup_overlay", (e) => {
    if (e.target.className.includes("licco_warranty_popup_overlay")) {
      close_licco_warranty_popup();
    }
  });

  // Cookie popup trigger
  if (jQuery(".cookies-modal-trigger a").length) {
    jQuery(".cookies-modal-trigger a").attr(
      "data-href",
      "#moove_gdpr_cookie_modal",
    );
    jQuery(".cookies-modal-trigger a").on("click", function (e) {
      e.preventDefault();
    });
  }

  // fix the overlapping of the header by the admin bar
  if (jQuery("#wpadminbar").length) {
    let barHeight = jQuery("#wpadminbar").height();
    jQuery("#masthead").css("top", `${barHeight}px`);
  }

  // see less/more logos animation
  if (jQuery(".logos-trigger").length) {
    jQuery(".logos-trigger a").on("click", function (e) {
      e.preventDefault();
      jQuery(this)
        .closest(".logos-row")
        .nextAll(".logos-row")
        .addClass("visible");
      jQuery(this).remove();
    });
  }

  // Add company related fields to Checkout page
  if (jQuery('[name="billing_status"]').length) {
    jQuery('[name="billing_status"]').select2();
  }
  function getUrlVars() {
    var vars = [],
      hash;
    var hashes = window.location.href
      .slice(window.location.href.indexOf("?") + 1)
      .split("&");
    for (var i = 0; i < hashes.length; i++) {
      hash = hashes[i].split("=");
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  }

  // "persoana fizica - persoana juridica" switcher on checkout page
  var client = getUrlVars()["client"];

  if (
    client === undefined ||
    client == "persoana-fizica" ||
    client == "individual"
  ) {
    jQuery("input#persoana-fizica").attr("checked", "checked");
    jQuery("#billing_first_name_field").show();
    jQuery("#billing_last_name_field").show();
    jQuery("#billing_company_field").hide();
    jQuery("#billing_j_field").hide();
    jQuery("#billing_cui_field").hide();
    jQuery("#billing_nume_banca_field").hide();
    jQuery("#billing_iban_field").hide();

    jQuery("#billing_status option:last-child").removeAttr("selected");
    jQuery("#billing_status option:first-child").attr("selected", "selected");
    jQuery("#billing_status option:first-child").insertBefore(
      "#billing_status option:last-child",
    );
  } else if (client == "persoana-juridica" || client == "company") {
    jQuery("input#persoana-juridica").attr("checked", "checked");

    jQuery("#billing_first_name_field").show(); //hide
    jQuery("#billing_last_name_field").show(); // hide
    jQuery("#billing_company_field").show();
    jQuery("#billing_j_field").show();
    jQuery("#billing_cui_field").show();
    jQuery("#billing_nume_banca_field").show();
    jQuery("#billing_iban_field").show();

    jQuery("#billing_status option:first-child").removeAttr("selected");
    jQuery("#billing_status option:last-child").attr("selected", "selected");
    jQuery("#billing_status option:last-child").insertBefore(
      "#billing_status option:first-child",
    );
  }

  // Action with the selector (Showing/hiding and adding/removing classes)
  jQuery("#billing_status_field").change(function () {
    // For "Persoana Juridica"
    let currentUrl = window.location.href;
    let baseUrl = currentUrl.split("?")[0];

    if (client == "persoana-fizica" || client === undefined) {
      let newUrl = baseUrl + "?client=persoana-juridica";

      location.href = newUrl;
    }
    // For "Persoana Fizica"
    else if (client == "persoana-juridica") {
      jQuery("#billing_first_name_field").show(function () {
        jQuery(this).addClass("validate-required");
        jQuery("#billing_company").val("");
      });
      jQuery("#billing_last_name_field").show(function () {
        jQuery(this).addClass("validate-required");
        jQuery("#billing_bt_id").val("");
      });
      let newUrl = baseUrl + "?client=persoana-fizica";
      location.href = newUrl;
    }
  });
});