import { useState, useCallback } from 'react'
import type { ToastItem, ToastType } from '../components/Toast/Toast'

/** 默认自动消失时间 (ms) */
const DEFAULT_DURATION = 3000

/** 最大同时显示数量 */
const MAX_TOASTS = 5

// Module-level counter survives component remounts
let toastCounter = 0

/**
 * UX-05: 升级版 Toast 状态管理 hook
 * 支持多条堆叠、类型区分、自动消失
 */
export function useToast() {
  const [toasts, setToasts] = useState<ToastItem[]>([])

  const showToast = useCallback((msg: string, type: ToastType = 'info', duration = DEFAULT_DURATION) => {
    const id = `toast-${++toastCounter}`
    const newToast: ToastItem = { id, message: msg, type, duration }

    setToasts(prev => {
      const next = [...prev, newToast]
      // 超过最大数量时移除最旧的
      if (next.length > MAX_TOASTS) {
        return next.slice(next.length - MAX_TOASTS)
      }
      return next
    })

    return id
  }, [])

  const dismissToast = useCallback((id: string) => {
    setToasts(prev => prev.filter(t => t.id !== id))
  }, [])

  const cleanup = useCallback(() => {
    setToasts([])
  }, [])

  return { toasts, showToast, dismissToast, cleanup }
}
