import { create } from 'zustand'

export interface ToastItem {
  id: number
  msg: string
  type: 'info' | 'ok' | 'warn'
}

interface ToastState {
  items: ToastItem[]
  push: (msg: string, type: ToastItem['type']) => void
  remove: (id: number) => void
}

let seq = 0

export const useToast = create<ToastState>((set) => ({
  items: [],
  push: (msg, type) => {
    const id = ++seq
    set((s) => ({ items: [...s.items, { id, msg, type }] }))
    setTimeout(() => {
      set((s) => ({ items: s.items.filter((t) => t.id !== id) }))
    }, 2800)
  },
  remove: (id) => set((s) => ({ items: s.items.filter((t) => t.id !== id) }))
}))

export function toast(msg: string, type: ToastItem['type'] = 'info'): void {
  useToast.getState().push(msg, type)
}
