const ToastContext = React.createContext(null);

function ToastProvider({ children }) {
  const [toasts, setToasts] = React.useState([]);

  const remove = React.useCallback((id) => {
    setToasts((t) => t.filter((x) => x.id !== id));
  }, []);

  const push = React.useCallback((message, type = 'info') => {
    const id = Date.now() + Math.random();
    const persistent = type === 'error';
    setToasts((t) => [...t, { id, message, type, persistent, exiting: false }]);

    // Los errores quedan visibles hasta que el usuario los cierre.
    // Éxitos y avisos se cierran solos después de un breve tiempo.
    if (!persistent) {
      const visibleMs = type === 'success' ? 2500 : 3300;
      setTimeout(() => {
        setToasts((items) => items.map((item) => item.id === id ? { ...item, exiting: true } : item));
        setTimeout(() => remove(id), 260);
      }, visibleMs);
    }
  }, [remove]);

  const api = React.useMemo(() => ({
    success: (m) => push(m, 'success'),
    error: (m) => push(m, 'error'),
    info: (m) => push(m, 'info'),
  }), [push]);

  return (
    <ToastContext.Provider value={api}>
      {children}
      <div className="toast-modal-layer" aria-live="polite" aria-atomic="true">
        {toasts.map((t) => (
          <div key={t.id} className={`toast-modal toast-modal--${t.type}${t.exiting ? ' is-exiting' : ''}`} role={t.type === 'error' ? 'alert' : 'status'}>
            <div className="toast-modal__icon">
              {t.type === 'success' ? <IconCheck size={21}/> : t.type === 'error' ? <IconAlert size={21}/> : <IconInfo size={21}/>} 
            </div>
            <div className="toast-modal__content">
              <div className="toast-modal__title">
                {t.type === 'success' ? 'Movimiento realizado' : t.type === 'error' ? 'No se pudo completar' : 'Aviso'}
              </div>
              <div className="toast-modal__message">{t.message}</div>
            </div>
            <button className="toast-modal__close" onClick={() => remove(t.id)} aria-label="Cerrar">×</button>
          </div>
        ))}
      </div>
    </ToastContext.Provider>
  );
}

function useToast() {
  return React.useContext(ToastContext);
}
