import React, { createContext, useContext, useState, useCallback } from 'react'; import { Toast } from '../types'; import { X, CheckCircle2, AlertCircle, Info, AlertTriangle } from 'lucide-react'; interface ToastContextData { addToast: (toast: Omit) => void; removeToast: (id: string) => void; } const ToastContext = createContext({} as ToastContextData); export const ToastProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { const [toasts, setToasts] = useState([]); const addToast = useCallback(({ type, title, message, duration = 4000 }: Omit) => { const id = Math.random().toString(36).substring(2, 9); const newToast = { id, type, title, message, duration }; setToasts((state) => [...state, newToast]); if (duration > 0) { setTimeout(() => { removeToast(id); }, duration); } }, []); const removeToast = useCallback((id: string) => { setToasts((state) => state.filter((toast) => toast.id !== id)); }, []); return ( {children} {/* Toast Container Rendered Here Globally */}
{toasts.map((toast) => (
{toast.type === 'success' && } {toast.type === 'error' && } {toast.type === 'warning' && } {toast.type === 'info' && }

{toast.title}

{toast.message &&

{toast.message}

}
))}
); }; export const useToast = () => { const context = useContext(ToastContext); if (!context) throw new Error('useToast must be used within a ToastProvider'); return context; };