'use client';

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

export function usePlaybackControls(taskSketch: any[], taskVideos: any[], currentStep: 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 (isPlaying && taskSketch.length > 0) {
  //     playTimerRef.current = setInterval(() => {
  //       // 这里的切换逻辑需要在父组件中处理
  //       // 因为需要访问 setCurrentSketchIndex
  //     }, 1000);
  //   } else if (playTimerRef.current) {
  //     clearInterval(playTimerRef.current);
  //   }

  //   return () => {
  //     if (playTimerRef.current) {
  //       clearInterval(playTimerRef.current);
  //     }
  //   };
  // }, [isPlaying, taskSketch.length]);

  // 视频自动播放逻辑
  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 (Number(currentStep) >= 3) {
  //     console.log('切换到步骤3+，停止分镜草图播放');
  //     setIsPlaying(false);
  //   }
  // }, [currentStep]);

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

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