// Screens: Trips list, Trip Detail + Timeline, Fleet

const { useState: useState2 } = window.React;

// ── Trips List ────────────────────────────────────────────────────
function ScreenTrips({ onNavigate, trips: tripsLive }) {
  const { drivers } = ROUTING_DATA;
  const trips = tripsLive || ROUTING_DATA.trips;
  const [search, setSearch] = useState2('');
  const [statusFilter, setStatusFilter] = useState2('todos');
  const [routeFilter, setRouteFilter] = useState2('todas');

  const filtered = trips.filter(t => {
    const drv = drivers.find(d => d.id === t.driver);
    const matchSearch = !search ||
      t.id.toLowerCase().includes(search.toLowerCase()) ||
      t.route.toLowerCase().includes(search.toLowerCase()) ||
      (drv?.name || '').toLowerCase().includes(search.toLowerCase());
    const matchStatus = statusFilter === 'todos' || t.status === statusFilter;
    const matchRoute = routeFilter === 'todas' || t.route === routeFilter;
    return matchSearch && matchStatus && matchRoute;
  });

  const statusOpts = [
    { value: 'todos', label: 'Todos los estados' },
    { value: 'en_ruta', label: 'En ruta' },
    { value: 'completado', label: 'Completado' },
    { value: 'programado', label: 'Programado' },
  ];

  const routeOpts = [
    { value: 'todas', label: 'Todas las rutas' },
    ...ROUTING_DATA.routes.map(r => ({ value: r, label: r })),
  ];

  return (
    <PageShell title="Viajes" sub={`${filtered.length} viajes encontrados`}
      actions={<Btn small>+ Nuevo viaje</Btn>}
    >
      {/* Filters */}
      <div style={{ display: 'flex', gap: 10, marginBottom: 18, flexWrap: 'wrap' }}>
        <FilterInput placeholder="Buscar ID, ruta, conductor…" value={search} onChange={setSearch} width={240} />
        <FilterSelect value={statusFilter} onChange={setStatusFilter} options={statusOpts} />
        <FilterSelect value={routeFilter} onChange={setRouteFilter} options={routeOpts} />
        {(search || statusFilter !== 'todos' || routeFilter !== 'todas') && (
          <Btn small variant="ghost" onClick={() => { setSearch(''); setStatusFilter('todos'); setRouteFilter('todas'); }}>✕ Limpiar</Btn>
        )}
      </div>

      {filtered.length === 0 ? (
        <EmptyState message="No se encontraron viajes con los filtros seleccionados." />
      ) : (
        <Table
          headers={['ID Viaje', 'Ruta', 'Conductor', 'Camión', 'Salida', 'Estado', 'Retraso', '']}
          onRowClick={i => onNavigate('trip-detail', filtered[i])}
          rows={filtered.map(t => {
            const drv = drivers.find(d => d.id === t.driver);
            const trk = ROUTING_DATA.trucks.find(tk => tk.id === t.truck);
            return [
              <span style={{ fontFamily: 'monospace', fontSize: 12, color: '#5a7366', fontWeight: 600 }}>{t.id}</span>,
              <RouteArrow origin={t.origin} destination={t.destination} />,
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <div style={{ width: 26, height: 26, borderRadius: '50%', background: '#dcfce7', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontWeight: 700, color: '#15803d' }}>
                  {(drv?.name || '?').split(' ').map(n => n[0]).join('').slice(0, 2)}
                </div>
                <span>{drv?.name || '—'}</span>
              </div>,
              <span style={{ fontFamily: 'monospace', fontSize: 12 }}>{trk?.plate || '—'}</span>,
              <span style={{ fontSize: 12, color: '#5a7366' }}>{t.departure.split('T')[0]} {t.departure.split('T')[1]}</span>,
              <Chip status={t.status} small />,
              <DelayBadge minutes={t.status === 'programado' ? null : t.delay} />,
              <span style={{ fontSize: 12, color: '#10B981', fontWeight: 600 }}>Ver →</span>,
            ];
          })}
        />
      )}
    </PageShell>
  );
}

// ── Trip Detail + Event Timeline ──────────────────────────────────
function ScreenTripDetail({ trip, onBack, onUpdateTrip }) {
  const { drivers, trucks } = ROUTING_DATA;
  const drv = drivers.find(d => d.id === trip.driver);
  const trk = trucks.find(t => t.id === trip.truck);
  const [showRegister, setShowRegister] = useState2(false);
  const [showClose, setShowClose] = useState2(false);
  const [localTrip, setLocalTrip] = useState2(trip);

  const handleSaveEvent = (ev) => {
    const updated = { ...localTrip, events: [...localTrip.events, ev] };
    setLocalTrip(updated);
    onUpdateTrip && onUpdateTrip(updated);
  };

  const handleCloseTrip = ({ arrivalTime, note, delay: finalDelay }) => {
    const closeEvent = { time: arrivalTime, type: 'llegada', label: 'Llegada al destino', detail: note || 'Viaje completado' };
    const updated = {
      ...localTrip,
      status: 'completado',
      progress: 100,
      delay: finalDelay > 0 ? finalDelay : 0,
      etaReal: localTrip.etaReal?.split('T')[0] + 'T' + arrivalTime || localTrip.etaPlanned?.split('T')[0] + 'T' + arrivalTime,
      events: [...localTrip.events, closeEvent],
    };
    setLocalTrip(updated);
    onUpdateTrip && onUpdateTrip(updated);
  };

  // Use localTrip everywhere below
  const t2 = localTrip;

  const eventIcons = {
    salida:     { icon: '▶', color: '#10B981', bg: '#dcfce7' },
    checkpoint: { icon: '●', color: '#3B82F6', bg: '#dbeafe' },
    parada:     { icon: '■', color: '#8B5CF6', bg: '#ede9fe' },
    demora:     { icon: '!', color: '#d97706', bg: '#fef9c3' },
    llegada:    { icon: '★', color: '#10B981', bg: '#dcfce7' },
  };

  return (
    <>
    <RegisterEventModal open={showRegister} onClose={() => setShowRegister(false)} trip={t2} onSave={handleSaveEvent} />
    <CloseTripModal open={showClose} onClose={() => setShowClose(false)} trip={t2} onConfirm={handleCloseTrip} />
    <PageShell
      title={`Viaje ${t2.id}`}
      sub={`${t2.route} — ${t2.cargo}`}
      actions={
        <div style={{ display: 'flex', gap: 10 }}>
          <Btn small variant="ghost" onClick={onBack}>← Volver</Btn>
          {t2.status === 'en_ruta' && <>
            <Btn small variant="ghost" onClick={() => setShowRegister(true)}>+ Registrar evento</Btn>
            <Btn small onClick={() => setShowClose(true)}>✓ Cerrar viaje</Btn>
          </>}
        </div>
      }
    >
      {/* Header info cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 24 }}>
        {[
          { label: 'Estado', value: <Chip status={t2.status} /> },
          { label: 'Conductor', value: drv?.name || '—' },
          { label: 'Camión', value: `${trk?.plate} · ${trk?.model}` },
          { label: 'Retraso', value: <DelayBadge minutes={t2.delay} /> },
        ].map((item, i) => (
          <div key={i} style={{ background: '#fff', borderRadius: 10, padding: '14px 16px', boxShadow: '0 1px 4px rgba(0,0,0,.06)' }}>
            <div style={{ fontSize: 11, color: '#5a7366', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '.05em', marginBottom: 6 }}>{item.label}</div>
            <div style={{ fontSize: 14, color: '#1a2e25', fontWeight: 600 }}>{item.value}</div>
          </div>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 20 }}>
        {/* Timeline */}
        <div style={{ background: '#fff', borderRadius: 12, padding: '22px 24px', boxShadow: '0 1px 4px rgba(0,0,0,.06)' }}>
          <SectionHeader title="Línea de tiempo" sub="Eventos registrados del viaje" />

          {/* ETA comparison */}
          <div style={{ display: 'flex', gap: 16, marginBottom: 24, padding: '14px 16px', background: '#f7faf8', borderRadius: 10 }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 11, color: '#5a7366', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '.05em', marginBottom: 4 }}>ETA Planeado</div>
              <div style={{ fontSize: 20, fontWeight: 700, color: '#1a2e25' }}>{t2.etaPlanned?.split('T')[1]}</div>
              <div style={{ fontSize: 12, color: '#5a7366' }}>{t2.etaPlanned?.split('T')[0]}</div>
            </div>
            <div style={{ width: 1, background: '#dde8e2' }}/>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 11, color: '#5a7366', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '.05em', marginBottom: 4 }}>ETA Real / Proyectado</div>
              <div style={{ fontSize: 20, fontWeight: 700, color: t2.delay > 0 ? '#d97706' : '#15803d' }}>
                {t2.etaReal?.split('T')[1] || t2.etaPlanned?.split('T')[1] || '—'}
              </div>
              <div style={{ fontSize: 12, color: '#5a7366' }}>{t2.delay > 0 ? `+${t2.delay} min de desvío` : 'Sin retraso activo'}</div>
            </div>
          </div>

          {/* Progress */}
          {t2.status === 'en_ruta' && (
            <div style={{ marginBottom: 24 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                <span style={{ fontSize: 12, color: '#5a7366' }}>Progreso del viaje</span>
                <span style={{ fontSize: 12, fontWeight: 700, color: '#1a2e25' }}>{t2.progress}%</span>
              </div>
              <ProgressBar value={t2.progress} color={t2.delay > 60 ? '#F59E0B' : '#10B981'} height={8} />
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 4 }}>
                <span style={{ fontSize: 11, color: '#5a7366' }}>{t2.origin}</span>
                <span style={{ fontSize: 11, color: '#5a7366' }}>{t2.destination}</span>
              </div>
            </div>
          )}

          {/* Events */}
          {trip.events.length === 0 ? (
            <EmptyState message="Aún no hay eventos registrados para este viaje." />
          ) : (
            <div style={{ position: 'relative' }}>
              <div style={{ position: 'absolute', left: 14, top: 0, bottom: 0, width: 2, background: '#e8f0ec' }}/>
              {t2.events.map((ev, i) => {
                const meta = eventIcons[ev.type] || eventIcons.checkpoint;
                return (
                  <div key={i} style={{ display: 'flex', gap: 16, marginBottom: 20, position: 'relative' }}>
                    <div style={{ width: 30, height: 30, borderRadius: '50%', background: meta.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, color: meta.color, fontWeight: 800, flexShrink: 0, zIndex: 1 }}>
                      {meta.icon}
                    </div>
                    <div style={{ flex: 1, paddingTop: 4 }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <span style={{ fontSize: 14, fontWeight: 600, color: '#1a2e25' }}>{ev.label}</span>
                        <span style={{ fontSize: 12, color: '#5a7366', fontFamily: 'monospace' }}>{ev.time}</span>
                      </div>
                      <div style={{ fontSize: 13, color: '#5a7366', marginTop: 2 }}>{ev.detail}</div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* Sidebar info */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {/* Driver card */}
          <div style={{ background: '#fff', borderRadius: 12, padding: '18px 20px', boxShadow: '0 1px 4px rgba(0,0,0,.06)' }}>
            <div style={{ fontSize: 11, color: '#5a7366', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.05em', marginBottom: 12 }}>Conductor</div>
            <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginBottom: 14 }}>
              <div style={{ width: 44, height: 44, borderRadius: '50%', background: '#dcfce7', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16, fontWeight: 700, color: '#15803d' }}>
                {(drv?.name || '?').split(' ').map(n => n[0]).join('').slice(0, 2)}
              </div>
              <div>
                <div style={{ fontSize: 14, fontWeight: 700, color: '#1a2e25' }}>{drv?.name}</div>
                <div style={{ fontSize: 12, color: '#5a7366' }}>{drv?.license}</div>
              </div>
            </div>
            <div style={{ fontSize: 12, color: '#5a7366', marginBottom: 4 }}>Score de rendimiento</div>
            <ProgressBar value={drv?.score || 0} />
            <div style={{ fontSize: 13, fontWeight: 700, color: '#1a2e25', marginTop: 4 }}>{drv?.score}%</div>
          </div>

          {/* Truck card */}
          <div style={{ background: '#fff', borderRadius: 12, padding: '18px 20px', boxShadow: '0 1px 4px rgba(0,0,0,.06)' }}>
            <div style={{ fontSize: 11, color: '#5a7366', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.05em', marginBottom: 12 }}>Camión</div>
            {[
              ['Placa', trk?.plate],
              ['Modelo', trk?.model],
              ['Año', trk?.year],
              ['Capacidad', trk?.capacity],
              ['Kilometraje', `${(trk?.km || 0).toLocaleString()} km`],
            ].map(([k, v], i) => (
              <div key={i} style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', borderBottom: i < 4 ? '1px solid #f0f4f2' : 'none' }}>
                <span style={{ fontSize: 12, color: '#5a7366' }}>{k}</span>
                <span style={{ fontSize: 12, fontWeight: 600, color: '#1a2e25' }}>{v}</span>
              </div>
            ))}
          </div>

          {/* Cargo */}
          <div style={{ background: '#fff', borderRadius: 12, padding: '18px 20px', boxShadow: '0 1px 4px rgba(0,0,0,.06)' }}>
            <div style={{ fontSize: 11, color: '#5a7366', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.05em', marginBottom: 8 }}>Carga</div>
            <div style={{ fontSize: 14, color: '#1a2e25', fontWeight: 600 }}>{t2.cargo}</div>
          </div>
        </div>
      </div>
    </PageShell>
    </>
  );
}

// ── Fleet ─────────────────────────────────────────────────────────
function ScreenFleet({ onNavigate }) {
  const { trucks, drivers } = ROUTING_DATA;
  const [filter, setFilter] = useState2('todos');

  const filterOpts = [
    { value: 'todos', label: 'Todos' },
    { value: 'en_ruta', label: 'En ruta' },
    { value: 'disponible', label: 'Disponible' },
    { value: 'mantenimiento', label: 'Mantenimiento' },
  ];

  const filtered = trucks.filter(t => filter === 'todos' || t.status === filter);

  const statusColors = { en_ruta: '#10B981', disponible: '#3B82F6', mantenimiento: '#F59E0B' };

  return (
    <PageShell title="Flota" sub={`${trucks.length} camiones registrados`}
      actions={<Btn small>+ Registrar camión</Btn>}
    >
      {/* Summary row */}
      <div style={{ display: 'flex', gap: 14, marginBottom: 24 }}>
        {['en_ruta', 'disponible', 'mantenimiento'].map(s => {
          const count = trucks.filter(t => t.status === s).length;
          const meta = statusMeta[s];
          return (
            <div key={s} onClick={() => setFilter(filter === s ? 'todos' : s)}
              style={{ background: '#fff', borderRadius: 10, padding: '14px 18px', cursor: 'pointer', flex: 1, borderTop: `3px solid ${statusColors[s]}`, boxShadow: filter === s ? `0 0 0 2px ${statusColors[s]}` : '0 1px 4px rgba(0,0,0,.06)', transition: 'box-shadow .15s' }}>
              <div style={{ fontSize: 24, fontWeight: 700, color: '#1a2e25' }}>{count}</div>
              <div style={{ fontSize: 12, color: '#5a7366', marginTop: 2 }}>{meta.label}</div>
            </div>
          );
        })}
      </div>

      {/* Truck grid */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 16 }}>
        {filtered.map(truck => {
          const drv = truck.driver ? drivers.find(d => d.id === truck.driver) : null;
          const sc = statusColors[truck.status] || '#94a3b8';
          return (
            <div key={truck.id} style={{ background: '#fff', borderRadius: 12, padding: '18px 20px', boxShadow: '0 1px 4px rgba(0,0,0,.06)', borderLeft: `4px solid ${sc}` }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 12 }}>
                <div>
                  <div style={{ fontSize: 18, fontWeight: 800, color: '#1a2e25', fontFamily: 'monospace' }}>{truck.plate}</div>
                  <div style={{ fontSize: 13, color: '#5a7366', marginTop: 2 }}>{truck.model} · {truck.year}</div>
                </div>
                <Chip status={truck.status} small />
              </div>
              {[
                ['Capacidad', truck.capacity],
                ['Kilometraje', `${truck.km.toLocaleString()} km`],
                ['Conductor', drv?.name || <span style={{ color: '#94a3b8' }}>Sin asignar</span>],
              ].map(([k, v], i) => (
                <div key={i} style={{ display: 'flex', justifyContent: 'space-between', padding: '5px 0', borderBottom: i < 2 ? '1px solid #f0f4f2' : 'none' }}>
                  <span style={{ fontSize: 12, color: '#5a7366' }}>{k}</span>
                  <span style={{ fontSize: 12, fontWeight: 600, color: '#1a2e25' }}>{v}</span>
                </div>
              ))}
            </div>
          );
        })}
      </div>
    </PageShell>
  );
}

Object.assign(window, { ScreenTrips, ScreenTripDetail, ScreenFleet });
