/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
*/

document.addEventListener("DOMContentLoaded", () => {
  const lazyVideos = document.querySelectorAll<HTMLVideoElement>('video[data-src]');

  const options = {
    rootMargin: '0px 0px 200px 0px', // Start loading videos when they are 200px from the viewport
    threshold: 0.01
  };

  if ("IntersectionObserver" in window) {
    const videoObserver = new IntersectionObserver((entries, observer) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          const video = entry.target as HTMLVideoElement;
          const src = video.getAttribute('data-src');
          if (src) {
            // Add an event listener that waits for the video to be ready to play
            video.addEventListener('canplay', () => {
              // Once it's ready, play the video.
              video.play().catch(error => {
                console.error("Video autoplay was prevented for:", src, error);
              });
            }, { once: true }); // { once: true } ensures the listener is removed after firing

            // Set the src and load the video. This will trigger the 'canplay' event once ready.
            video.src = src;
            video.load(); 
            
            video.removeAttribute('data-src'); // Clean up
            videoObserver.unobserve(video); // Stop observing once loaded
          }
        }
      });
    }, options);

    lazyVideos.forEach(video => {
      videoObserver.observe(video);
    });
  } else {
    // Fallback for older browsers without IntersectionObserver
    // Loads all videos immediately
    lazyVideos.forEach(video => {
      const src = video.getAttribute('data-src');
      if (src) {
        video.src = src;
        video.load();
        video.play().catch(error => {
            console.error("Video autoplay was prevented for:", src, error);
        });
        video.removeAttribute('data-src');
      }
    });
  }
});
