// Vono — testimonial marquee: seamless infinite loop + pause on hover.
// With few cards the single set can be narrower than the viewport, which would
// leave a blank gap at the end. So we repeat the set until it comfortably fills
// the viewport, then duplicate the whole thing once for a seamless -50% loop.
export function initTestimonials() {
  const viewport = document.querySelector('.testimonials__viewport');
  const track = document.querySelector('.testimonials__track');
  if (!viewport || !track || track.dataset.init) return;
  track.dataset.init = '1';

  const originals = Array.from(track.children);
  if (!originals.length) return;

  // 1) Repeat the original set until it is at least ~1.5x the viewport width.
  const target = Math.max(viewport.offsetWidth * 1.5, 1);
  let guard = 0;
  while (track.scrollWidth < target && guard < 30) {
    originals.forEach((el) => track.appendChild(el.cloneNode(true)));
    guard += 1;
  }

  // 2) Duplicate the whole (now viewport-filling) set once more. The CSS
  //    keyframe translates the track by -50%, i.e. exactly one filled set,
  //    so the loop is seamless with no blank space.
  Array.from(track.children).forEach((el) => {
    const clone = el.cloneNode(true);
    clone.setAttribute('aria-hidden', 'true');
    track.appendChild(clone);
  });

  // Pause on hover / focus.
  const pause = () => { track.style.animationPlayState = 'paused'; };
  const resume = () => { track.style.animationPlayState = 'running'; };
  viewport.addEventListener('mouseenter', pause);
  viewport.addEventListener('mouseleave', resume);
  viewport.addEventListener('focusin', pause);
  viewport.addEventListener('focusout', resume);
}
