"use client";

import * as React from "react";

/**
 * Looping muted autoplay background video.
 * - Plays automatically (muted, loop, playsInline) for ambient section backgrounds
 * - Shows a poster image while the video loads
 * - Falls back to poster if video fails or on reduced-motion preference
 * - Pauses when offscreen via IntersectionObserver
 */
export function LoopingVideoBackground({
  src,
  poster,
  alt = "",
  className = "",
  overlayClassName = "",
  overlayStyle,
  priority = false,
}: {
  src: string;
  poster?: string;
  alt?: string;
  className?: string;
  overlayClassName?: string;
  overlayStyle?: React.CSSProperties;
  priority?: boolean;
}) {
  const videoRef = React.useRef<HTMLVideoElement>(null);
  const [loaded, setLoaded] = React.useState(false);
  const [failed, setFailed] = React.useState(false);
  const [inView, setInView] = React.useState(false);
  const [reduce, setReduce] = React.useState(false);

  React.useEffect(() => {
    const mq = window.matchMedia("(prefers-reduced-motion: reduce)");
    setReduce(mq.matches);
    const onChange = () => setReduce(mq.matches);
    mq.addEventListener?.("change", onChange);
    return () => mq.removeEventListener?.("change", onChange);
  }, []);

  React.useEffect(() => {
    const el = videoRef.current;
    if (!el) return;
    const obs = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          setInView(e.isIntersecting);
        });
      },
      { rootMargin: "100px" },
    );
    obs.observe(el);
    return () => obs.disconnect();
  }, []);

  React.useEffect(() => {
    const el = videoRef.current;
    if (!el) return;
    if (inView && !reduce) {
      el.play().catch(() => {
        // Autoplay may be blocked; leave the poster visible.
      });
    } else {
      el.pause();
    }
  }, [inView, reduce]);

  return (
    <div className={`absolute inset-0 overflow-hidden ${className}`}>
      {/* Poster image (always rendered as fallback / while loading) */}
      {poster && (
        <img
          src={poster}
          alt={alt}
          className="absolute inset-0 h-full w-full object-cover transition-opacity duration-700"
          style={{ opacity: loaded && !failed && !reduce ? 0 : 1 }}
          aria-hidden="true"
        />
      )}
      {/* Video */}
      {!reduce && !failed && (
        <video
          ref={videoRef}
          src={src}
          poster={poster}
          muted
          loop
          playsInline
          preload={priority ? "auto" : "metadata"}
          onLoadedData={() => setLoaded(true)}
          onError={() => setFailed(true)}
          className="absolute inset-0 h-full w-full object-cover transition-opacity duration-700"
          style={{ opacity: loaded ? 1 : 0 }}
          aria-hidden="true"
        />
      )}
      {/* Overlay grade */}
      <div
        className={`absolute inset-0 ${overlayClassName}`}
        style={overlayStyle}
        aria-hidden="true"
      />
    </div>
  );
}
