# Sistema Global de Notificaciones

Sistema unificado de notificaciones que funciona en toda la aplicación: React, Livewire, Alpine.js, y JavaScript vanilla.

## 🎯 Características

- ✅ **Global**: Funciona en cualquier parte de la aplicación
- ✅ **React Component**: Renderizado nativo de React con z-index máximo
- ✅ **Auto-dismiss**: Se cierra automáticamente después de 5 segundos
- ✅ **Manual close**: Botón X para cerrar manualmente
- ✅ **4 Tipos**: success, error, warning, info
- ✅ **Responsive**: Se adapta a diferentes tamaños de pantalla

## 📦 Archivos Creados

```
resources/
├── js/
│   ├── components/
│   │   └── GlobalNotification.jsx    # Componente React global
│   └── utils/
│       └── notifications.js           # Helper function
└── views/
    └── layouts/
        └── app.blade.php              # Incluye <div id="global-notification-root">
```

## 🚀 Uso

### **Desde React**
```javascript
import { showNotification } from '../../utils/notifications';

// Success
showNotification('success', 'Operation completed successfully!');

// Error
showNotification('error', 'Something went wrong');

// Warning
showNotification('warning', 'Please review your input');

// Info
showNotification('info', 'New updates available');
```

### **Desde Livewire/Alpine.js**
```blade
{{-- En un componente Livewire --}}
<button 
    @click="window.showNotification('success', 'Data saved successfully!')"
>
    Save
</button>

{{-- Desde Alpine x-data --}}
<div x-data="{
    saveData() {
        // ... tu lógica ...
        window.showNotification('error', 'Failed to save data');
    }
}">
```

### **Desde JavaScript Vanilla**
```javascript
// La función está disponible globalmente
window.showNotification('info', 'Processing your request...');
```

### **Desde PHP (Backend)**
```php
// Esto dispara el sistema Alpine/Livewire tradicional
$this->dispatch('showalert', response: [
    'type' => 'success',
    'message' => 'Record created successfully'
]);
```

## 🎨 Tipos de Notificaciones

| Tipo | Color | Uso |
|------|-------|-----|
| `success` | Verde | Operaciones exitosas |
| `error` | Rojo | Errores y fallos |
| `warning` | Amarillo/Naranja | Advertencias |
| `info` | Azul | Información general |

## 🔧 Personalización

El componente está en `resources/js/components/GlobalNotification.jsx` y puedes modificar:

- **Duración**: Cambiar el timeout de 5000ms (línea 18)
- **Posición**: Modificar `top`, `left` en styles
- **Colores**: Ajustar los valores en `typeStyles`
- **z-index**: Actualmente en 99999

## 📋 Ejemplos de Uso en el Proyecto

### **FlowView.jsx**
```javascript
// Al guardar el flujo
if (!response.ok) {
    showNotification('error', 'Failed to save flow');
    return;
}
```

### **Formularios de Nodos (Blade)**
```blade
<button 
    @click="async () => {
        try {
            const response = await fetch(...);
            if (response.ok) {
                window.showNotification('success', 'Node saved successfully');
            } else {
                window.showNotification('error', 'Failed to save node');
            }
        } catch (error) {
            window.showNotification('error', 'An error occurred');
        }
    }"
>
    Save Node
</button>
```

## 🐛 Troubleshooting

**Notificación no aparece:**
1. Verificar que `npm run dev` esté corriendo
2. Recargar la página con `Ctrl + Shift + R`
3. Abrir consola del navegador (F12) y buscar errores

**Error "showNotification is not defined":**
- Verificar que `resources/js/app.js` incluya:
  ```javascript
  import "./utils/notifications";
  ```

**Notificación queda detrás de otros elementos:**
- Ajustar el `zIndex: 99999` en `GlobalNotification.jsx`

## ✅ Ventajas sobre el Sistema Anterior

| Característica | Sistema Anterior | Sistema Nuevo |
|----------------|------------------|---------------|
| Funciona en React | ❌ No | ✅ Sí |
| Funciona en Alpine | ✅ Sí | ✅ Sí |
| z-index garantizado | ❌ No (z-50) | ✅ Sí (z-99999) |
| Función global | ❌ No | ✅ Sí |
| Auto-dismiss | ✅ Sí | ✅ Sí |
| Botón de cierre | ✅ Sí | ✅ Sí |

---

**Última actualización:** 2025-11-21

