'use client';

import { useState, useRef, useEffect, useCallback } from 'react';

export function usePlaybackControls(taskVideos: any[], currentStage: string) {
  const [isPlaying, setIsPlaying] = useState(false);
  const [isVideoPlaying, setIsVideoPlaying] = useState(true);
  const [showControls, setShowControls] = useState(false);
  const playTimerRef = useRef<NodeJS.Timeout | null>(null);
  const videoPlayTimerRef = useRef<NodeJS.Timeout | null>(null);

  // 处理播放/暂停
  const togglePlay = useCallback(() => {
    setIsPlaying(prev => !prev);
  }, []);

  // 处理视频播放/暂停
  const toggleVideoPlay = useCallback(() => {
    setIsVideoPlaying(prev => !prev);
  }, []);

  // 视频自动播放逻辑
  useEffect(() => {
    if (isVideoPlaying && taskVideos.length > 0) {
      // 具体的视频播放控制在 MediaViewer 组件中处理
    } else {
      // 清除定时器
      if (videoPlayTimerRef.current) {
        clearInterval(videoPlayTimerRef.current);
      }
    }

    return () => {
      if (videoPlayTimerRef.current) {
        clearInterval(videoPlayTimerRef.current);
      }
    };
  }, [isVideoPlaying, taskVideos.length]);

  // 当切换到分镜草图模式时，停止视频播放
  useEffect(() => {
    if (currentStage !== 'video') {
      setIsVideoPlaying(false);
    }
  }, [currentStage]);

  return {
    isPlaying,
    isVideoPlaying,
    showControls,
    setShowControls,
    setIsPlaying,
    togglePlay,
    toggleVideoPlay,
    playTimerRef, // 暴露给父组件使用
  };
} 