// Shared video preview with autoplay retry and optional codec fallback.

const VideoPreview = ({
  src,
  fallbackSrc,
  poster,
  title,
  label = "DEMO",
  fallbackIcon = "play",
  aspectRatio = 9 / 16,
  className = "",
  showLabel = true,
}) => {
  const [failed, setFailed] = React.useState(!src);
  const [activeSrc, setActiveSrc] = React.useState(src);
  const [naturalRatio, setNaturalRatio] = React.useState(null);
  const videoRef = React.useRef(null);

  React.useEffect(() => {
    setActiveSrc(src);
    setFailed(!src);
    setNaturalRatio(null);
  }, [src]);

  const tryPlay = React.useCallback(() => {
    const video = videoRef.current;
    if (!video || failed || !activeSrc) return;

    video.muted = true;
    video.playsInline = true;

    const playPromise = video.play();
    if (playPromise && typeof playPromise.catch === "function") {
      playPromise.catch(() => {});
    }
  }, [activeSrc, failed]);

  React.useEffect(() => {
    const video = videoRef.current;
    if (!video || failed || !activeSrc) return;

    tryPlay();

    if (typeof IntersectionObserver === "undefined") return;
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) tryPlay();
      });
    }, { threshold: 0.35 });

    observer.observe(video);
    return () => observer.disconnect();
  }, [activeSrc, failed, tryPlay]);

  const handleError = () => {
    if (fallbackSrc && activeSrc !== fallbackSrc) {
      setActiveSrc(fallbackSrc);
      setNaturalRatio(null);
      setFailed(false);
      return;
    }
    setFailed(true);
  };

  const isAuto = aspectRatio === "auto";
  const effectiveRatio = isAuto && naturalRatio ? naturalRatio : (isAuto ? 16 / 9 : aspectRatio);
  const paddingTop = `${(1 / effectiveRatio) * 100}%`;

  return (
    <div className={`vp-wrap ${className}`} style={{ paddingTop }}>
      {!failed && activeSrc ? (
        <video
          key={activeSrc}
          ref={videoRef}
          className="vp-video"
          src={activeSrc}
          poster={poster}
          autoPlay
          muted
          loop
          playsInline
          preload="auto"
          aria-label={title || label}
          title={title || label}
          onError={handleError}
          onLoadedData={tryPlay}
          onCanPlay={tryPlay}
          onLoadedMetadata={(event) => {
            if (isAuto && event.target.videoWidth && event.target.videoHeight) {
              setNaturalRatio(event.target.videoWidth / event.target.videoHeight);
            }
            tryPlay();
          }}
        />
      ) : (
        <VideoPlaceholder icon={fallbackIcon} title={title} />
      )}

      {showLabel && (
        <span className="vp-label" aria-hidden="true">
          <Icon name="play" size={10} />
          {failed || !activeSrc ? "VIDEO PREVIEW" : "LIVE DEMO"}
          {(failed || !activeSrc) && <span className="vp-label-sample">SAMPLE</span>}
        </span>
      )}
    </div>
  );
};

const VideoPlaceholder = ({ icon = "play", title }) => (
  <div className="vp-placeholder" role="img" aria-label={title || "Video preview placeholder"}>
    <div className="vp-ph-grid" aria-hidden="true" />
    <div className="vp-ph-glow" aria-hidden="true" />
    <div className="vp-ph-icon" aria-hidden="true">
      <Icon name={icon} size={44} />
    </div>
  </div>
);

window.VideoPreview = VideoPreview;
