import { Component, OnInit, inject } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { IonHeader, IonToolbar, IonTitle, IonContent, IonCard, IonCardHeader, IonCardSubtitle, IonCardTitle, IonCardContent, IonButton, IonIcon, IonBadge, IonItem, IonLabel, IonSelect, IonSelectOption, IonInput, IonSpinner, IonList, IonProgressBar, } from '@ionic/angular/standalone'; import { WazeNavigationService, WazeStop } from '../../services/waze-navigation.service'; import { TripService, BookingPayload } from '../../services/trip.service'; @Component({ selector: 'app-trip-pooling', standalone: true, imports: [ CommonModule, FormsModule, IonHeader, IonToolbar, IonTitle, IonContent, IonCard, IonCardHeader, IonCardSubtitle, IonCardTitle, IonCardContent, IonButton, IonIcon, IonBadge, IonItem, IonLabel, IonSelect, IonSelectOption, IonInput, IonSpinner, IonList, IonProgressBar, ], template: ` Pacifictrans Go Cuenta Bloqueada por Penalidad Sanción por cancelación tardía

Tienes un saldo pendiente de \${{ userPenaltyBalance | number }} COP. Debes saldar esta penalidad para poder solicitar nuevos viajes o servicios de mensajería.

Pagar Penalidad con Bold (PSE / Nequi / QR Bre-B)
Solicitud de Puesto (Pool de 4) Agrupación inteligente por cercanía Ruta Cali ➔ Buenaventura Buenaventura ➔ Cali Dirección de recogida en Cali Parada fija en Buenaventura {{ stop.nombre }} Método de Pago Preferido Bold (PSE, Tarjetas, Bre-B) Nequi Digital Efectivo al abordar Solicitar Puesto ($35.000 COP)
Viaje #{{ activeTrip._id?.slice(-6) }} {{ activeTrip.estado }}
{{ activeTrip.origen?.ciudad }} ➔ {{ activeTrip.destino?.ciudad }}

⏳ En revisión del Administrador

Tu solicitud ha sido agrupada en el pool. Recibirás una notificación push cuando sea aprobada.

🚗 Conductor Asignado

Nombre: {{ activeTrip.conductorId?.nombre || 'Confirmado' }}

Hora estimada de recogida: {{ activeTrip.horaEstimadaRecogida | date:'shortTime' }}

🗺️ Ruta Optimizada Waze (Parada por Parada)

{{ wazeProgress.completadas }} de {{ wazeProgress.total }} paradas completadas

Siguiente recogida: {{ currentStop.nombrePasajero }}

{{ currentStop.direccion }}

Abrir en Waze Marcar Recogido
Cancelar Reserva
`, styles: [ ` .flex-header { display: flex; justify-content: space-between; align-items: center; } .notice-box { background: #fff3cd; color: #856404; padding: 12px; border-radius: 8px; margin-bottom: 12px; } .driver-box { background: #e8f4fd; color: #0b5394; padding: 12px; border-radius: 8px; margin-bottom: 12px; } .current-stop-card { background: #f8f9fa; border: 1px solid #dee2e6; padding: 12px; border-radius: 8px; margin-top: 8px; } .address-text { font-size: 0.9rem; color: #6c757d; } .action-buttons { display: flex; gap: 8px; margin-top: 10px; } .small-text { font-size: 0.8rem; color: #6c757d; margin-top: 4px; } `, ], }) export class TripPoolingComponent implements OnInit { private wazeService = inject(WazeNavigationService); private tripService = inject(TripService); loading: boolean = false; userPenaltyBalance: number = 0; boldPenaltyCheckoutUrl?: string; activeTrip: any = null; bvStops = [ { nombre: 'Terminal de Transportes Buenaventura', coordenadas: [-77.018, 3.882] }, { nombre: 'Centro / Muelle Turístico Buenaventura', coordenadas: [-77.031, 3.889] }, { nombre: 'Sector El Piñal Buenaventura', coordenadas: [-77.025, 3.879] }, ]; selectedBuenaventuraStop = this.bvStops[0]; booking: BookingPayload = { usuarioId: 'usr-demo-123', direccionTexto: '', coordenadas: [-76.532, 3.4516], sentido: 'CALI_A_BUENAVENTURA', puntoFijoBuenaventura: this.selectedBuenaventuraStop, metodoPago: 'BOLD', }; wazeStops: WazeStop[] = []; currentStop: WazeStop | null = null; wazeProgress = { completadas: 0, total: 0, porcentaje: 0 }; async ngOnInit() { await this.checkUserStatus(); } async checkUserStatus() { try { const res = await this.tripService.getUserStatus(this.booking.usuarioId); if (res.success) { this.userPenaltyBalance = res.montoPenalidad || 0; this.boldPenaltyCheckoutUrl = res.linkLiquidacionBold; } } catch (err) { console.warn('Error verificando penalidades de usuario:', err); } } async submitBooking() { this.loading = true; this.booking.puntoFijoBuenaventura = this.selectedBuenaventuraStop; try { const res = await this.tripService.requestPoolTrip(this.booking); if (res.success) { this.activeTrip = res.trip; if (res.secuenciaParadas) { this.wazeStops = res.secuenciaParadas.map((p: any) => ({ orden: p.orden, nombrePasajero: `Parada ${p.orden}`, direccion: p.direccion, lat: p.lat, lng: p.lng, completada: p.completada, })); this.wazeService.setStops(this.wazeStops); this.updateWazeState(); } } } catch (err: any) { alert(`Error al solicitar viaje: ${err.message}`); } finally { this.loading = false; } } openWazeForCurrentStop() { this.wazeService.navigateToCurrentStop(); } completeStop() { this.wazeService.completeCurrentStopAndAdvance(); this.updateWazeState(); } updateWazeState() { this.currentStop = this.wazeService.getCurrentStop(); this.wazeProgress = this.wazeService.getProgress(); } getStatusColor(estado: string): string { switch (estado) { case 'PENDING_APPROVAL': return 'warning'; case 'ACTIVE': return 'success'; case 'IN_PROGRESS': return 'primary'; case 'COMPLETED': return 'medium'; case 'CANCELLED': return 'danger'; default: return 'medium'; } } async cancelTrip() { if (!confirm('¿Seguro que deseas cancelar? Si el viaje ya está aprobado, incurrirás en una penalidad.')) { return; } try { const res = await this.tripService.cancelTrip(this.activeTrip._id, this.booking.usuarioId); alert(res.message); this.activeTrip = null; await this.checkUserStatus(); } catch (err: any) { alert(`Error cancelando viaje: ${err.message}`); } } openUrl(url: string) { window.open(url, '_system'); } }