/**
 * useBackgroundVideoPlayback Hook
 *
 * Manages background video playback with custom start/end times.
 * Follows patterns from useTransitionPlayback for video time control.
 */

import { useEffect, useRef, useCallback, type RefObject } from 'react';
import { logger } from '../lib/logger';

export interface UseBackgroundVideoPlaybackOptions {
  /** URL of the video to play */
  videoUrl?: string;
  /** Whether to autoplay the video (default: true) */
  autoplay?: boolean;
  /** Whether to loop the video (default: true) */
  loop?: boolean;
  /** Whether the video is muted (default: true) */
  muted?: boolean;
  /** Start time in seconds (default: null = start from beginning) */
  startTime?: number | null;
  /** End time in seconds (default: null = play to end) */
  endTime?: number | null;
}

export interface UseBackgroundVideoPlaybackResult {
  /** Ref to attach to the video element */
  videoRef: RefObject<HTMLVideoElement | null>;
}

/**
 * Hook for managing background video playback with custom start/end times.
 *
 * When startTime is set, the video will seek to that position on load.
 * When endTime is set, the video will either loop back to startTime or pause,
 * depending on the loop setting.
 *
 * @example
 * const { videoRef } = useBackgroundVideoPlayback({
 *   videoUrl: 'https://example.com/video.mp4',
 *   autoplay: true,
 *   loop: true,
 *   muted: true,
 *   startTime: 2.5,
 *   endTime: 10.0,
 * });
 *
 * return <video ref={videoRef} src={videoUrl} />;
 */
export function useBackgroundVideoPlayback({
  videoUrl,
  autoplay = true,
  loop = true,
  muted = true,
  startTime = null,
  endTime = null,
}: UseBackgroundVideoPlaybackOptions): UseBackgroundVideoPlaybackResult {
  const videoRef = useRef<HTMLVideoElement | null>(null);
  // Store current values in refs for event handlers to access
  const startTimeRef = useRef(startTime);
  const endTimeRef = useRef(endTime);
  const loopRef = useRef(loop);
  const autoplayRef = useRef(autoplay);

  // Update refs when values change
  useEffect(() => {
    startTimeRef.current = startTime;
  }, [startTime]);

  useEffect(() => {
    endTimeRef.current = endTime;
  }, [endTime]);

  useEffect(() => {
    loopRef.current = loop;
  }, [loop]);

  useEffect(() => {
    autoplayRef.current = autoplay;
  }, [autoplay]);

  // Seek to start time when specified and video is ready
  const seekToStartTime = useCallback(() => {
    const video = videoRef.current;
    const st = startTimeRef.current;
    if (!video || st == null || st <= 0) return;

    video.currentTime = st;
    logger.info('Background video: seeking to start time', { startTime: st });
  }, []);

  // Handle start time changes - seek immediately when startTime changes
  useEffect(() => {
    const video = videoRef.current;
    if (!video || !videoUrl) return;

    // If video has loaded metadata, seek immediately
    if (video.readyState >= 1 && startTime != null && startTime > 0) {
      video.currentTime = startTime;
      logger.info('Background video: seeking to start time', { startTime });
    }

    // Set up listener for initial load (if not loaded yet)
    const handleLoadedMetadata = () => {
      seekToStartTime();
    };

    video.addEventListener('loadedmetadata', handleLoadedMetadata);
    return () => {
      video.removeEventListener('loadedmetadata', handleLoadedMetadata);
    };
  }, [videoUrl, startTime, seekToStartTime]);

  // Handle autoplay state changes
  useEffect(() => {
    const video = videoRef.current;
    if (!video || !videoUrl) return;

    if (autoplay) {
      video.play().catch((error) => {
        // Autoplay blocked by browser - this is expected behavior
        logger.info('Background video autoplay blocked by browser', {
          error: error instanceof Error ? error.message : String(error),
        });
      });
    } else {
      video.pause();
    }
  }, [videoUrl, autoplay]);

  // Handle end time enforcement via timeupdate
  useEffect(() => {
    const video = videoRef.current;
    if (!video || !videoUrl) return;

    const handleTimeUpdate = () => {
      const currentEndTime = endTimeRef.current;
      const currentLoop = loopRef.current;
      const currentStartTime = startTimeRef.current;

      // Skip if no end time is set
      if (currentEndTime == null) return;

      // Check if we've reached or passed the end time
      if (video.currentTime >= currentEndTime) {
        if (currentLoop) {
          // Loop back to start time (or beginning)
          const loopTarget = currentStartTime ?? 0;
          video.currentTime = loopTarget;
          logger.info('Background video: looping back', {
            from: currentEndTime,
            to: loopTarget,
          });
        } else {
          // Pause at end time
          video.pause();
          logger.info('Background video: paused at end time', {
            endTime: currentEndTime,
          });
        }
      }
    };

    video.addEventListener('timeupdate', handleTimeUpdate);
    return () => {
      video.removeEventListener('timeupdate', handleTimeUpdate);
    };
  }, [videoUrl]);

  // Handle muted state changes
  useEffect(() => {
    const video = videoRef.current;
    if (!video) return;
    video.muted = muted;
  }, [muted]);

  return { videoRef };
}

export default useBackgroundVideoPlayback;
