/**
 * @param $scope The Widget wrapper element as a jQuery element
 * @param $ The jQuery alias
 */

// Function to initialize product carousel
function initProductCarousel($scope) {
      /* Product Carousel Swiper Initialization */
      var $productSlideWrap = $scope.find(".unlockafe-product-slide-wrap");
      
      if ($productSlideWrap.length === 0) {
        return; // Exit if no product slide wrap found
      }

      var productCount = $productSlideWrap.data("product-count") || 4;
      var $swiperContainer = $scope.find(".unlockafe-product-slide");
      var $nextButton = $scope.find(".unlockafe-product-button-next");
      var $prevButton = $scope.find(".unlockafe-product-button-prev");
      var $pagination = $scope.find(".unlockafe-pagination");

      // Ensure buttons are visible
      if ($nextButton.length > 0) {
        $nextButton.css({
          'display': 'grid',
          'visibility': 'visible',
          'opacity': '1'
        });
      }
      if ($prevButton.length > 0) {
        $prevButton.css({
          'display': 'grid',
          'visibility': 'visible',
          'opacity': '1'
        });
      }

      if ($swiperContainer.length > 0) {
        // Wait for DOM to be fully ready
        setTimeout(function() {
          // Check if Swiper is already initialized
          if ($swiperContainer[0].swiper) {
            $swiperContainer[0].swiper.destroy(true, true);
          }

          // Ensure productCount is a valid number
          productCount = parseInt(productCount) || 4;
          if (productCount < 1) productCount = 1;
          if (productCount > 4) productCount = 4;

          var swiperConfig = {
            spaceBetween: 24,
            loop: false,
            watchOverflow: true,
            observer: true,
            observeParents: true,
            slidesPerView: 1,
            slidesPerGroup: 1, // Slide one product at a time
            speed: 600, // Smooth transition speed
            effect: 'slide', // Slide effect
            grabCursor: true, // Show grab cursor
            breakpoints: {
              320: {
                slidesPerView: 1,
                slidesPerGroup: 1,
              },
              480: {
                slidesPerView: 1,
                slidesPerGroup: 1,
              },
              768: {
                slidesPerView: Math.min(productCount, 2),
                slidesPerGroup: 1,
              },
              992: {
                slidesPerView: Math.min(productCount, 3),
                slidesPerGroup: 1,
              },
              1200: {
                slidesPerView: Math.min(productCount, 4),
                slidesPerGroup: 1,
              },
            },
          };

          // Add navigation if buttons exist
          if ($nextButton.length > 0 && $prevButton.length > 0) {
            swiperConfig.navigation = {
              nextEl: $nextButton[0],
              prevEl: $prevButton[0],
            };
          }

          // Add pagination if it exists
          if ($pagination.length > 0) {
            swiperConfig.pagination = {
              el: $pagination[0],
              clickable: true,
              type: 'bullets',
            };
          }

          // Initialize Swiper
          try {
            var swiper = new Swiper($swiperContainer[0], swiperConfig);
            
            // Force update after initialization
            swiper.update();
            swiper.updateSlides();
            swiper.updateSlidesClasses();
            
            // Add fade-in animation to slides
            swiper.on('slideChangeTransitionStart', function () {
              var activeSlide = $swiperContainer.find('.swiper-slide-active');
              activeSlide.css({
                'animation': 'fadeInUp 0.5s ease-out'
              });
            });
            
            // Update navigation button states on slide change
            swiper.on('slideChange', function () {
              swiper.update();
              
              // Add pulse effect to active slide
              $swiperContainer.find('.swiper-slide').removeClass('slide-active-pulse');
              $swiperContainer.find('.swiper-slide-active').addClass('slide-active-pulse');
            });

            // Add touch/swipe feedback
            swiper.on('touchStart', function () {
              $swiperContainer.addClass('swiper-touching');
            });
            
            swiper.on('touchEnd', function () {
              setTimeout(function() {
                $swiperContainer.removeClass('swiper-touching');
              }, 300);
            });

            // Update on window resize
            $(window).on('resize', function() {
              if (swiper) {
                swiper.update();
              }
            });
            
            // Add initial animation to first slide
            setTimeout(function() {
              $swiperContainer.find('.swiper-slide-active').addClass('slide-initial-animate');
            }, 100);
          } catch (error) {
            console.error('Swiper initialization error:', error);
          }
        }, 100);
      }

      /* Team Slide - Keep for backward compatibility */
      var $teamSlide = $scope.find(".unlockafe-team-slide");
      if ($teamSlide.length > 0) {
        var $teamNextButton = $scope.find(".unlockafe-team-button-next");
        var $teamPrevButton = $scope.find(".unlockafe-team-button-prev");
        var $teamPagination = $scope.find(".unlockafe-pagination");

        // Check if Swiper is already initialized
        if ($teamSlide[0].swiper) {
          $teamSlide[0].swiper.destroy(true, true);
        }

        var teamSwiperConfig = {
          spaceBetween: 24,
          loop: false,
          slidesPerView: 1,
          slidesPerGroup: 1,
          breakpoints: {
            320: {
              slidesPerView: 1,
              slidesPerGroup: 1,
            },
            480: {
              slidesPerView: 1,
              slidesPerGroup: 1,
            },
            768: {
              slidesPerView: Math.min(productCount, 2),
              slidesPerGroup: 1,
            },
            992: {
              slidesPerView: Math.min(productCount, 3),
              slidesPerGroup: 1,
            },
            1200: {
              slidesPerView: Math.min(productCount, 4),
              slidesPerGroup: 1,
            },
          },
        };

        if ($teamNextButton.length > 0 && $teamPrevButton.length > 0) {
          teamSwiperConfig.navigation = {
            nextEl: $teamNextButton[0],
            prevEl: $teamPrevButton[0],
          };
        }

        if ($teamPagination.length > 0) {
          teamSwiperConfig.pagination = {
            el: $teamPagination[0],
            clickable: true,
            type: 'bullets',
          };
        }

        try {
          var teamSlider = new Swiper($teamSlide[0], teamSwiperConfig);
        } catch (error) {
          console.error('Team Swiper initialization error:', error);
        }
      }
}

// Initialize on Elementor frontend
$(window).on("elementor/frontend/init", function () {
  elementorFrontend.hooks.addAction(
    "frontend/element_ready/unlockafe-product-carousel.default",
    function ($scope) {
      initProductCarousel($scope);
    }
  );
});

// Also initialize on document ready (for non-Elementor pages or after page load)
$(document).ready(function() {
  if (typeof Swiper !== 'undefined') {
    $('.unlockafe-product-slide-wrap').each(function() {
      var $scope = $(this).closest('.elementor-widget-unlockafe-product-carousel');
      if ($scope.length > 0) {
        initProductCarousel($scope);
      }
    });
  }
});
