import React, { useEffect, useRef } from "react";
import { motion, useScroll, useTransform } from "framer-motion";

/**
 * HeroVideoBackground
 * - Video de fondo a pantalla parcial/entera (configurable) SIN poster.
 * - Reproduce en loop y reintenta si el navegador lo pausa (cambio de pestaña, etc.).
 * - Agrega overlay (no imagen) para contraste.
 *
 * Props:
 *  - src: string (requerido) -> usa import de Vite: import video from "@/assets/video/..mp4"
 *  - minHeight: string (default "75vh") -> Tailwind arbitrary value p.ej. "min-h-[75vh]"
 *  - overlayClass: string (default "bg-slate-900/45") -> controla contraste
 *  - className: string -> clases extra del <section>
 *  - children: contenido del hero (texto, botones, etc.)
 */
export default function HeroVideoBackground({
  src,
  minHeight = "min-h-[75vh]",
  overlayClass = "bg-slate-900/45",
  className = "",
  children,
}) {
  const videoRef = useRef(null);
  const { scrollYProgress } = useScroll();
  const bgScale = useTransform(scrollYProgress, [0, 0.2], [1.02, 1]);
  const bgOpacity = useTransform(scrollYProgress, [0, 0.2], [1, 0.95]);

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

    const tryPlay = () => {
      const p = v.play?.();
      if (p && typeof p.then === "function") p.catch(() => {});
    };

    // Intentos iniciales
    tryPlay();

    // Reanudar cuando la pestaña vuelve a ser visible
    const onVisibility = () => {
      if (document.visibilityState === "visible") tryPlay();
    };

    // Reintentos ante eventos frecuentes
    const onPause = () => tryPlay();
    const onLoadedData = () => tryPlay();

    document.addEventListener("visibilitychange", onVisibility);
    v.addEventListener("pause", onPause);
    v.addEventListener("loadeddata", onLoadedData);

    return () => {
      document.removeEventListener("visibilitychange", onVisibility);
      v.removeEventListener("pause", onPause);
      v.removeEventListener("loadeddata", onLoadedData);
    };
  }, []);

  return (
    <section className={`relative overflow-hidden ${minHeight} ${className}`}>
      {/* Capa de video */}
      <div className="absolute inset-0 z-0">
        <motion.div style={{ scale: bgScale, opacity: bgOpacity }} className="absolute inset-0" aria-hidden="true">
          <video
            ref={videoRef}
            className="h-full w-full object-cover"
            autoPlay
            muted
            loop
            playsInline
            controls={false}
            disablePictureInPicture
            preload="auto"
          >
            <source src={src} type="video/mp4" />
          </video>
        </motion.div>
      </div>

      {/* Overlay (no imagen), ajustable por props */}
      <div className={`absolute inset-0 z-10 ${overlayClass}`} />

      {/* Slot de contenido */}
      <div className="relative z-20">{children}</div>
    </section>
  );
}
