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

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

  const media = productData?.video;

  const isVideo = media?.mime?.startsWith("video/");
  const isImage = media?.mime?.startsWith("image/");

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsVisible(true);
          observer.unobserve(entry.target);
        }
      },
      { threshold: 0.5 }
    );

    if (mediaRef.current) observer.observe(mediaRef.current);

    return () => {
      if (mediaRef.current) observer.unobserve(mediaRef.current);
    };
  }, []);

  if (!media?.url) return null;

  return (
    <section className="video_sec">
      <div className="custom_containers">

        {/* VIDEO */}
        {isVideo && (
          <video
            ref={mediaRef}
            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>
        )}

        {/* IMAGE */}
        {isImage && (
          <div
            ref={mediaRef}
            className={`w-100 video-animate ${isVisible ? "video-visible" : ""}`}
          >
            <Image
              src={cleanImage(media?.url)}
              alt={media?.alternativeText || media?.name || "Media"}
              width={media?.width || 868}
              height={media?.height || 560}
              className="w-100"
              style={{ objectFit: "cover" }}
            />
          </div>
        )}

      </div>
    </section>
  );
};

export default Video;