(function ($) {
  "use strict";

  /**
   * shop-details.html / slider-one: .swiper.shop-slider inside .wco-container with .array-button + .dot
   */
  function wcpInitShopSlidersInScope($scope) {
    if (typeof Swiper === "undefined") {
      return;
    }
    $scope.find(".shop-slider").each(function () {
      var el = this;
      if (el.swiper) {
        return;
      }
      var data = el.getAttribute("data-slider-settings");
      var opts = data ? JSON.parse(data) : {};
      var spaceBetween = typeof opts.margin !== "undefined" ? opts.margin : 30;
      var speed =
        typeof opts.smart_speed !== "undefined" ? opts.smart_speed : 700;
      var loop = typeof opts.loop !== "undefined" ? opts.loop : true;
      var items = typeof opts.items !== "undefined" ? opts.items : 3;
      var $wrap = $(el).closest(".wco-container");
      var slideCount = $(el).find("> .swiper-wrapper > .swiper-slide").length;
      var isRelated =
        el.classList && el.classList.contains("szp-related-shop-slider");
      // Other shop sliders: cap so at least one slide stays off-screen (next/prev stay usable).
      // Related products (.szp-related-shop-slider): show up to 4 per row (Storzen); use min(requested, slideCount), no forced hidden slide.
      var capPerView = function (requested) {
        if (slideCount <= 1) {
          return 1;
        }
        if (isRelated) {
          return Math.min(requested, slideCount);
        }
        return Math.min(requested, Math.max(1, slideCount - 1));
      };
      // Swiper 8 loop + few slides duplicates DOM and often breaks card height / pink hover overlay; use linear mode instead.
      var useLoop = !!(loop && slideCount >= 6);
      var swiperOpts = {
        spaceBetween: spaceBetween,
        speed: speed,
        loop: useLoop,
        /* Related: keep arrows/dots visible even when 4/4 slides fit (otherwise Swiper hides nav). */
        watchOverflow: !isRelated,
        breakpoints: {
          1199: { slidesPerView: capPerView(Math.min(4, items)) },
          991: { slidesPerView: capPerView(Math.min(3, items)) },
          767: { slidesPerView: capPerView(Math.min(2, items)) },
          575: { slidesPerView: capPerView(1) },
          0: { slidesPerView: capPerView(1) },
        },
      };
      if (useLoop && opts.loop) {
        swiperOpts.autoplay = {
          delay: 2000,
          disableOnInteraction: false,
        };
      }
      if (opts.enable_nav) {
        swiperOpts.navigation = {
          nextEl: $wrap.find(".array-next")[0],
          prevEl: $wrap.find(".array-prev")[0],
        };
      }
      if (opts.enable_dots) {
        var dotEl = $(el).find(".dot")[0];
        if (dotEl) {
          swiperOpts.pagination = {
            el: dotEl,
            clickable: true,
          };
        }
      }
      new Swiper(el, swiperOpts);
    });
  }

  /**
   * shop-details.html: .preview-images + .thumb-images (Swiper + thumbs)
   */
  function wcpInitProductGallery($scope) {
    var $root = $scope && $scope.length ? $scope : $("body");

    /* shop-details-2 / shop-details-3: tab panes + vertical thumbs (.thumb-images-two or .thumb-images-three). */
    $root
      .find(".szp-pd-gallery-layout-two, .szp-pd-gallery-layout-three")
      .each(function () {
      var wrap = this;
      var $wrap = $(wrap);
      if ($wrap.data("wcpGalleryThumbTabsInit")) {
        return;
      }
      $wrap.data("wcpGalleryThumbTabsInit", true);
      var thumbs = wrap.querySelectorAll(
        ".thumb-images-two .thumb-item, .thumb-images-three .thumb-item",
      );
      var previews = wrap.querySelectorAll(".preview-images-two .preview-item");
      thumbs.forEach(function (thumb) {
        thumb.addEventListener("click", function (e) {
          e.preventDefault();
          var target = thumb.getAttribute("data-img");
          if (!target) {
            return;
          }
          thumbs.forEach(function (t) {
            t.classList.remove("active");
          });
          thumb.classList.add("active");
          previews.forEach(function (p) {
            p.classList.remove("active", "show");
          });
          var pane = document.getElementById(target);
          if (pane) {
            pane.classList.add("active", "show");
          }
        });
      });
    });

    if (typeof Swiper === "undefined") {
      return;
    }
    $root.find(".szp-pd-gallery-root").each(function () {
      var $g = $(this);
      if ($g.data("wcpGalleryInit")) {
        return;
      }
      var mainEl = $g.find(".szp-preview-swiper")[0];
      var thumbEl = $g.find(".szp-thumb-swiper")[0];
      if (!mainEl || !thumbEl) {
        return;
      }
      $g.data("wcpGalleryInit", true);
      var thumbSwiper = new Swiper(thumbEl, {
        spaceBetween: 10,
        slidesPerView: 4,
        freeMode: true,
        watchSlidesProgress: true,
        breakpoints: {
          0: { slidesPerView: 3 },
          576: { slidesPerView: 4 },
        },
      });
      new Swiper(mainEl, {
        spaceBetween: 0,
        loop: false,
        thumbs: { swiper: thumbSwiper },
      });
    });
  }

  var WcommeroSlider = function ($scope) {
    wcpInitShopSlidersInScope($scope);

    if ($scope.find(".shop-slider2").length > 0) {
      var $el2 = $scope.find(".shop-slider2")[0];
      var data2 = $el2.getAttribute("data-slider-settings");
      var opts2 = data2 ? JSON.parse(data2) : {};
      var spaceBetween2 =
        typeof opts2.margin !== "undefined" ? opts2.margin : 30;
      var speed2 =
        typeof opts2.smart_speed !== "undefined" ? opts2.smart_speed : 700;
      var loop2 = typeof opts2.loop !== "undefined" ? opts2.loop : true;
      var swiperOpts2 = {
        effect: "coverflow",
        spaceBetween: spaceBetween2,
        speed: speed2,
        centeredSlides: true,
        loop: loop2,
        coverflowEffect: {
          rotate: 30,
          stretch: 0,
          depth: 60,
          modifier: 1,
          slideShadows: false,
          scale: 1,
        },
        breakpoints: {
          1399: {
            slidesPerView: 3,
            spaceBetween: Math.min(60, spaceBetween2 * 2),
          },
          1199: { slidesPerView: 3, spaceBetween: spaceBetween2 },
          991: { slidesPerView: 2, spaceBetween: spaceBetween2 },
          767: { slidesPerView: 2, spaceBetween: spaceBetween2 },
          575: { slidesPerView: 1, spaceBetween: spaceBetween2 },
          0: { slidesPerView: 1 },
        },
      };
      if (opts2.loop) {
        swiperOpts2.autoplay = {
          delay: 2000,
          disableOnInteraction: false,
        };
      }
      if (opts2.enable_nav) {
        swiperOpts2.navigation = {
          nextEl: $scope.find(".array-prev")[0] || ".array-prev",
          prevEl: $scope.find(".array-next")[0] || ".array-next",
        };
      }
      if (opts2.enable_dots) {
        swiperOpts2.pagination = {
          el: $scope.find(".dot")[0] || ".dot",
          clickable: true,
        };
      }
      new Swiper($el2, swiperOpts2);
    }
  };

  var WcommeroTab = function ($scope) {
    // Custom Tab
    if ($scope.find(".custom-tabs").length) {
      $scope.find(".custom-tabs").each(function () {
        const $tabWrap = $(this);
        const $tabBtn = $tabWrap.find(".tab-btn");
        const $tabContent = $tabWrap.find(".tab");

        $tabBtn.on("click", function () {
          const tab_id = $(this).data("tab");

          $tabBtn.removeClass("active");
          $(this).addClass("active");

          $tabContent.removeClass("active");
          $("#" + tab_id).addClass("active");
        });
      });
    }
  };

  /**
   * shop-details.html: .product-description-tab .nav-link[data-tab] + .tab-pane#id
   */
  /**
   * Storzen-style − / + buttons for WooCommerce .qty inside the product Add to Cart widget.
   */
  function wcpInitProductQtyStepper($scope) {
    var $root = $scope && $scope.length ? $scope : $("body");
    $root
      .find(".szp-wc-add-to-cart .szp-qty-down, .szp-wc-add-to-cart .szp-qty-up")
      .off("click.wcpQty")
      .on("click.wcpQty", function (e) {
        e.preventDefault();
        var $btn = $(this);
        var $wrap = $btn.closest(".quantity");
        var $input = $wrap.find("input.qty");
        if (!$input.length) {
          return;
        }
        var step = parseFloat($input.attr("step"));
        if (isNaN(step) || step <= 0) {
          step = 1;
        }
        var min = parseFloat($input.attr("min"));
        if (isNaN(min)) {
          min = 0;
        }
        var maxRaw = $input.attr("max");
        var max = maxRaw !== undefined && maxRaw !== "" ? parseFloat(maxRaw) : NaN;
        var val = parseFloat($input.val());
        if (isNaN(val)) {
          val = min;
        }
        if ($btn.hasClass("szp-qty-down")) {
          val = Math.max(min, val - step);
        } else {
          val = val + step;
          if (!isNaN(max) && max > 0) {
            val = Math.min(max, val);
          }
        }
        $input.val(val).trigger("change");
      });
  }

  function wcpInitProductDetailTabs($scope) {
    var $root = $scope && $scope.length ? $scope : $("body");
    $root.find(".szp-product-description-tab .nav.custom-tabs").each(function () {
      var $nav = $(this);
      if ($nav.data("wcpPdTabsInit")) {
        return;
      }
      $nav.data("wcpPdTabsInit", true);
      var $wrap = $nav.closest(".szp-product-description-tab");
      $nav.find(".nav-link").on("click", function (e) {
        e.preventDefault();
        var tabId = $(this).data("tab");
        if (!tabId) {
          return;
        }
        $nav.find(".nav-link").removeClass("active").attr("aria-selected", "false");
        $(this).addClass("active").attr("aria-selected", "true");
        $wrap.find(".tab-pane").removeClass("show active");
        $wrap.find("#" + tabId).addClass("show active");
      });
    });
  }

  /**
   * Mini cart drawer (toggle + overlay + panel).
   */
  function wcpInitMiniCartDrawer($scope) {
    var $root = $scope && $scope.length ? $scope : $("body");
    $root.find("[data-szp-mini-cart]").each(function () {
      var $wrap = $(this);
      if ($wrap.data("wcpMiniCartInit")) {
        return;
      }
      $wrap.data("wcpMiniCartInit", true);
      var $panel = $wrap.find(".szp-mini-cart-panel");
      var $ovl = $wrap.find(".szp-mini-cart-overlay");
      var $toggle = $wrap.find(".szp-mini-cart-toggle");
      var $close = $wrap.find(".szp-mini-cart-close");

      function openDrawer() {
        $panel.removeAttr("hidden").addClass("is-open");
        $ovl.addClass("is-open");
        $toggle.attr("aria-expanded", "true");
        $("body").addClass("szp-mini-cart-open");
      }

      function closeDrawer() {
        $panel.removeClass("is-open").attr("hidden", "hidden");
        $ovl.removeClass("is-open");
        $toggle.attr("aria-expanded", "false");
        $("body").removeClass("szp-mini-cart-open");
      }

      $toggle.on("click", function (e) {
        e.preventDefault();
        if ($panel.hasClass("is-open")) {
          closeDrawer();
        } else {
          openDrawer();
        }
      });
      $close.on("click", function (e) {
        e.preventDefault();
        closeDrawer();
      });
      $ovl.on("click", function () {
        closeDrawer();
      });
      $(document).on("keydown.wcpMiniCart", function (e) {
        if (e.keyCode === 27 && $panel.hasClass("is-open")) {
          closeDrawer();
        }
      });
    });
  }

  /**
   * After add-to-cart redirect, WooCommerce stores notices in session — but Elementor product
   * templates often never call woocommerce_output_all_notices(). The Add to Cart widget now
   * prints them; scroll into view so the message is not missed below the header/fold.
   */
  function wcpScrollToAddToCartNotices() {
    var $wrap = $(".szp-product-add-to-cart .woocommerce-notices-wrapper");
    if (!$wrap.length) {
      return;
    }
    if (
      !$wrap.find(
        ".woocommerce-message, .woocommerce-error, .woocommerce-info",
      ).length
    ) {
      return;
    }
    if ($wrap[0] && typeof $wrap[0].scrollIntoView === "function") {
      $wrap[0].scrollIntoView({ behavior: "smooth", block: "nearest" });
    }
  }

  $(function () {
    wcpInitProductDetailTabs($("body"));
    wcpInitShopSlidersInScope($("body"));
    wcpInitProductGallery($("body"));
    wcpInitProductQtyStepper($("body"));
    wcpInitMiniCartDrawer($("body"));
    wcpScrollToAddToCartNotices();
  });

  $(window).on("elementor/frontend/init", function () {
    if (
      typeof window.elementorFrontend === "undefined" ||
      !window.elementorFrontend.hooks
    ) {
      return;
    }
    window.elementorFrontend.hooks.addAction(
      "frontend/element_ready/storzen-slider.default",
      WcommeroSlider,
    );

    window.elementorFrontend.hooks.addAction(
      "frontend/element_ready/storzen-tab.default",
      WcommeroTab,
    );

    window.elementorFrontend.hooks.addAction(
      "frontend/element_ready/storzen-product-tabs.default",
      wcpInitProductDetailTabs,
    );

    window.elementorFrontend.hooks.addAction(
      "frontend/element_ready/storzen-product-related.default",
      function ($scope) {
        wcpInitShopSlidersInScope($scope);
      },
    );

    window.elementorFrontend.hooks.addAction(
      "frontend/element_ready/storzen-product-gallery.default",
      function ($scope) {
        wcpInitProductGallery($scope);
      },
    );

    window.elementorFrontend.hooks.addAction(
      "frontend/element_ready/storzen-product-add-to-cart.default",
      function ($scope) {
        wcpInitProductQtyStepper($scope);
      },
    );

    window.elementorFrontend.hooks.addAction(
      "frontend/element_ready/storzen-mini-cart-drawer.default",
      function ($scope) {
        wcpInitMiniCartDrawer($scope);
      },
    );
  });
})(jQuery);
