document.querySelectorAll(".video-player").forEach((player) => {
  const video = player.querySelector("video");
  const button = player.querySelector(".video-play-button");
  let loaded = false;
  let hls;
  let fallbackUsed = false;
  let fallbackTimer;

  const playVideo = () => {
    player.classList.add("is-playing");
    video.play().catch(() => {});
  };

  const useFallback = () => {
    const fallback = video.dataset.fallbackStream;
    if (!fallback || fallbackUsed) return;
    fallbackUsed = true;
    if (hls) {
      hls.destroy();
      hls = null;
    }
    clearTimeout(fallbackTimer);
    video.src = fallback;
    playVideo();
  };

  const loadAndPlay = () => {
    if (!loaded) {
      const stream = video.dataset.stream;
      if (video.dataset.hls === "true" && window.Hls && Hls.isSupported()) {
        hls = new Hls({ enableWorker: false });
        fallbackTimer = setTimeout(() => {
          if (!video.currentTime && video.readyState < 3) useFallback();
        }, 5000);
        hls.on(Hls.Events.MANIFEST_PARSED, () => {
          clearTimeout(fallbackTimer);
          playVideo();
        });
        hls.on(Hls.Events.ERROR, (event, data) => {
          if (data && data.fatal) useFallback();
        });
        hls.loadSource(stream);
        hls.attachMedia(video);
      } else {
        video.src = stream;
        playVideo();
      }
      loaded = true;
      return;
    }
    playVideo();
  };

  button.addEventListener("click", loadAndPlay);
  video.addEventListener("play", () => player.classList.add("is-playing"));
  video.addEventListener("error", useFallback);
  video.addEventListener("ended", () => player.classList.remove("is-playing"));
});
