// Bunny Stream embed — wraps the player iframe in a 16:9 responsive container
// matching the existing .vp visual treatment (border, radius).
//
// Required props:
//   libraryId — Bunny Library ID (number, e.g. 655495)
//   videoId   — Video GUID (string)
//
// Optional:
//   autoplay   — start muted-autoplay (default false; recommended false for VSL)
//   loop       — loop video (default false)
//   muted      — start muted (default false)
//   onProgress — receives % watched (0-100), polled every 1s

function BunnyPlayer({
  libraryId,
  videoId,
  autoplay = false,
  loop = false,
  muted = false,
  onProgress = null,
  large = true,
}) {
  const iframeRef = React.useRef(null);

  // Bunny embed URL (player.mediadelivery.net is the global player domain)
  const params = new URLSearchParams({
    autoplay: autoplay ? "true" : "false",
    loop: loop ? "true" : "false",
    muted: muted ? "true" : "false",
    preload: "true",
    responsive: "true",
  });
  const src = `https://iframe.mediadelivery.net/embed/${libraryId}/${videoId}?${params.toString()}`;

  // Bunny posts {event, time} messages for play/pause/ended/timeupdate when
  // the embed has Player API enabled (default for new libraries).
  React.useEffect(() => {
    if (!onProgress) return;
    const onMsg = (e) => {
      try {
        const data = typeof e.data === "string" ? JSON.parse(e.data) : e.data;
        if (data && data.eventName === "play" || data?.event === "play") return;
        if (data && (data.eventName === "timeupdate" || data.event === "timeupdate")) {
          const pct = (data.currentTime / data.duration) * 100;
          if (isFinite(pct)) onProgress(pct);
        }
      } catch (_) {}
    };
    window.addEventListener("message", onMsg);
    return () => window.removeEventListener("message", onMsg);
  }, [onProgress]);

  return (
    <div className={`vp vp-bunny ${large ? "vp--large" : ""}`}>
      <iframe
        ref={iframeRef}
        src={src}
        loading="lazy"
        allow="accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture;"
        allowFullScreen
        title="Cashy VSL"
      />
    </div>
  );
}

window.BunnyPlayer = BunnyPlayer;
