/**
 * UI Store - Zustand
 * ==================
 */

import { create } from 'zustand';

type ToastType = 'success' | 'error' | 'info' | 'warning';

export interface ToastMessage {
  id: string;
  message: string;
  type: ToastType;
  duration?: number;
}

interface UIState {
  toasts: ToastMessage[];
}

interface UIActions {
  addToast: (_message: string, _type?: ToastType, _duration?: number) => string;
  removeToast: (_id: string) => void;
  clearToasts: () => void;
}
 

type UIStore = UIState & UIActions;

let toastIdCounter = 0;

// 模块级定时器管理，防止泄漏
const toastTimers = new Map<string, ReturnType<typeof setTimeout>>();

export const useUIStore = create<UIStore>((set) => ({
  toasts: [],

  addToast: (message, type = 'info', duration = 3000) => {
    const state = useUIStore.getState();

    // 去重：相同消息和类型的 toast 已存在则移除旧的，避免堆积
    const existing = state.toasts.find((t) => t.message === message && t.type === type);
    if (existing) {
      const oldTimer = toastTimers.get(existing.id);
      if (oldTimer) {
      clearTimeout(oldTimer);
    }
      toastTimers.delete(existing.id);
      set((s) => ({ toasts: s.toasts.filter((t) => t.id !== existing.id) }));
    }

    // 限制最大数量：超过 5 个时移除最早的
    const maxToasts = 5;
    let currentToasts = existing
      ? state.toasts.filter((t) => t.id !== existing.id)
      : state.toasts;
    if (currentToasts.length >= maxToasts) {
      const toRemove = currentToasts.slice(0, currentToasts.length - maxToasts + 1);
      toRemove.forEach((t) => {
        const timer = toastTimers.get(t.id);
        if (timer) {
      clearTimeout(timer);
    }
        toastTimers.delete(t.id);
      });
      currentToasts = currentToasts.slice(-maxToasts + 1);
    }

    const id = `toast-${++toastIdCounter}`;
    const toast: ToastMessage = { id, message, type, duration };

    set({ toasts: [...currentToasts, toast] });

    const timer = setTimeout(() => {
      toastTimers.delete(id);
      set((s) => ({ toasts: s.toasts.filter((t) => t.id !== id) }));
    }, duration);

    toastTimers.set(id, timer);
    return id;
  },

  removeToast: (id) => {
    const timer = toastTimers.get(id);
    if (timer) {
      clearTimeout(timer);
      toastTimers.delete(id);
    }
    set((state) => ({ toasts: state.toasts.filter((t) => t.id !== id) }));
  },

  clearToasts: () => {
    toastTimers.forEach((timer) => clearTimeout(timer));
    toastTimers.clear();
    set({ toasts: [] });
  },
}));

// 全局便捷方法
export const toast = {
  success: (message: string, duration?: number) =>
    useUIStore.getState().addToast(message, 'success', duration),
  error: (message: string, duration?: number) =>
    useUIStore.getState().addToast(message, 'error', duration || 5000),
  info: (message: string, duration?: number) =>
    useUIStore.getState().addToast(message, 'info', duration),
  warning: (message: string, duration?: number) =>
    useUIStore.getState().addToast(message, 'warning', duration),
  loading: (message: string, duration?: number) =>
    useUIStore.getState().addToast(message, 'info', duration),
};
