// ─── Video Section ────────────────────────────────────────────────────────────

import { useState, useRef, useEffect } from "react";

const VideoSection = ({ videoData }: any) => {
  // console.log('Video', videoData)
  const [playing, setPlaying] = useState(false);
  const videoRef = useRef<HTMLVideoElement>(null);

  const toggle = () => {
    if (!videoRef.current) return;
    
    try {
      if (playing) {
        videoRef.current.pause();
        setPlaying(false);
      } else {
        const playPromise = videoRef.current.play();
        if (playPromise !== undefined) {
          playPromise
            .then(() => {
              setPlaying(true);
            })
            .catch((error: any) => {
              console.error("Playback failed:", error);
              setPlaying(false);
            });
        }
      }
    } catch (error) {
      console.error("Video toggle error:", error);
    }
  };

  const handleVideoError = (e: any) => {
    console.error("Video loading error:", e);
  };

  // Get video URL from videoData
  const videoUrl = videoData?.video_url || "/images/wedding.mp4";

  return (
    <section className="videocontainer">
      <div className="container container-xxl px-3">
        <div className="section-heading text-center">
          <h2>In the spotlight</h2>
        </div>
      </div>
      <div className="videoinner">
        <video
          ref={videoRef}
          muted
          playsInline
          poster="images/video-poster.jpg"
          onPlay={() => setPlaying(true)}
          onPause={() => setPlaying(false)}
          onError={handleVideoError}
        >
          <source src={videoUrl} type="video/mp4" />
          Your browser does not support the video tag.
        </video>
        <div className="videoovarlay">
          <button
            onClick={toggle}
            className="play-pause-button"
            aria-label={playing ? "Pause" : "Play"}
          >
            {playing ? (
              <svg fill="currentColor" viewBox="0 0 24 24">
                <path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/>
              </svg>
            ) : (
              <svg fill="currentColor" viewBox="0 0 24 24">
                <path d="M8 5v14l11-7z"/>
              </svg>
            )}
          </button>
          <h2><span>{videoData?.title}</span>{videoData?.subtitle}</h2>
        </div>
      </div>
    </section>
  );
};

export default VideoSection;