document.addEventListener('DOMContentLoaded', () => {
  const iframes = document.querySelectorAll('.video__vimeo-video-wrapper iframe[src*="player.vimeo.com"]');

  const players = new Map();

  // Create Vimeo Player instances
  iframes.forEach((iframe) => {
    players.set(iframe, new Vimeo.Player(iframe));
  });

  const observer = new IntersectionObserver(
    (entries) => {
      entries.forEach(async (entry) => {
        const player = players.get(entry.target);
        if (!player) return;

        if (entry.isIntersecting) {
          // Bottom has entered the viewport (or any part is visible)
          player.play();
        }
        else {
          // Top or bottom has left the viewport
          player.pause();
        }
      });
    },
    {
      root: null,
      threshold: 1,
    }
  );

  iframes.forEach((iframe) => observer.observe(iframe));
});
