"use client";

import { useEffect, useRef } from "react";

interface BackgroundVideoProps extends React.VideoHTMLAttributes<HTMLVideoElement> {
  src: string;
  playbackRate?: number;
  visibilityThreshold?: number;
}

export default function BackgroundVideo({
  src,
  playbackRate = 0.45,
  visibilityThreshold = 0.4,
  className = "",
  style,
  ...props
}: BackgroundVideoProps) {
  const videoRef = useRef<HTMLVideoElement>(null);

  useEffect(() => {
    const video = videoRef.current;
    if (!video) return;

    // Apply slow ambient playback rate (45% default speed)
    video.playbackRate = playbackRate;

    // IntersectionObserver: Auto-pause when 60% or more out of view (visibility < 40%)
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.intersectionRatio >= visibilityThreshold) {
          video.play().catch(() => {
            // Autoplay safety handling
          });
        } else {
          video.pause();
        }
      },
      { threshold: [0, visibilityThreshold, 1.0] }
    );

    observer.observe(video);

    return () => {
      observer.disconnect();
    };
  }, [playbackRate, visibilityThreshold]);

  const handleLoadedData = (e: React.SyntheticEvent<HTMLVideoElement>) => {
    e.currentTarget.playbackRate = playbackRate;
    if (props.onLoadedData) {
      props.onLoadedData(e);
    }
  };

  return (
    <video
      ref={videoRef}
      src={src}
      autoPlay
      loop
      muted
      playsInline
      onLoadedData={handleLoadedData}
      className={`w-full h-full object-cover opacity-85 transition-opacity duration-700 pointer-events-none mix-blend-multiply ${className}`}
      style={{ mixBlendMode: "multiply", ...style }}
      {...props}
    />
  );
}
