import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from 'react' import { dismissToast, initialToasts, pushToast, type Toast, type ToastState } from './toast-store' const AUTO_DISMISS_MS = 4000 interface ToastApi { ok: (msg: string) => void; err: (msg: string) => void } const Ctx = createContext(null) /** Mount once at app root; renders the bottom-right stack. */ export function ToastProvider(props: { children: ReactNode }) { const [state, setState] = useState(initialToasts) const push = useCallback((tone: Toast['tone'], message: string) => { setState((s) => { const next = pushToast(s, tone, message) const id = next.toasts[next.toasts.length - 1]!.id window.setTimeout(() => setState((s2) => dismissToast(s2, id)), AUTO_DISMISS_MS) return next }) }, []) const api = useMemo(() => ({ ok: (msg) => push('ok', msg), err: (msg) => push('err', msg), }), [push]) return ( {props.children}
{state.toasts.map((t) => (
{t.message}
))}
) } export function useToast(): ToastApi { const api = useContext(Ctx) if (api === null) throw new Error('useToast requires at the app root') return api }