"use client";

import { useEffect, useRef } from "react";

type AutoPlayVideoProps = {
  src: string;
  className?: string;
};

export default function AutoPlayVideo({
  src,
  className = "",
}: AutoPlayVideoProps) {
  const videoRef = useRef<HTMLVideoElement | null>(null);

  useEffect(() => {
    const video = videoRef.current;
    if (video) {
      const playPromise = video.play();
      if (playPromise !== undefined) {
        playPromise.catch((error) => {
          console.warn(`Autoplay failed for ${src}:`, error);
        });
      }
    }
  }, [src]);

  // Build captions path based on video src
  const captionsSrc = src.replace(/\.\w+$/, ".vtt");

  return (
    <video
      ref={videoRef}
      src={src}
      autoPlay
      muted
      playsInline
      loop
      preload="auto"
      className={className}
    >
      <track
        kind="captions"
        src={captionsSrc}
        srcLang="en"
        label="English"
        default
      />
    </video>
  );
}
