import { create } from 'zustand'

interface Toast {
  id: number
  message: string
  tone: 'info' | 'success' | 'error'
}

interface ToastState {
  toasts: Toast[]
  show: (message: string, tone?: Toast['tone']) => void
  dismiss: (id: number) => void
}

let counter = 0

export const useToastStore = create<ToastState>(set => ({
  toasts: [],
  show: (message, tone = 'info') => {
    const id = ++counter
    set(s => ({ toasts: [...s.toasts, { id, message, tone }] }))
    setTimeout(() => {
      set(s => ({ toasts: s.toasts.filter(t => t.id !== id) }))
    }, 2400)
  },
  dismiss: id => set(s => ({ toasts: s.toasts.filter(t => t.id !== id) })),
}))

/** Convenience that doesn't require subscribing - safe to call anywhere. */
export function toast(message: string, tone: Toast['tone'] = 'info') {
  useToastStore.getState().show(message, tone)
}
