"use client";

import { useEffect, useRef, useState } from "react";

type AmbientVideoProps = {
  src: string;
  poster: string;
  className?: string;
  priority?: boolean;
};

export function AmbientVideo({ src, poster, className = "", priority = false }: AmbientVideoProps) {
  const wrapperRef = useRef<HTMLDivElement>(null);
  const videoRef = useRef<HTMLVideoElement>(null);
  const [enabled, setEnabled] = useState(priority);

  useEffect(() => {
    if (priority || !wrapperRef.current) return;
    const observer = new IntersectionObserver(
      ([entry]) => setEnabled(entry.isIntersecting),
      { rootMargin: "320px 0px", threshold: 0.01 }
    );
    observer.observe(wrapperRef.current);
    return () => observer.disconnect();
  }, [priority]);

  useEffect(() => {
    const video = videoRef.current;
    if (!video) return;
    if (enabled) void video.play().catch(() => undefined);
    else video.pause();
  }, [enabled]);

  return (
    <div ref={wrapperRef} className={`ambient-video ${className}`}>
      <video ref={videoRef} muted loop playsInline autoPlay={priority} preload={priority ? "metadata" : "none"} poster={poster} aria-hidden="true">
        {enabled && <source src={src} type="video/mp4" />}
      </video>
    </div>
  );
}
