import { ref, onMounted, onUnmounted } from 'vue';

export function useProgress() {
  const progress = ref(0);
  const isPaused = ref(false);
  
  // 速度控制参数
  const speed = ref(50); // 速度滑块值 (0-100)
  const targetFPS = ref(60); // 目标帧率 (FPS)
  
  let lastTime = 0;
  let animationTimer = null;

  const updateProgress = () => {
    if (isPaused.value || progress.value >= 100) {
      return;
    }

    const now = Date.now();
    const interval = 1000 / targetFPS.value;
    const elapsed = now - lastTime;

    if (elapsed > interval) {
      // 基础速度：speed 值为 50 时，每秒约增加 10%
      const increment = (speed.value / 100) * (elapsed / 1000) * 20;
      progress.value = Math.min(progress.value + increment, 100);
      lastTime = now - (elapsed % interval);
    }
    
    animationTimer = setTimeout(updateProgress, interval);
  };

  const start = () => {
    progress.value = 0;
    isPaused.value = false;
    lastTime = Date.now();
    
    if (animationTimer) clearTimeout(animationTimer);
    updateProgress();
  };
  
  // 暂停/继续控制
  const togglePause = () => {
    isPaused.value = !isPaused.value;
    if (!isPaused.value) {
      lastTime = Date.now();
      updateProgress();
    }
  };
  
  // 设置速度
  const setSpeed = (value) => {
    speed.value = Math.max(0, Math.min(100, value));
  };

  // 设置FPS
  const setFPS = (value) => {
    targetFPS.value = Math.max(1, Math.min(120, value));
  };

  onUnmounted(() => {
    if (animationTimer) clearTimeout(animationTimer);
  });

  return {
    progress,
    isPaused,
    speed,
    targetFPS,
    start,
    togglePause,
    setSpeed,
    setFPS
  };
}
