/**
 * 全局进度状态管理 - Progress Store
 * ================================
 *
 * 支持两种进度展示模式：
 * - 确定进度：progress 有值时显示百分比进度条
 * - 不确定进度：progress 为 undefined 时显示 CSS 条纹动画
 */

import { create } from 'zustand';

type ProgressPhase = 'idle' | 'running' | 'success' | 'error';

interface ProgressState {
  visible: boolean;
  title: string;
  status: string;
  phase: ProgressPhase;
  progress?: number; // 0-100，undefined 表示不确定进度
  errorMessage?: string;
  pointsConsumed?: number; // 实际消耗积分
}

interface ProgressActions {
  show: (_title: string) => void;
  hide: () => void;
  update: (_status: string) => void;
  setProgress: (_progress: number) => void;
  success: (_message?: string, _pointsConsumed?: number) => void;
  error: (_message: string) => void;
  reset: () => void;
}
 

const DEFAULT_STATE: ProgressState = {
  visible: false,
  title: '',
  status: '',
  phase: 'idle',
  progress: undefined,
};

// 模块级定时器，确保可清理
let hideTimer: ReturnType<typeof setTimeout> | null = null;

export const useProgressStore = create<ProgressState & ProgressActions>((set) => ({
  ...DEFAULT_STATE,

  show: (title) => {
    if (hideTimer) {
      clearTimeout(hideTimer);
      hideTimer = null;
    }
    set({
      visible: true,
      title,
      status: '',
      phase: 'running',
      progress: undefined,
      errorMessage: undefined,
      pointsConsumed: undefined,
    });
  },

  hide: () => {
    set({ visible: false });
    if (hideTimer) {
      clearTimeout(hideTimer);
    }
    hideTimer = setTimeout(() => {
      set(DEFAULT_STATE);
      hideTimer = null;
    }, 300);
  },

  update: (status) => {
    set({ status, phase: 'running' });
  },

  setProgress: (progress) => {
    set((state) => ({
      progress: Math.min(100, Math.max(state.progress ?? 0, progress)),
    }));
  },

  success: (message = '生成完成', pointsConsumed) => {
    set({ status: message, phase: 'success', progress: 100, pointsConsumed });
  },

  error: (message) => {
    set({ errorMessage: message, phase: 'error', progress: undefined });
  },

  reset: () => {
    if (hideTimer) {
      clearTimeout(hideTimer);
      hideTimer = null;
    }
    set(DEFAULT_STATE);
  },
}));
