/**
 * Amazon Product Slider JS
 *
 * This file moves the Swiper initialization code out of the PHP file and
 * handles all slider logic, including pagination events.
 *
 * It assumes each slider wrapper has an ID (e.g. #amazon-slider-<unique>)
 * and "data-" attributes so we can read the needed info in JavaScript.
 *
 * If your code uses different data attributes or structures, adjust accordingly.
 */

document.addEventListener('DOMContentLoaded', function () {
  const allSliders = document.querySelectorAll('.tsamazon-products-slider-wrapper');

  allSliders.forEach(function (sliderWrapper) {
    const sliderId = sliderWrapper.getAttribute('id') || '';
    if (!sliderId) return;

    const container = sliderWrapper.querySelector('.swiper');
    if (!container) return;

    const prevEl = sliderWrapper.querySelector('.swiper-button-prev-' + sliderId);
    const nextEl = sliderWrapper.querySelector('.swiper-button-next-' + sliderId);

    const paginationContainer = sliderWrapper.querySelector('.slider-pagination');
    const paginationDots = paginationContainer ? paginationContainer.querySelectorAll('.pagination-dot') : [];

    const swiper = new Swiper(container, {
      loop: true,
      spaceBetween: 10,
      navigation: {
        nextEl: nextEl,
        prevEl: prevEl,
      },
      speed: 400,
      slidesPerView: 'auto',
      slidesPerGroup: 1,
      breakpoints: {
        676: { slidesPerView: 'auto' },
        901: { slidesPerView: 'auto' },
        1151: { slidesPerView: 'auto' }
      },
      on: {
        init: function () {
          updateActiveDot(this.realIndex);
        },
        slideChange: function () {
          updateActiveDot(this.realIndex);
        }
      }
    });

    function updateActiveDot(realIndex) {
      paginationDots.forEach(dot => dot.classList.remove('active'));
      const correctedIndex = realIndex % paginationDots.length;
      if (paginationDots[correctedIndex]) {
        paginationDots[correctedIndex].classList.add('active');
      }
    }

    paginationDots.forEach(function (dot, index) {
      dot.addEventListener('click', function () {
        swiper.slideToLoop(index); // jump to corresponding slide
      });
    });
  });
});