document.addEventListener('DOMContentLoaded', function () {

  const wrappers = document.querySelectorAll('.products-row-wrapper.is-slider');

  wrappers.forEach(wrapper => {
    const track = wrapper.querySelector('.products-cards-grid');
    if (!track) return;

    const gap = 20;
    const delay = 3000;
    let timer = null;
    let paused = false;

    function cardStep() {
      const card = track.children[0];
      return card ? card.offsetWidth + gap : 0;
    }

    function next() {
      if (paused) return;

      const step = cardStep();
      if (!step) return;

      track.style.transition = 'transform 0.5s ease-out';
      track.style.transform = `translateX(-${step}px)`;

      setTimeout(() => {
        track.style.transition = 'none';
        track.style.transform = 'translateX(0)';
        track.appendChild(track.firstElementChild);
      }, 520);
    }

    function start() {
      if (!timer) timer = setInterval(next, delay);
    }

    function stop() {
      clearInterval(timer);
      timer = null;
    }

    /* Pause on hover / touch */
    wrapper.addEventListener('mouseenter', () => {
      paused = true;
      stop();
    });

    wrapper.addEventListener('mouseleave', () => {
      paused = false;
      start();
    });

    wrapper.addEventListener('touchstart', () => {
      paused = true;
      stop();
    }, { passive: true });

    wrapper.addEventListener('touchend', () => {
      paused = false;
      start();
    });

    start();
  });

});
