import React, { createContext, useContext, useState, useCallback } from 'react'; interface Toast { id: string; message: string; type: 'success' | 'error' | 'info' | 'warning'; duration?: number; } interface ToastContextType { showToast: (message: string, type: Toast['type'], duration?: number) => void; } const ToastContext = createContext(undefined); export const useToast = () => { const context = useContext(ToastContext); if (!context) { throw new Error('useToast must be used within a ToastProvider'); } return context; }; export const ToastProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { const [toasts, setToasts] = useState([]); const removeToast = useCallback((id: string) => { setToasts(prev => prev.filter(toast => toast.id !== id)); }, []); const showToast = useCallback((message: string, type: Toast['type'], duration = 5000) => { const id = Date.now().toString(); const toast: Toast = { id, message, type, duration }; setToasts(prev => [...prev, toast]); if (duration > 0) { setTimeout(() => removeToast(id), duration); } }, [removeToast]); return ( {children}
{toasts.map(toast => (
{toast.type === 'success' && ( )} {toast.type === 'error' && ( )} {toast.type === 'info' && ( )} {toast.type === 'warning' && ( )} {toast.message}
))}
); };