$(document).ready(function () {
  $(".daily_deals").slick({
    dots: true,
    infinite: true,
    speed: 300,
    slidesToShow: 2,
    adaptiveHeight: true,
    responsive: [
      {
        breakpoint: 1200,
        settings: {
          slidesToShow: 1,
          slidesToScroll: 1,
        },
      },
      {
        breakpoint: 576,
        settings: {
          slidesToShow: 1,
          slidesToScroll: 1,
        },
      }
    ],
  });

  document
    .querySelectorAll("#dropdown_categories")
    .forEach(function (dropdown) {
      dropdown.addEventListener("mouseenter", function () {
        let menu = this.querySelector(".dropdown-menu");
        if (menu) {
          menu.classList.add("show");
        }
      });

      dropdown.addEventListener("mouseleave", function () {
        let menu = this.querySelector(".dropdown-menu");
        if (menu) {
          menu.classList.remove("show");
        }
      });
    });

  const toggleButtons = document.querySelectorAll(".toggle-products-view");
  const gridListView = document.getElementById("gridlistview");
  const shortDescriptions = document.querySelectorAll(
    ".short_discription_card"
  );

  toggleButtons.forEach((button) => {
    button.addEventListener("click", function () {
      toggleButtons.forEach((btn) => btn.classList.remove("active"));

      this.classList.add("active");

      const dataName = this.getAttribute("data-name");

      if (dataName === "GRID") {
        gridListView.classList.add("row");
        gridListView.classList.remove("list_view_main");
        shortDescriptions.forEach((card) => {
          card.classList.add("d-none");
          card.classList.remove("d-block");
        });
      } else if (dataName === "LIST") {
        gridListView.classList.remove("row");
        gridListView.classList.add("list_view_main");
        shortDescriptions.forEach((card) => {
          card.classList.add("d-block");
          card.classList.remove("d-none");
        });
      }
    });
  });

  $(".btn-mainproduct-cart-buy-now-pro-page").click(function () {
    $(this).children('span').addClass('hiddenText');
    $(this).find('span').hide();
    $(this).find('.loader').show();
    var data = {
      productId: $(this).data('id'),
      productQty: $(this).find('.productQtys').val()
    };
    var redirect = ''
    addToCart(data);
  });


  // $(".btn-mainproduct-cart").click(function () {
  //
  //   data = {
  //     'productId': 1707672
  //   };

  //   addToCart();
  //
  // });
  $(".product-cart-only").click(function () {
    const element = $(this);
    element.find(".button-wrapper span").hide();
    element.find(".loader").show();
    var productId = $(this).data("id");
    var productQty = $(".productQty").val();
    data = { productId, productQty };

    $.ajax({
      dataType: "json",
      data: data,
      type: "post",
      url: "/checkout/cart/add",
      success: function (response) {
        element.find(".loader").hide();
        element.find(".button-wrapper span").show();

        if (response.status) {
          Swal.fire({
            title: response.msg,
            text: "",
            icon: "success",
            showDenyButton: true,
            confirmButtonColor: "#2e2e2e",
            denyButtonColor: "#2e2e2e",
            confirmButtonText: "View Cart",
            denyButtonText: "Checkout",
            background: "#0084C5",
            color: "#ffff",
            iconColor: "#fff",

            showCloseButton: true,
          }).then((result) => {
            if (result.isConfirmed) {
              window.location = window.location.origin + "/checkout/cart";
            } else if (result.isDenied) {
              window.location = window.location.origin + "/checkout/onepage";
            }
          });
          // notify("success",response.msg);
        } else {
          $(".product-cart-only").attr("disabled", false);
          $(".btn-addToCart").html(
            '<i class="fa fa-shopping-cart" aria-hidden="true"></i>Add to Cart'
          );
          notify("error", response.msg);
        }
      },
      complete: function () {
        window.refreshCart();
      },
    });
  });

  window.refreshCart = function () {
    $.ajax({
      url: "/checkout/cart/get-user-products",
      success: function (response) {
        $(".detail-minicart").text(response.totalItems);
        $(".cart-dropdown-load").html(response.itemsSummaryHtml);
        $(".cart-amount").html(response.grandTotal);
        //$(\".count-item\").show();
        if (response.totalItems == 0) {
          //$('header .mobile-cart-sec .block-content').slideUp('slow');
        }
      },
    });
  };

  function wishlist(sku) {
    $.ajax({
      dataType: "json",
      data: {
        product_sku: sku,
      },
      type: "post",
      url: "/catalog/products/wish-list",
      success: function (response) {
        if (response.status == 1) {
          notify("success", response.msg);
        } else {
          notify("error", response.msg);
        }
      },
    });
  }

  function clearCart() {
    ajaxLoader();
    $.ajax({
      dataType: "json",
      url: "/checkout/cart/clear-cart",
      method: "POST",
      success: function (response) {
        if (response.status === 0 || response.status === 1) {
          location.reload();
        }
        location.reload();
      },
    });
  }

  // Buy now Code
  $(".btn-mainproduct-cart-buy-now").click(function () {
    $(this).children("span").addClass("hiddenText");
    $(this).find("span").hide();
    $(this).find(".loader").show();
    var data = {
      productId: $(this).data("id"),
      productQty: $(".productQty").val(),
    };
    var redirect = "";
    addToCart(data);
  });

  function addToCart(data) {
    $.ajax({
      dataType: "json",
      data: data,
      type: "post",
      url: "/checkout/cart/add",
      success: function (response) {
        $(".hiddenText").show();
        $(".hiddenText").siblings(".loader").hide();
        $(".hiddenText").removeClass("hiddenText");
        if (response.status) {
          window.location = "/checkout/onepage";
        } else {
          notify("error", "Something went wrong");
        }
      },
    });
  }

  //header search code
  $(".sm-serachbox-pro").hide();
  $(".btn-search").click(function () {
    var searchedFor =
      $("#search-catalog").val() || $("#search-catalog-mobile").val();

    var searchedCategory = $("#search-category").val();

    if (searchedFor !== "") {
      var url = "/catalog-search/filter/q/" + searchedFor;

      if (searchedCategory !== "") {
        //url += '/filter/category/' + searchedCategory;
      }
      window.location = url;
    }
  });

  var typingTimer;
  var doneTypingInterval = 1000;

  $(".search-catalog-ajax").keyup(function (e) {
    if (e.which != 40 && e.which != 38) {
      if (e.which == 13) {
        $(".btn-search").click();
      } else {
        clearTimeout(typingTimer);
        var text = $(this).val();

        if (text) {
          typingTimer = setTimeout(function () {
            var csrfParam = yii.getCsrfParam();
            var csrfToken = yii.getCsrfToken();
            var searchCategory = $("#search-category").val();
            var data = { text: text, searchCategory: "" };
            data[csrfParam] = csrfToken;

            $.ajax({
              url: "/catalog-search-input",
              type: "post",
              data: data,
              success: function (response) {
                $("#autocomplete").remove();
                $(".sm-serachbox-pro").html(response);
                $(".sm-serachbox-pro").show();
              },
              complete: function (response) {
                if (response.responseText == "") {
                  $("#autocomplete").remove();
                }
              },
            });
          }, doneTypingInterval);
        } else {
          $("#autocomplete").remove();
          $(".sm-serachbox-pro").hide();
        }
      }
    }
  });

  // track order popup
  $(".track-order-btn").click(function () {
    $(".track-order-modal").modal("show").css({
      width: "auto",
      height: "auto",
    });
  });

  const notify = () => { };

  document.addEventListener("DOMContentLoaded", function () {
    Fancybox.bind('[data-fancybox="gallery"]', {
      Toolbar: {
        display: ["zoom", "close"],
      },
      Thumbs: {
        autoStart: true,
      },
    });
  });

  function quantityInputs() {
    e.fn.TouchSpin &&
      (e(".vertical-quantity").TouchSpin({
        verticalbuttons: !0,
        verticalup: "",
        verticaldown: "",
        verticalupclass: "icon-up-dir",
        verticaldownclass: "icon-down-dir",
        buttondown_class: "btn btn-outline",
        buttonup_class: "btn btn-outline",
        initval: 1,
        min: 1,
      }),
        e(".horizontal-quantity").TouchSpin({
          verticalbuttons: !1,
          buttonup_txt: "",
          buttondown_txt: "",
          buttondown_class: "btn btn-outline btn-down-icon",
          buttonup_class: "btn btn-outline btn-up-icon",
          initval: 1,
          min: 1,
        }));
  }

  const pageHeader = document.querySelector(".page-header");
  const openMobMenu = document.querySelector(".custom-open-mobile-menu");
  const closeMobMenu = document.querySelector(".custom-close-mobile-menu");
  const topMenuWrapper = document.querySelector(".custom-top-menu-wrapper");
  const showOffCanvas = "show-offcanvas";
  const noTransition = "no-transition";
  let resize;

  // Opening Mobile Menu
  openMobMenu.addEventListener("click", () => {
    topMenuWrapper.classList.add(showOffCanvas);
  });

  // Closing Mobile Menu
  closeMobMenu.addEventListener("click", () => {
    topMenuWrapper.classList.remove(showOffCanvas);
  });

  // Resizing Screen
  window.addEventListener("resize", () => {
    if(pageHeader){
      pageHeader.querySelectorAll("*").forEach(function (el) {
        el.classList.add(noTransition);
      });
      clearTimeout(resize);
      resize = setTimeout(resizingComplete, 300);
    }
  });

  function resizingComplete() {
    pageHeader.querySelectorAll("*").forEach(function (el) {
      el.classList.remove(noTransition);
    });
  }

  document.querySelectorAll(".custom-dropdown-submenu > a").forEach((menu) => {
    menu.addEventListener("click", (e) => {
      let submenu = menu.nextElementSibling;
      let icon = menu.querySelector("i");
      let allSubmenus = document.querySelectorAll(".custom-secChild");
      let allIcons = document.querySelectorAll(".custom-dropdown-submenu > a i");

      if (submenu && submenu.classList.contains("custom-secChild")) {
        e.preventDefault();

        allSubmenus.forEach((sub) => {
          if (sub !== submenu) {
            sub.style.display = "none";
          }
        });

        allIcons.forEach((icn) => {
          if (icn !== icon) {
            icn.classList.remove("fa-chevron-down");
            icn.classList.add("fa-chevron-right");
          }
        });

        let isVisible = submenu.style.display === "block";
        submenu.style.display = isVisible ? "none" : "block";

        if (icon) {
          icon.classList.toggle("fa-chevron-right", isVisible);
          icon.classList.toggle("fa-chevron-down", !isVisible);
        }
      }
    });
  });

  const sidebar = document.querySelector(".mobile-sidebar-main-wrapper");
  const openBtn = document.querySelector(".filter-toggle-btn");
  const closeBtn = document.querySelector(".close-sidebar");
  const overlay = document.querySelector(".mobile-sidebar-main-wrapper-overlay");

  if (sidebar && openBtn && closeBtn) {
    function openSidebar() {
      sidebar.classList.add("active");
      overlay.classList.add("active");
    }

    function closeSidebar() {
      sidebar.classList.remove("active");
      overlay.classList.remove("active");
    }

    openBtn.addEventListener("click", openSidebar);
    closeBtn.addEventListener("click", closeSidebar);
    overlay.addEventListener("click", closeSidebar);
  }




  $(".request-a-quote-btn").click(function () {
    $('.request-a-quote-modal').modal().css({
      width: 'auto',
      height: 'auto',
    });
  });
  $(".track-order-btn").click(function () {
    $('.track-order-modal').modal().css({
      width: 'auto',
      height: 'auto',
    });
  });


  //sticky header
  $(window).scroll(function () {

    if ($(this).scrollTop() > 500) {
      $("header.header").addClass("fixed-header");
    } else {
      $("header.header").removeClass("fixed-header");
    }
  });

});

const qtyInput = document.querySelector(".productQty");
const incrementBtn = document.querySelector(".btn-plus");
const decrementBtn = document.querySelector(".btn-minus");

if (qtyInput) {
  console.log(qtyInput)
  document.addEventListener("DOMContentLoaded", function () {
    incrementBtn.addEventListener("click", function () {
      let currentValue = parseInt(qtyInput.value, 10) || 0;
      qtyInput.value = currentValue + 1;
    });

    decrementBtn.addEventListener("click", function () {
      let currentValue = parseInt(qtyInput.value, 10) || 0;
      if (currentValue > 1) {
        qtyInput.value = currentValue - 1;
      }
    });
  });
}