"use client";

import { useEffect, useRef } from "react";

interface VideoLightboxProps {
  videoUrl: string;
  poster?: string;
  onClose: () => void;
}

/**
 * Matches the live site's fancybox video popup (`.fancybox-content.videomain`,
 * `templates/GAH/scss/homenew.scss`): a white rounded card on a dimmed
 * backdrop, not a bare `<video>` floating on the overlay. Shared by
 * `HeroBannerCarousel` (the hero banner's video slide) and
 * `CmsVideoLightboxHydrator` (the "Avail the Best" section's four
 * `.videopart` thumbnails, which are raw CMS markup with no React tree of
 * their own to attach a click handler to).
 */
export function VideoLightbox({ videoUrl, poster, onClose }: VideoLightboxProps) {
  const videoRef = useRef<HTMLVideoElement>(null);

  // `autoPlay` alone is unreliable: the <video> mounts after a setState +
  // re-render, often outside the browser's "user activation" window, so some
  // browsers silently block it with no error. Calling `.play()` explicitly
  // and swallowing a rejection avoids a video that looks permanently stuck.
  useEffect(() => {
    videoRef.current?.play().catch(() => {
      // Autoplay blocked — controls are still visible, user can press play.
    });
  }, [videoUrl]);

  return (
    <div
      className="fixed inset-0 z-[999] flex items-center justify-center bg-black/80 p-4"
      onClick={onClose}
    >
      <div
        className="relative w-full max-w-3xl rounded-[6px] bg-white p-[5px] shadow-xl"
        onClick={(e) => e.stopPropagation()}
      >
        <button
          type="button"
          aria-label="Close video"
          onClick={onClose}
          className="absolute top-2 right-2 z-10 flex h-9 w-9 items-center justify-center rounded-full bg-white text-2xl leading-none text-[#2a2a2a] shadow-md hover:bg-slate-100 transition-colors"
        >
          ×
        </button>
        <video
          ref={videoRef}
          key={videoUrl}
          src={videoUrl}
          poster={poster}
          controls
          controlsList="nodownload"
          autoPlay
          playsInline
          className="block w-full rounded-[4px] bg-black"
        >
          Your browser does not support HTML video.
        </video>
      </div>
    </div>
  );
}
