/** Toast notifications: provider + auto-dismissing toast stack. */
import { useCallback, useMemo, useRef, useState, type ReactNode } from 'react'
import { ToastContext, type ToastApi, type ToastVariant } from './toast'
import './toast.css'

interface ToastItem {
  id: number
  message: string
  variant: ToastVariant
}

export function ToastProvider({ children }: { children: ReactNode }) {
  const [toasts, setToasts] = useState<ToastItem[]>([])
  const idRef = useRef(0)
  const remove = useCallback((id: number) => setToasts((ts) => ts.filter((t) => t.id !== id)), [])

  const api = useMemo<ToastApi>(() => {
    const show = (message: string, variant: ToastVariant = 'info') => {
      const id = (idRef.current += 1)
      setToasts((ts) => [...ts, { id, message, variant }])
      window.setTimeout(() => remove(id), 3500)
    }
    return { show, success: (m) => show(m, 'success'), error: (m) => show(m, 'error') }
  }, [remove])

  return (
    <ToastContext.Provider value={api}>
      {children}
      <div className="toast-stack" role="status" aria-live="polite">
        {toasts.map((t) => (
          <button
            key={t.id}
            type="button"
            className={`toast toast--${t.variant}`}
            onClick={() => remove(t.id)}
          >
            {t.message}
          </button>
        ))}
      </div>
    </ToastContext.Provider>
  )
}
