import { useEffect, useState, RefObject } from 'react';

const useVideoControls = (
  videoRef: RefObject<HTMLVideoElement>,
  videoUrl: string,
  autoplay = false,
  forcedMuted = false,
) => {
  const [isPaused, setIsPaused] = useState(!autoplay);
  // Start muted — required for autoplay and consistent across all modes.
  const [userMutedPreference, setUserMutedPreference] = useState(true);
  const isMuted = forcedMuted || userMutedPreference;

  const toggleMute = () => {
    if (forcedMuted) return;
    const video = videoRef.current;
    if (!video) return;
    const next = !userMutedPreference;
    video.muted = next;
    setUserMutedPreference(next);
  };

  useEffect(() => {
    if (videoRef.current) {
      videoRef.current.muted = isMuted;
    }
  }, [isMuted, videoRef]);

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

    video.load();
    video.muted = isMuted;

    if (autoplay) {
      const handleCanPlay = () => {
        video
          .play()
          .then(() => setIsPaused(false))
          .catch(() => setIsPaused(true));
      };
      video.addEventListener('loadeddata', handleCanPlay, { once: true });
      return () => video.removeEventListener('loadeddata', handleCanPlay);
    } else {
      setIsPaused(true);
    }
  }, [videoUrl, autoplay, videoRef]);

  const playVideo = async () => {
    try {
      await videoRef.current?.play();
      setIsPaused(false);
    } catch (error) {
      setIsPaused(true);
      throw new Error('Error playing video. Please try again later.');
    }
  };

  const pauseVideo = () => {
    videoRef.current?.pause();
    setIsPaused(true);
  };

  return { isPaused, isMuted, toggleMute, playVideo, pauseVideo };
};

export default useVideoControls;
