'use client' import { createContext, useContext, useState, useCallback, ReactNode } from 'react' interface Toast { id: string message: string type: 'info' | 'success' | 'error' | 'loading' } interface ToastContextValue { toasts: Toast[] addToast: (message: string, type?: Toast['type']) => string removeToast: (id: string) => void updateToast: (id: string, message: string, type?: Toast['type']) => void } const ToastContext = createContext(null) export function ToastProvider({ children }: { children: ReactNode }) { const [toasts, setToasts] = useState([]) const addToast = useCallback((message: string, type: Toast['type'] = 'info') => { const id = crypto.randomUUID() setToasts(prev => [...prev, { id, message, type }]) if (type !== 'loading') { setTimeout(() => { setToasts(prev => prev.filter(t => t.id !== id)) }, 4000) } return id }, []) const removeToast = useCallback((id: string) => { setToasts(prev => prev.filter(t => t.id !== id)) }, []) const updateToast = useCallback((id: string, message: string, type: Toast['type'] = 'info') => { setToasts(prev => prev.map(t => t.id === id ? { ...t, message, type } : t)) if (type !== 'loading') { setTimeout(() => { setToasts(prev => prev.filter(t => t.id !== id)) }, 4000) } }, []) return ( {children} ) } export function useToast() { const context = useContext(ToastContext) if (!context) { throw new Error('useToast must be used within a ToastProvider') } return context } function ToastContainer({ toasts, removeToast }: { toasts: Toast[]; removeToast: (id: string) => void }) { if (toasts.length === 0) return null return (
{toasts.map(toast => (
{toast.type === 'loading' && (
)} {toast.message} {toast.type !== 'loading' && ( )}
))}
) }