Video.js 1.52 KB
import React, { useRef, useEffect, useState } from "react";
import { cleanImage } from "../services/imageHandling";

const Video = ({ productData }) => {
  const videoRef = useRef(null);
  const [isVisible, setIsVisible] = useState(false);

  const media = productData?.video;

  useEffect(() => {
    // ✅ Guard for missing video OR SSR
    if (!media?.url || typeof window === "undefined") return;

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsVisible(true);

          if (videoRef.current) {
            observer.unobserve(videoRef.current);
          }
        }
      },
      { threshold: 0.5 }
    );

    if (videoRef.current) {
      observer.observe(videoRef.current);
    }

    return () => {
      if (videoRef.current) {
        observer.unobserve(videoRef.current);
      }
    };
  }, [media?.url]); // ✅ dependency added (important)

  // ✅ AFTER hooks → safe
  if (!media?.url) return null;

  return (
    <section className="video_sec">
      <div className="custom_containers">
        <video
          ref={videoRef}
          autoPlay
          muted
          loop
          playsInline
          className={`w-100 video-animate ${
            isVisible ? "video-visible" : ""
          }`}
        >
          <source
            src={cleanImage(media?.url)}
            type={media?.mime || "video/mp4"}
          />
          Your browser does not support the video tag.
        </video>
      </div>
    </section>
  );
};

export default Video;