// ─── Rutas: bandeja (por planear) + ruta del día (ejecutar) ──────────────
// Dos pestañas:
//   • Por planear → bandeja de trabajo sin secuenciar:
//       - Entregas listas (derivadas de lo ya recogido, con su estado SLA)
//       - Recogidas solicitadas (creadas por admin; mañana, por los talleres)
//     El mensajero multiselecciona y "Agrega a su ruta": la app agrupa por
//     taller y ordena por cercanía. Cero captura de datos para entregas.
//   • Mi ruta → la secuencia ordenada del día (iniciar/completar cada parada).
//     Vista admin: progreso de ruta (parada X de Y, qué falta, recoge/entrega).
//
// Modelo Parada {
//   id, fecha (DD/MM/YYYY), asignadoA,
//   tipo: 'recoger' | 'entregar' | 'otro',
//   tallerId?, taller, sede, direccion, ciudad, lat, lng,
//   referencia, consecutivos? (['6024',...] para entregas), ticketIds?,
//   estado: 'solicitud' | 'pendiente' | 'en_curso' | 'completada' | 'cancelada',
//   creadaPor, prioridad, notas, createdAt, updatedAt, iniciadaEn?, completadaEn?,
// }
//   estado 'solicitud' = en la bandeja (aún sin planear)
//   estado 'pendiente' = ya en la ruta del día, por iniciar

// Talleres con coordenadas + usuarios (encargados) — Cali aprox.
const TALLERES_COORDS = [
{ id: 'arautos-sur', nombre: 'Arautos', sede: 'Sur', direccion: 'Cra. 67 #3C-18', ciudad: 'Cali',
  lat: 3.4112, lng: -76.5430, telefono: '+57 602 555 1001',
  usuarios: [
  { id: 'u1', nombre: 'Sebastián López', cargo: 'Jefe de Taller', telefono: '+57 300 555 4101' },
  { id: 'u2', nombre: 'Andrea Mejía', cargo: 'Asistente de Siniestros', telefono: '+57 311 555 4102' }]

},
{ id: 'almotor-norte', nombre: 'Almotores', sede: 'Kia', direccion: 'Calle 70 N No. 2A-280', ciudad: 'Cali',
  lat: 3.4760, lng: -76.5114, telefono: '+57 602 555 1002',
  usuarios: [
  { id: 'u1', nombre: 'Carlos Ramírez', cargo: 'Coordinador de Siniestros', telefono: '+57 312 555 4201' },
  { id: 'u2', nombre: 'Diana Castaño', cargo: 'Asistente Administrativa', telefono: '+57 315 555 4202' },
  { id: 'u3', nombre: 'Esteban Riascos', cargo: 'Jefe de Latonería', telefono: '+57 314 555 4203' }]

},
{ id: 'renovautos', nombre: 'Renovautos', sede: 'Sur', direccion: 'Cra. 43 #9A-27', ciudad: 'Cali',
  lat: 3.4498, lng: -76.5170, telefono: '+57 602 555 1003',
  usuarios: [
  { id: 'u1', nombre: 'Margarita Vélez', cargo: 'Gerente de Operaciones', telefono: '+57 318 555 4301' },
  { id: 'u2', nombre: 'Felipe Granada', cargo: 'Jefe de Taller', telefono: '+57 313 555 4302' }]

}];

const CITY_CENTER = { lat: 3.4516, lng: -76.5320 }; // Cali

// Coordenadas aproximadas para los talleres de los registros demo que no están
// en el catálogo rico de arriba. Clave: "nombre|sede" en minúsculas. Permite
// ubicar las entregas en el mapa y ordenarlas por cercanía.
const DEMO_TALLER_COORDS = {
  'almotores|volkswagen': { lat: 3.3905, lng: -76.5380, direccion: 'Cra. 39 #10-22' },
  'mazko|sur': { lat: 3.4020, lng: -76.5300, direccion: 'Cra. 50 #5-19' },
  'mazko|norte': { lat: 3.4790, lng: -76.5180, direccion: 'Av. 6N #28-15' },
  'autopacífico|norte': { lat: 3.4516, lng: -76.5320, direccion: 'Calle 15 #8-44' },
  'autosuperior|norte': { lat: 3.4705, lng: -76.5240, direccion: 'Calle 80 #2N-30' },
  'coches de la sabana|8va': { lat: 3.4750, lng: -76.5150, direccion: 'Av. 3N #45-10' }
};
// Resuelve coordenadas + dirección para un taller dado (nombre + sede).
function tallerCoords(taller, sede) {
  if (window.esParticular && window.esParticular(taller)) return { lat: null, lng: null, direccion: '', ciudad: 'Cali', tallerId: null };
  // Catálogo (13/11/2026): si la sede tiene ubicación guardada, manda.
  const cu = window.catUbicacion ? window.catUbicacion(taller, sede) : null;
  if (cu && cu.lat != null && cu.lng != null) return { lat: cu.lat, lng: cu.lng, direccion: cu.direccion || sede || '', ciudad: cu.ciudad, tallerId: null };
  const nombre = String(taller || '').toLowerCase().trim();
  const sd = String(sede || '').toLowerCase().trim();
  const cat = TALLERES_COORDS.find((x) =>
  x.nombre.toLowerCase() === nombre && x.sede.toLowerCase() === sd
  ) || TALLERES_COORDS.find((x) => x.nombre.toLowerCase() === nombre);
  if (cat) return { lat: cat.lat, lng: cat.lng, direccion: cat.direccion, ciudad: cat.ciudad, tallerId: cat.id };
  const d = DEMO_TALLER_COORDS[`${nombre}|${sd}`];
  if (d) return { ...d, ciudad: 'Cali', tallerId: null };
  return { lat: CITY_CENTER.lat, lng: CITY_CENTER.lng, direccion: sede || '', ciudad: 'Cali', tallerId: null };
}

// Catálogo Taller → Sedes: viene de catalogo.jsx (13/11/2026), solo talleres activos.
function talleresSedes() { return window.catTalleresSedes ? window.catTalleresSedes() : []; }
// 25/11/2026: para recoger, solo las sedes en ciudades donde el mensajero recoge.
function sedesRutaM(nombre) { return window.catSedesRuta ? window.catSedesRuta(nombre) : sedesDe(nombre); }
function sedesDe(nombre) {
  const t = talleresSedes().find((x) => x.nombre === nombre);
  return t ? t.sedes : [];
}

const MENSAJEROS = [
{ id: 'juan-diego', nombre: 'Juan Diego', avatar: 'JD' }];


// Etiqueta SLA corta (singular) para una entrega.
const SLA_LABEL = { aldia: 'Al día', atrasado: 'Atrasado', critico: 'Crítico' };

// ─── Storage ────────────────────────────────────────────────────────────
const LS_PARADAS_KEY = 'rodando.paradas.v2';
// Mensajero por defecto: el primero con rol mensajero (los datos viejos decían 'juan-diego').
function mensajeroPorDefecto() { const m = window.mensajerosApp ? window.mensajerosApp()[0] : null; return m ? m.usuario : 'cesar'; }
function loadParadas() {
  let list = [];
  try {list = JSON.parse(localStorage.getItem(LS_PARADAS_KEY) || '[]');}
  catch {return [];}
  // Migración (13/11/2026): rutas asignadas a 'juan-diego' pasan al mensajero real.
  if (list.some((p) => p.asignadoA === 'juan-diego')) {
    const def = mensajeroPorDefecto();
    list = list.map((p) => p.asignadoA === 'juan-diego' ? { ...p, asignadoA: def } : p);
    try {localStorage.setItem(LS_PARADAS_KEY, JSON.stringify(list));} catch (e) {}
  }
  return window.catCanonObj ? list.map(window.catCanonObj) : list; // 26/11/2026: talleres unidos
}
function saveParadas(list) {
  localStorage.setItem(LS_PARADAS_KEY, JSON.stringify(list));
  // Aviso en vivo a cualquier vista abierta (supervisión del admin, etc.)
  try {window.dispatchEvent(new Event('rodando-paradas'));} catch (e) {}
}
function addParada(p) {
  const list = loadParadas();
  list.unshift(p);
  saveParadas(list);
  return p;
}
function updateParada(id, patch) {
  const list = loadParadas();
  const idx = list.findIndex((p) => p.id === id);
  if (idx === -1) return false;
  list[idx] = { ...list[idx], ...patch, updatedAt: Date.now() };
  saveParadas(list);
  return list[idx];
}
function removeParada(id) {
  saveParadas(loadParadas().filter((p) => p.id !== id));
}
function clearParadas() {localStorage.removeItem(LS_PARADAS_KEY);}

// ─── Roll-over + cierre de jornada ───────────────────────────────────────
// Política: lo que NO se termina NO se arrastra solo a la ruta del día
// siguiente. Vuelve a la bandeja "Por planear" para que el mensajero (o el
// admin) decida si lo reprograma o lo descarta. Nada se pierde en silencio.

// Devuelve una parada sin terminar a la bandeja.
//  • Entregas → se elimina la parada; la entrega reaparece sola en
//    "Entregas listas" (esa lista se deriva de lo pendiente por entregar).
//  • Recogidas / otros → vuelven a estado 'solicitud' con la fecha de hoy,
//    marcadas como "arrastrada" para que se note de dónde vienen.
function devolverParadaABandeja(parada) {
  if (!parada) return;
  if (parada.tipo === 'entregar' || parada.tipo === 'encargo') {removeParada(parada.id);return;}
  updateParada(parada.id, {
    estado: 'solicitud',
    fecha: fechaDDMMYYYY(),
    arrastrada: true,
    fechaOriginal: parada.fechaOriginal || parada.fecha,
    iniciadaEn: null,
    orden: null
  });
}

// Red de seguridad: al abrir Rutas un día nuevo, cualquier parada de días
// anteriores que quedó 'pendiente' o 'en_curso' vuelve a la bandeja (por si
// no se cerró la jornada manualmente). Devuelve cuántas se arrastraron.
function rolloverParadasIfNeeded() {
  const hoy = fechaDDMMYYYY();
  const viejas = loadParadas().filter((p) =>
  p.fecha !== hoy && (p.estado === 'pendiente' || p.estado === 'en_curso'));
  viejas.forEach(devolverParadaABandeja);
  return viejas.length;
}

// Marca de cierre manual de jornada (por día).
const LS_JORNADA_KEY = 'rodando.jornadaCerrada';
function jornadaCerradaFecha() {
  try {return localStorage.getItem(LS_JORNADA_KEY) || '';} catch (e) {return '';}
}
function isJornadaCerrada() {return jornadaCerradaFecha() === fechaDDMMYYYY();}
function marcarJornadaCerrada(fecha) {
  try {localStorage.setItem(LS_JORNADA_KEY, fecha || fechaDDMMYYYY());} catch (e) {}
}
function reabrirJornada() {
  try {localStorage.removeItem(LS_JORNADA_KEY);} catch (e) {}
}

// Seed demo: deja la bandeja y la ruta con material para mostrar ambos lados.
function seedDemoParadasIfEmpty() {
  if (loadParadas().length > 0 || localStorage.getItem('rodando.sinDemo') === '1') return;
  const hoy = fechaDDMMYYYY();
  const now = Date.now();
  const mk = (taller, sede, tipo, extra) => {
    const co = tallerCoords(taller, sede);
    return {
      tipo, taller, sede, tallerId: co.tallerId,
      direccion: co.direccion, ciudad: co.ciudad, lat: co.lat, lng: co.lng,
      fecha: hoy, asignadoA: mensajeroPorDefecto(), createdAt: now, updatedAt: now,
      prioridad: 'normal', notas: '', ...extra
    };
  };
  const seed = [
  // ── Ya en la ruta del día ──
  mk('Almotores', 'Kia', 'entregar', {
    id: 'p-seed-r1', consecutivos: ['6024'], referencia: '6024',
    estado: 'pendiente', creadaPor: 'admin', prioridad: 'alta', orden: 0
  }),
  mk('Renovautos', 'Sur', 'recoger', {
    id: 'p-seed-r2', referencia: 'Recogida — 4 rines y llantas', placas: ['KLM123', 'HTR552'],
    estado: 'pendiente', creadaPor: 'admin', orden: 1,
    notas: 'Margarita confirma que el vehículo ya está listo.'
  }),
  mk('Mazko', 'Sur', 'entregar', {
    id: 'p-seed-r3', consecutivos: ['6023'], referencia: '6023',
    estado: 'completada', creadaPor: 'mensajero', orden: 2,
    iniciadaEn: now - 1000 * 60 * 95, completadaEn: now - 1000 * 60 * 70
  }),
  // ── En la bandeja (por planear) ──
  mk('Arautos', 'Sur', 'recoger', {
    id: 'p-seed-b1', referencia: 'Recogida solicitada — 4 rines', placas: ['IVP394'],
    estado: 'solicitud', creadaPor: 'admin',
    notas: 'Sebastián avisa que estará en el taller hasta las 5 pm.'
  }),
  mk('Almotores', 'Kia', 'recoger', {
    id: 'p-seed-b2', referencia: 'Recogida solicitada — 2 llantas', placas: ['HTR552'],
    estado: 'solicitud', creadaPor: 'admin', prioridad: 'alta',
    notas: 'Urgente, el taller cierra a mediodía.'
  })];

  saveParadas(seed);
}

// ─── Distance helper (haversine, in meters) ──────────────────────────────
function distanceMeters(a, b) {
  if (!a || !b) return Infinity;
  const R = 6371000;
  const toRad = (d) => d * Math.PI / 180;
  const dLat = toRad(b.lat - a.lat);
  const dLng = toRad(b.lng - a.lng);
  const sa = Math.sin(dLat / 2) ** 2 +
  Math.cos(toRad(a.lat)) * Math.cos(toRad(b.lat)) * Math.sin(dLng / 2) ** 2;
  return 2 * R * Math.asin(Math.sqrt(sa));
}
function formatDistance(m) {
  if (!isFinite(m)) return '—';
  return m < 1000 ? `${Math.round(m)} m` : `${(m / 1000).toFixed(1)} km`;
}

// ─── WhatsApp share helpers ─────────────────────────────────────────────
// 24/11/2026: mensaje de WhatsApp de una tarea (estilo mixto): 🆕 NUEVA TAREA, tipo en negrita,
// ❗ PRIORIDAD si aplica, etiquetas en negrita, placas en letra de máquina, 📍 antes del enlace de Maps
// y 📝 en la nota. Las líneas que no aplican no salen.
function tareaWhatsAppTexto(d) {
  const T = { placas: 'RECOGER PLACAS', recoger: 'RECOGER', entregar: 'ENTREGAR', hacer: 'HACER' }[d.tipo] || 'TAREA';
  const L = [d.nuevo === false ? '*TAREA*' : '🆕 *NUEVA TAREA*', `*${T}*`];
  if (d.prioridad) L.push('❗ *PRIORIDAD*');
  L.push('');
  const pls = (d.placas || []).filter(Boolean);
  if (d.tipo !== 'placas' && d.que) L.push(`*Qué:* ${d.que}`);
  if (pls.length) L.push(`*${pls.length > 1 ? 'Placas' : 'Placa'}:* ${pls.map((x) => '```' + x + '```').join('  ')}`);
  if (d.tipo === 'placas' && d.que) L.push(`*Qué:* ${d.que}`);
  const hayLugar = d.cliente || d.donde || d.direccion;
  if (hayLugar) {
    L.push('');
    if (d.cliente) { L.push(`*Cliente particular:* ${d.cliente.nombre}`); if (d.cliente.telefono) L.push(`*Tel:* ${d.cliente.telefono}`); if (d.cliente.direccion) L.push(`*Dirección:* ${d.cliente.direccion}`); } else {
      if (d.donde) L.push(`*Dónde:* ${d.donde}`);
      if (d.direccion && d.direccion !== d.donde) L.push(`*Dirección:* ${d.direccion}`);
    }
    const q = d.lat != null && d.lng != null ? `${d.lat},${d.lng}` : encodeURIComponent([(d.cliente && d.cliente.direccion) || d.direccion || d.donde, 'Cali'].filter(Boolean).join(', '));
    L.push(`📍 https://maps.google.com/?q=${q}`);
  }
  L.push('');
  if (d.para) L.push(`*Para:* ${d.para}`);
  if (d.asignada) L.push(`*Asignada a:* ${d.asignada}`);
  if (d.nota) { L.push(''); L.push(`📝 *Nota:* ${d.nota}`); }
  return L.join('\n').replace(/\n{3,}/g, '\n\n').trim();
}
function paraTxtDeFecha(f) {
  const hoy = fechaDDMMYYYY(); const m = new Date(); m.setDate(m.getDate() + 1);
  const limpia = (x) => String(x || '').replace(/\s/g, '');
  if (!f || limpia(f) === limpia(hoy)) return 'hoy';
  if (limpia(f) === limpia(fechaDDMMYYYY(m))) return 'mañana';
  return limpia(f).slice(0, 5);
}
function buildParadaWhatsAppText(parada, nuevo) {
  const mensajero = (window.nombreDeUsuario && window.nombreDeUsuario(parada.asignadoA)) || (MENSAJEROS.find((m) => m.id === parada.asignadoA) || {}).nombre || parada.asignadoA;
  const tks = parada.tipo === 'entregar' ? tareaPlacas(parada).map((x) => x.placa).filter(Boolean) : (parada.placas || []);
  const enc = parada.tipo === 'encargo' && window.loadEncargos ? window.loadEncargos().find((e) => e.id === parada.encargoId) : null;
  return tareaWhatsAppTexto({
    nuevo: nuevo !== false, tipo: parada.tipo === 'recoger' ? 'placas' : parada.tipo === 'entregar' ? 'entregar' : enc ? enc.tipo : 'hacer',
    prioridad: parada.prioridad === 'alta', placas: tks, que: enc ? enc.que : parada.tipo === 'entregar' ? '' : parada.referencia,
    cliente: parada.cliente, donde: parada.cliente ? '' : [parada.taller, parada.sede].filter(Boolean).join(' · '), direccion: parada.direccion,
    lat: parada.lat, lng: parada.lng, para: paraTxtDeFecha(parada.fecha), asignada: mensajero, nota: parada.notas
  });
}
function buildWhatsAppShareUrl(text) {
  return `https://wa.me/?text=${encodeURIComponent(text)}`;
}
// Compartir nativo del sistema (permite elegir un GRUPO de WhatsApp). Si no
// está disponible (desktop sin share), copia el mensaje y abre WhatsApp Web.
async function shareParadaToWhatsApp(parada, nuevo) {
  const text = buildParadaWhatsAppText(parada, nuevo);
  if (navigator.share) {
    try {await navigator.share({ text });return;}
    catch (e) {if (e && e.name === 'AbortError') return;}
  }
  let copiado = false;
  try {await navigator.clipboard.writeText(text);copiado = true;} catch (e) {}
  window.open(buildWhatsAppShareUrl(text), '_blank', 'noopener,noreferrer');
  if (copiado) {
    setTimeout(() => alert('Mensaje copiado. Pégalo en el grupo de WhatsApp (Ctrl/Cmd+V).'), 60);
  }
}
// Abre la navegación en la app de mapas del teléfono (Google Maps / Waze),
// según la preferencia guardada en Ajustes.
function openInMaps(parada) {
  const pref = window.loadPrefs ? window.loadPrefs().mapa : 'google';
  const url = pref === 'waze' ?
  `https://waze.com/ul?ll=${parada.lat},${parada.lng}&navigate=yes` :
  `https://maps.google.com/?q=${parada.lat},${parada.lng}`;
  window.open(url, '_blank', 'noopener,noreferrer');
}

// Inline WhatsApp icon (no external dep)
const WA_ICON = (s = 16, c = '#fff') =>
<svg width={s} height={s} viewBox="0 0 24 24" fill={c}>
    <path d="M12 .5C5.65.5.5 5.65.5 12c0 2.12.55 4.17 1.6 5.98L.5 23.5l5.7-1.5A11.46 11.46 0 0 0 12 23.5c6.35 0 11.5-5.15 11.5-11.5S18.35.5 12 .5zm0 21c-1.85 0-3.67-.5-5.25-1.43l-.38-.22-3.4.9.9-3.32-.25-.4A9.46 9.46 0 0 1 2.5 12c0-5.24 4.26-9.5 9.5-9.5s9.5 4.26 9.5 9.5-4.26 9.5-9.5 9.5zm5.2-7.1c-.28-.14-1.66-.82-1.92-.92-.26-.1-.45-.14-.64.14-.19.28-.74.93-.9 1.12-.17.19-.33.21-.61.07-.28-.14-1.18-.43-2.25-1.39-.83-.74-1.39-1.66-1.55-1.93-.16-.28-.02-.43.12-.57.13-.13.28-.33.42-.5.14-.16.19-.28.28-.47.09-.19.05-.35-.02-.49-.07-.14-.64-1.55-.88-2.12-.23-.55-.46-.47-.64-.48l-.55-.01c-.19 0-.49.07-.74.35-.26.28-.97.95-.97 2.31s.99 2.68 1.13 2.87c.14.19 1.95 2.97 4.71 4.16.66.28 1.17.45 1.57.58.66.21 1.26.18 1.73.11.53-.08 1.66-.68 1.9-1.33.23-.66.23-1.22.16-1.33-.07-.12-.26-.19-.54-.33z" />
  </svg>;


// ─── Mini Leaflet map wrapper ────────────────────────────────────────────
function MapView({ markers = [], currentLocation = null, height = 200, fitBounds = false }) {
  const ref = React.useRef(null);
  const mapRef = React.useRef(null);
  const layersRef = React.useRef([]);

  React.useEffect(() => {
    if (!ref.current || mapRef.current || !window.L) return;
    const map = window.L.map(ref.current, {
      zoomControl: false, attributionControl: false, dragging: true, tap: true
    }).setView([CITY_CENTER.lat, CITY_CENTER.lng], 12);
    window.L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19 }).addTo(map);
    mapRef.current = map;
    setTimeout(() => map.invalidateSize(), 100);
    return () => {map.remove();mapRef.current = null;};
  }, []);

  React.useEffect(() => {
    const map = mapRef.current;
    if (!map || !window.L) return;
    layersRef.current.forEach((l) => l.remove());
    layersRef.current = [];
    const bounds = [];
    markers.forEach((m, idx) => {
      const color = m.color || TOKENS.primary;
      const html = `
        <div style="
          background:${color}; color:#fff; border-radius:999px;
          width:30px; height:30px; display:flex; align-items:center; justify-content:center;
          font-weight:700; font-size:13px; box-shadow:0 2px 6px rgba(0,0,0,0.3);
          border: 2px solid #fff;
        ">${m.label || idx + 1}</div>`;
      const icon = window.L.divIcon({ className: '', html, iconSize: [30, 30], iconAnchor: [15, 15] });
      const marker = window.L.marker([m.lat, m.lng], { icon }).addTo(map);
      if (m.popup) marker.bindPopup(m.popup);
      layersRef.current.push(marker);
      bounds.push([m.lat, m.lng]);
    });
    if (currentLocation) {
      const c = window.L.circleMarker([currentLocation.lat, currentLocation.lng], {
        color: '#fff', fillColor: TOKENS.primary, fillOpacity: 1, weight: 3, radius: 8
      }).addTo(map);
      layersRef.current.push(c);
      bounds.push([currentLocation.lat, currentLocation.lng]);
    }
    if (fitBounds && bounds.length > 1) map.fitBounds(bounds, { padding: [30, 30] });else
    if (bounds.length === 1) map.setView(bounds[0], 14);
  }, [markers, currentLocation, fitBounds]);

  return (
    <div ref={ref} style={{
      width: '100%', height, borderRadius: 12, overflow: 'hidden',
      border: `1px solid ${TOKENS.border}`, background: TOKENS.surfaceLow
    }} />);

}

// ─── Main screen: Rutas ──────────────────────────────────────────────────
// Memoria de Rutas (18/11/2026): al abrir una placa desde Por planear y volver, todo queda
// como estaba (pestaña, Por entregar/recoger, búsqueda, grupos abiertos, selección y scroll).
const RUTAS_MEMO = window.__rdRutasMemo || (window.__rdRutasMemo = {});
function rutasGuardarScroll() {
  const pf = document.getElementById('rd-phone-frame');
  const cands = [document.scrollingElement, pf, ...(pf ? pf.querySelectorAll('*') : [])].filter(Boolean);
  const el = cands.find((e) => e.scrollTop > 0);
  RUTAS_MEMO.scroll = el ? { el, top: el.scrollTop } : null;
}
function RutasScreen({ role, onBack, onNav, onIniciarRecoger, onIniciarEntregar, onVerEntrega }) {
  const isAdmin = role === 'admin';
  const [paradas, setParadas] = React.useState(loadParadas());
  const [tab, setTabSt] = React.useState(RUTAS_MEMO.tab || 'ruta'); // 'planear' | 'ruta'
  const setTab = (t) => { RUTAS_MEMO.tab = t; setTabSt(t); };
  React.useEffect(() => {
    if (!RUTAS_MEMO.volver) return;
    RUTAS_MEMO.volver = false;
    const sc = RUTAS_MEMO.scroll;
    if (sc && sc.el && sc.el.isConnected) [60, 200].forEach((ms) => setTimeout(() => { try { sc.el.scrollTop = sc.top; } catch (e) {} }, ms));
  }, []);
  const [selectedId, setSelectedId] = React.useState(null);
  const [showNew, setShowNew] = React.useState(false);
  const [location, setLocation] = React.useState(null);
  const [locationStatus, setLocationStatus] = React.useState('idle');
  const [sel, setSel] = React.useState(() => new Set(RUTAS_MEMO.sel || [])); // bandeja multiselección
  React.useEffect(() => { RUTAS_MEMO.sel = [...sel]; }, [sel]);
  const [notice, setNotice] = React.useState(null); // {text, tone}
  const [finalizando, setFinalizando] = React.useState(null); // destino en validación de cierre
  const [cerrandoJornada, setCerrandoJornada] = React.useState(false);

  // Mensajeros que el admin puede supervisar. Hoy hay uno; estructura lista
  // para varios (selector). El nombre del único mensajero sigue al perfil.
  const couriers = (window.mensajerosApp ? window.mensajerosApp() : []).map((u) => ({ id: u.usuario, nombre: u.nombre }));
  if (!couriers.length) couriers.push({ id: mensajeroPorDefecto(), nombre: 'Mensajero' });
  const [selCourier, setSelCourier] = React.useState(couriers[0].id);
  const courierActual = couriers.find((c) => c.id === selCourier) || couriers[0];

  const refresh = React.useCallback(() => setParadas(loadParadas()), []);
  React.useEffect(() => {
    window.addEventListener('rodando-paradas', refresh);
    window.addEventListener('storage', refresh);
    window.addEventListener('focus', refresh);
    // El admin supervisa en vivo: refresco periódico de respaldo (otra pestaña).
    const poll = isAdmin ? setInterval(refresh, 2000) : null;
    return () => {
      window.removeEventListener('rodando-paradas', refresh);
      window.removeEventListener('storage', refresh);
      window.removeEventListener('focus', refresh);
      if (poll) clearInterval(poll);
    };
  }, [refresh, isAdmin]);

  const hoy = fechaDDMMYYYY();
  // El mensajero ve su propia ruta; el admin ve la del mensajero seleccionado.
  const yoUsuario = (window.usuarioActual && window.usuarioActual() || {}).usuario || mensajeroPorDefecto();
  const userId = isAdmin ? selCourier : yoUsuario;
  const mine = paradas.filter((p) => p.fecha === hoy && p.asignadoA === userId);

  // Aviso al mensajero cuando el admin cambia su plan de ruta.
  const notifyCourier = (titulo, mensaje, extra = {}) => {
    if (!isAdmin || !window.addNotif) return;
    const base = {
      id: 'n-' + Date.now() + '-' + Math.random().toString(36).slice(2, 6),
      tipo: 'ruta_update', para: 'mensajero', paraUsuario: selCourier, estado: 'pendiente',
      titulo, mensaje, actor: 'admin', createdAt: Date.now(), resolucion: null,
      ...extra
    };
    if (window.addOrCoalesceNotif) window.addOrCoalesceNotif(base, 'ruta_update:mensajero:' + selCourier);
    else window.addNotif(base);
  };

  // ── Bandeja: recogidas solicitadas + entregas derivadas de lo recogido ──
  const recogidasBandeja = mine.filter((p) => p.estado === 'solicitud');

  const enRutaCodigos = new Set();
  mine.filter((p) => p.tipo === 'entregar' && p.estado !== 'cancelada').
  forEach((p) => (p.consecutivos || []).forEach((c) => enRutaCodigos.add(String(c))));
  const deliveredIds = new Set((window.loadEntregados ? window.loadEntregados() : []).map((e) => e.ticketId));
  const allPendientes = [...(window.loadPendientesSaved ? window.loadPendientesSaved() : []), ...(window.PENDIENTES_DEMO || [])];
  const entregasBandeja = allPendientes.
  filter((t) => !deliveredIds.has(t.id) && !enRutaCodigos.has(String(t.codigo))).
  map((t) => {
    const co = tallerCoords(t.taller, t.sede);
    const sev = window.ticketSeverity ? window.ticketSeverity(t) : { level: 'aldia', dias: 0 };
    return { ...t, ...co, severity: sev };
  }).
  sort((a, b) => {
    const rank = { critico: 0, atrasado: 1, aldia: 2 };
    const ra = rank[a.severity.level] ?? 9,rb = rank[b.severity.level] ?? 9;
    if (ra !== rb) return ra - rb;
    return b.severity.dias - a.severity.dias;
  });

  // Garantías por entregar (18/11/2026): rines que el taller devolvió y hay que llevar de nuevo.
  // Salen de la bandeja mientras estén en una parada pendiente o en curso.
  const enRutaGar = new Set();
  mine.filter((p) => (p.estado === 'pendiente' || p.estado === 'en_curso') && p.garantias).
  forEach((p) => p.garantias.forEach((g) => enRutaGar.add(g.garId)));
  const garantiasBandeja = [];
  (window.loadEntregados ? window.loadEntregados() : []).forEach((e) => {
    const g = window.garantiaAbierta ? window.garantiaAbierta(e.ticketId) : null;
    if (g && !enRutaGar.has(g.id)) garantiasBandeja.push({ e, g, est: window.garEstado(g) });
  });
  garantiasBandeja.sort((a, b) => a.est.orden - b.est.orden || b.est.dias - a.est.dias);

  const encargosBandeja = encargosPlanDe(userId, paradas);
  const bandejaCount = recogidasBandeja.length + entregasBandeja.length + garantiasBandeja.length + encargosBandeja.length;

  // ── Mi ruta: paradas agrupadas por DESTINO (taller + sede) ──
  // Una tarjeta = un lugar a visitar; dentro van sus tareas (recoger/entregar).
  const ruta = mine.filter((p) => ['pendiente', 'en_curso', 'completada'].includes(p.estado));
  const destinos = groupByDestino(ruta).sort((a, b) => a.orden - b.orden);
  // La parada en curso se ancla arriba: es la que se está realizando.
  const activos = destinos.
  filter((d) => d.estado !== 'completada').
  sort((a, b) => {
    if (a.estado === 'en_curso' && b.estado !== 'en_curso') return -1;
    if (b.estado === 'en_curso' && a.estado !== 'en_curso') return 1;
    return a.orden - b.orden;
  });
  const completados = destinos.
  filter((d) => d.estado === 'completada').
  sort((a, b) => (b.completadaEn || 0) - (a.completadaEn || 0));
  const enCursoDestino = destinos.find((d) => d.estado === 'en_curso') || null;
  const totalDest = destinos.length;
  const stats = {
    pendiente: activos.filter((d) => d.estado === 'pendiente').length,
    enCurso: enCursoDestino ? 1 : 0,
    completada: completados.length
  };

  const requestLocation = () => {
    if (!navigator.geolocation) return;
    setLocationStatus('asking');
    navigator.geolocation.getCurrentPosition(
      (pos) => {setLocation({ lat: pos.coords.latitude, lng: pos.coords.longitude });setLocationStatus('ok');},
      () => setLocationStatus('denied'),
      { enableHighAccuracy: true, timeout: 8000 }
    );
  };

  const flash = (text, tone = 'success') => {setNotice({ text, tone });setTimeout(() => setNotice(null), 4500);};

  // Al abrir: siembra el demo + arrastra a la bandeja lo que quedó sin
  // terminar de días anteriores (red de seguridad por si no se cerró la
  // jornada manualmente).
  React.useEffect(() => {
    seedDemoParadasIfEmpty();
    const n = rolloverParadasIfNeeded();
    setParadas(loadParadas());
    if (n > 0) flash(
      `${n} ${n === 1 ? 'parada sin terminar' : 'paradas sin terminar'} de días anteriores ${n === 1 ? 'volvió' : 'volvieron'} a tu bandeja “Por planear”.`,
      'danger'
    );
  }, []);

  // ── Selección de bandeja ──
  const toggleMany = (keys, on) => setSel((prev) => {
    const next = new Set(prev);
    keys.forEach((k) => on ? next.add(k) : next.delete(k));
    return next;
  });
  // Talleres que ya están en la ruta de hoy (para "Ya vas para allá").
  const enRutaKeys = new Set(mine.filter((p) => p.estado === 'pendiente' || p.estado === 'en_curso').map((p) => `${p.taller}|${p.sede}`));
  const [confirmar, setConfirmar] = React.useState(null); // { title, message, label, run }
  const toggleSel = (key) => setSel((prev) => {
    const next = new Set(prev);
    next.has(key) ? next.delete(key) : next.add(key);
    return next;
  });
  const selRecogidas = recogidasBandeja.filter((p) => sel.has('sol:' + p.id));
  const selEntregas = entregasBandeja.filter((t) => sel.has('ent:' + t.codigo) && !(window.anulacionEnEspera && window.anulacionEnEspera(t.id)));
  // Cuántas paradas resultarán (entregas se agrupan por taller+sede)
  const selGarantias = garantiasBandeja.filter((x) => sel.has('gar:' + x.g.id));
  const grupos = new Set([...selEntregas.map((t) => `${t.taller}|${t.cliente ? t.cliente.nombre : t.sede}`), ...selGarantias.map((x) => `${x.e.taller}|${x.e.sede}`)]);
  const selEncargos = encargosBandeja.filter((e) => sel.has('enc:' + e.id));
  const paradasResultantes = selRecogidas.length + new Set([...grupos, ...selEncargos.map(encClave)]).size;

  const agregarARuta = () => {
    const base = Date.now();
    selRecogidas.forEach((p, i) => updateParada(p.id, { estado: 'pendiente', orden: base + i }));
    const byTaller = {};
    selEntregas.forEach((t) => {
      const k = `${t.taller}|${t.cliente ? t.cliente.nombre : t.sede}`;
      (byTaller[k] = byTaller[k] || []).push(t);
    });
    // Garantías: van en la misma parada del taller (una sola visita).
    const garTaller = {};
    selGarantias.forEach((x) => {
      const k = `${x.e.taller}|${x.e.sede}`;
      byTaller[k] = byTaller[k] || [];
      (garTaller[k] = garTaller[k] || []).push(x);
    });
    const now = Date.now();
    Object.entries(byTaller).forEach(([k, tks], i) => {
      const gs = garTaller[k] || [];
      const f = tks[0] ? { ...tks[0], sede: tks[0].cliente ? tks[0].cliente.nombre : tks[0].sede } : { taller: gs[0].e.taller, sede: gs[0].e.sede };
      const co = tallerCoords(f.taller, f.sede); if (tks[0] && tks[0].cliente) co.direccion = tks[0].cliente.direccion;
      addParada({
        id: 'p-ent-' + now + '-' + i, tipo: 'entregar',
        taller: f.taller, sede: f.sede, tallerId: co.tallerId,
        direccion: co.direccion, ciudad: co.ciudad, lat: co.lat, lng: co.lng,
        consecutivos: tks.map((x) => String(x.codigo)),
        ticketIds: tks.map((x) => x.id),
        referencia: [...tks.map((x) => '' + x.codigo), ...gs.map((x) => '' + x.e.codigo)].join(', '),
        garantias: gs.map((x) => ({ ticketId: x.e.ticketId, garId: x.g.id, codigo: String(x.e.codigo), placa: x.e.placa, rines: x.g.rines.length })),
        estado: 'pendiente', creadaPor: role === 'admin' ? 'admin' : 'mensajero',
        prioridad: 'normal', notas: '', fecha: hoy, asignadoA: userId,
        orden: now + 100 + i,
        createdAt: now, updatedAt: now
      });
    });
    selEncargos.forEach((e, i) => crearParadaEncargo(e, { asignadoA: userId, creadaPor: role === 'admin' ? 'admin' : 'mensajero', orden: now + 200 + i, fecha: hoy }));
    const n = selRecogidas.length + selEntregas.length + selGarantias.length + selEncargos.length;
    reabrirJornada(); // si se agrega trabajo, la jornada vuelve a estar abierta
    setParadas(loadParadas());
    setSel(new Set());
    setTab('ruta');
    if (isAdmin) notifyCourier(
      'El admin agregó paradas a tu ruta',
      `${paradasResultantes} ${paradasResultantes === 1 ? 'parada nueva' : 'paradas nuevas'} en tu ruta de hoy.`,
      { kind: 'add', detalle: `Agregó ${paradasResultantes} ${paradasResultantes === 1 ? 'parada' : 'paradas'}` }
    );
    flash(`${n} ${n === 1 ? 'tarea agregada' : 'tareas agregadas'} a ${isAdmin ? 'la ruta de ' + courierActual.nombre : 'tu ruta'} · ${paradasResultantes} ${paradasResultantes === 1 ? 'parada' : 'paradas'}.`);
  };

  // ── Acciones del ADMIN sobre el PLAN (solo paradas pendientes) ──
  // Repriorizar todas las tareas de un destino pendiente y avisar al mensajero.
  const handleReprioritizar = (destino) => {
    if (destino.estado !== 'pendiente') return;
    const nueva = destino.prioridad === 'alta' ? 'normal' : 'alta';
    destino.tareas.forEach((t) => updateParada(t.id, { prioridad: nueva }));
    setParadas(loadParadas());
    notifyCourier(
      'El admin cambió una prioridad',
      `${destino.taller}${destino.sede ? ' · ' + destino.sede : ''} ahora es prioridad ${nueva === 'alta' ? 'ALTA' : 'normal'}.`,
      { kind: 'priority', detalle: `${destino.taller}: prioridad ${nueva === 'alta' ? 'ALTA' : 'normal'}` }
    );
    flash(`Prioridad ${nueva === 'alta' ? 'alta' : 'normal'} · ${destino.taller}.`);
  };
  // Quitar un destino pendiente de la ruta: vuelve a la bandeja "Por planear".
  const handleQuitarDeRuta = (destino, ok) => {
    if (destino.estado !== 'pendiente') return;
    if (!ok) { setConfirmar({ title: `¿Quitar ${destino.taller} de la ruta?`, message: 'Volverá a "Por planear".', label: 'Quitar', run: () => handleQuitarDeRuta(destino, true) }); return; }
    destino.tareas.forEach((t) => devolverParadaABandeja(t));
    setParadas(loadParadas());
    notifyCourier(
      'El admin quitó una parada de tu ruta',
      `${destino.taller}${destino.sede ? ' · ' + destino.sede : ''} volvió a "Por planear".`,
      { kind: 'remove', detalle: `Quitó ${destino.taller}${destino.sede ? ' · ' + destino.sede : ''}` }
    );
    flash(`${destino.taller} volvió a la bandeja.`, 'danger');
  };

  // ── Acciones sobre paradas de la ruta ──
  const handleIniciar = (p) => {
    updateParada(p.id, { estado: 'en_curso', iniciadaEn: Date.now() });
    setParadas(loadParadas());
    setSelectedId(null);
    if (p.tipo === 'recoger' && onIniciarRecoger) onIniciarRecoger(p);else
    if (p.tipo === 'entregar' && onIniciarEntregar) onIniciarEntregar(p);
  };
  const handleCompletar = (p) => {
    updateParada(p.id, { estado: 'completada', completadaEn: Date.now() });
    setParadas(loadParadas());
    setSelectedId(null);
  };

  // ── Acciones a nivel DESTINO (la unidad real de la ruta) ──
  // Iniciar: marca en curso + arranca cronómetro. Máximo un destino en curso.
  const handleIniciarDestino = (destino) => {
    if (enCursoDestino && enCursoDestino.key !== destino.key) {
      flash('Ya tienes una parada en curso. Finalízala antes de iniciar otra.', 'danger');
      return;
    }
    const now = Date.now();
    destino.tareas.forEach((t) => {
      if (t.estado === 'pendiente') updateParada(t.id, { estado: 'en_curso', iniciadaEn: now });
    });
    setParadas(loadParadas());
    flash(`Iniciaste la parada en ${destino.taller}${destino.sede ? ' · ' + destino.sede : ''}.`);
  };
  // Registrar una tarea concreta: abre Recoger o Entregar. La parada sigue en curso.
  const handleRegistrarTarea = (tarea) => {
    if (tarea.tipo === 'recoger' && onIniciarRecoger) onIniciarRecoger(tarea);else
    if (tarea.tipo === 'entregar' && onIniciarEntregar) onIniciarEntregar(tarea);
  };
  // Finalizar: valida y cierra el destino (congela el tiempo).
  const confirmFinalizarDestino = (destino) => {
    const now = Date.now();
    destino.tareas.forEach((t) => updateParada(t.id, { estado: 'completada', completadaEn: now }));
    // 23/11/2026: los encargos de la parada quedan hechos al finalizarla (si no se marcaron antes).
    destino.tareas.filter((t) => t.tipo === 'encargo' && t.encargoId).forEach((t) => { const e = (window.loadEncargos ? window.loadEncargos() : []).find((x) => x.id === t.encargoId); if (e && e.estado !== 'hecho' && window.marcarEncargoHecho) window.marcarEncargoHecho(e.id, {}); });
    // Registra el tiempo en sitio en el histórico (para estadística por taller).
    if (destino.iniciadaEn) {
      try {
        const log = JSON.parse(localStorage.getItem('rodando.tiempos') || '[]');
        log.push({ taller: destino.taller, sede: destino.sede, ms: now - destino.iniciadaEn, fecha: fechaDDMMYYYY(), ts: now });
        localStorage.setItem('rodando.tiempos', JSON.stringify(log));
      } catch (e) {}
    }
    setParadas(loadParadas());
    setFinalizando(null);
    flash(`Parada completada: ${destino.taller}${destino.sede ? ' · ' + destino.sede : ''}.`);
  };
  // Cierre de jornada (B+E): archiva lo completado y devuelve a la bandeja lo
  // no terminado. Nada se arrastra solo a la ruta del día siguiente.
  const confirmCerrarJornada = () => {
    const incompletas = mine.filter((p) => p.estado === 'pendiente' || p.estado === 'en_curso');
    incompletas.forEach(devolverParadaABandeja);
    marcarJornadaCerrada(hoy);
    setParadas(loadParadas());
    setCerrandoJornada(false);
    const c = stats.completada,r = activos.length;
    flash(
      `Jornada cerrada · ${c} ${c === 1 ? 'parada completada' : 'paradas completadas'}` + (
      r > 0 ? ` · ${r} ${r === 1 ? 'volvió' : 'volvieron'} a la bandeja.` : '.'),
      r > 0 ? 'danger' : 'success'
    );
  };
  // Reordenar destinos activos por arrastre: persiste 'orden' en cada tarea.
  const reorderActivos = (orderedKeys) => {
    // Orden anterior (antes de sobrescribir) para saber qué parada se movió.
    const ordenOf = (key) => {
      const d = destinos.find((x) => x.key === key);
      if (!d || !d.tareas || !d.tareas.length) return 9999;
      return Math.min(...d.tareas.map((t) => (t.orden != null ? t.orden : 9999)));
    };
    const oldOrder = orderedKeys.slice().sort((a, b) => ordenOf(a) - ordenOf(b));
    orderedKeys.forEach((key, i) => {
      const d = destinos.find((x) => x.key === key);
      if (d) d.tareas.forEach((t) => updateParada(t.id, { orden: i }));
    });
    setParadas(loadParadas());
    if (isAdmin) {
      let movedKey = null, best = -1;
      orderedKeys.forEach((key, newIdx) => {
        const oldIdx = oldOrder.indexOf(key);
        const delta = Math.abs(newIdx - oldIdx);
        if (delta > best) { best = delta; movedKey = key; }
      });
      const md = destinos.find((x) => x.key === movedKey);
      const pos = orderedKeys.indexOf(movedKey) + 1;
      const detalle = md ? `${md.taller} → posición ${pos}` : 'Cambió el orden';
      notifyCourier('El admin reordenó tu ruta', `Cambió el orden de las paradas de hoy de ${courierActual.nombre}.`, { kind: 'reorder', detalle });
    }
  };
  const handleCancelar = (p, ok) => {
    if (!ok) { setConfirmar({ title: `¿Cancelar la parada en ${p.taller}?`, message: 'Se quitará de tu ruta de hoy.', label: 'Cancelar parada', run: () => handleCancelar(p, true) }); return; }
    // Si era una entrega planeada, vuelve a la bandeja eliminando la parada.
    removeParada(p.id);
    setParadas(loadParadas());
    setSelectedId(null);
    flash(`Parada cancelada: ${p.taller} (${p.sede}).`, 'danger');
  };
  const handleDescartarSolicitud = (p, ok) => {
    if (!ok) { setConfirmar({ title: '¿Descartar la solicitud?', message: `Se quitará la recogida de ${p.taller} · ${p.sede}${(p.placas || []).length ? ' (' + p.placas.join(', ') + ')' : ''}. No llegará a tu ruta.`, label: 'Descartar', run: () => handleDescartarSolicitud(p, true) }); return; }
    removeParada(p.id);
    setParadas(loadParadas());
    flash(`Solicitud descartada: ${p.taller}.`, 'danger');
  };
  const handleCreate = (newParada) => {
    addParada(newParada);
    if (newParada.creadaPor === 'admin' && window.addNotif) {
      window.addNotif({
        id: 'n-' + Date.now(), tipo: 'autoasignacion', para: 'mensajero', paraUsuario: newParada.asignadoA || null, estado: 'pendiente',
        taller: newParada.taller, sede: newParada.sede, accion: newParada.tipo,
        referencia: newParada.referencia, paradaId: newParada.id, actor: 'admin',
        createdAt: Date.now(), resolucion: null
      });
    }
    setParadas(loadParadas());
    setShowNew(false);
    setTab('planear');
    flash('Solicitud agregada a la bandeja.');
  };

  // ── Modo demo: simula al mensajero avanzando su ruta (solo para mostrar
  // la supervisión en vivo, ya que no hay un dispositivo real del mensajero). ──
  const simularAvance = () => {
    const now = Date.now();
    if (enCursoDestino) {
      // Completa la parada en curso (como si el mensajero la finalizara).
      enCursoDestino.tareas.forEach((t) => updateParada(t.id, { estado: 'completada', completadaEn: now }));
      if (enCursoDestino.iniciadaEn) {
        try {
          const log = JSON.parse(localStorage.getItem('rodando.tiempos') || '[]');
          log.push({ taller: enCursoDestino.taller, sede: enCursoDestino.sede, ms: now - enCursoDestino.iniciadaEn, fecha: hoy, ts: now });
          localStorage.setItem('rodando.tiempos', JSON.stringify(log));
        } catch (e) {}
      }
      setParadas(loadParadas());
      flash(`(demo) ${courierActual.nombre} completó ${enCursoDestino.taller}.`);
      return;
    }
    const next = activos.find((d) => d.estado === 'pendiente');
    if (next) {
      next.tareas.forEach((t) => updateParada(t.id, { estado: 'en_curso', iniciadaEn: now }));
      setParadas(loadParadas());
      flash(`(demo) ${courierActual.nombre} inició ${next.taller}.`);
      return;
    }
    flash('(demo) No quedan paradas por avanzar.', 'danger');
  };

  const selected = selectedId ? paradas.find((p) => p.id === selectedId) : null;

  // Markers para el mapa de la ruta (uno por destino, en orden de visita)
  const rutaMarkers = destinos.
  map((d, i) => ({
    lat: d.lat, lng: d.lng, label: i + 1,
    color: estadoColor(d.estado),
    popup: `<b>${d.taller}</b><br/>${d.sede}`
  }));

  return (
    <div style={{ background: TOKENS.bg, display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
      <AppHeader title="Rutas del día" onBack={onBack} right={null} />

      {isAdmin &&
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10, padding: '10px 16px',
        background: TOKENS.surfaceLow, borderBottom: `1px solid ${TOKENS.border}`
      }}>
          {couriers.length > 1 ?
        <>
              <span style={{ fontSize: 12.5, fontWeight: 700, color: TOKENS.textMuted, flexShrink: 0 }}>Ruta de</span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <Select value={selCourier} options={couriers.map((c) => ({ value: c.id, label: c.nombre }))} onChange={(v) => setSelCourier(v)} />
              </div>
            </> :
        <span style={{ flex: 1, fontSize: 13.5, color: TOKENS.textMuted, fontWeight: 600 }}>Ruta de <b style={{ color: TOKENS.text }}>{courierActual.nombre}</b></span>
        }
          {/* "En vivo" neutro (regla de color 13/11/2026): sin verde ni parpadeo */}
          <span style={{
          display: 'inline-flex', alignItems: 'center', gap: 5, flexShrink: 0,
          fontSize: 11, fontWeight: 700, color: TOKENS.textMuted,
          background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 999, padding: '3px 9px'
        }}>
            <span style={{ width: 6, height: 6, borderRadius: 999, background: TOKENS.textMuted }} />
            En vivo
          </span>
        </div>
      }

      {notice &&
      <div style={{
        background: notice.tone === 'danger' ? TOKENS.dangerBg : TOKENS.successBg,
        color: notice.tone === 'danger' ? TOKENS.danger : TOKENS.success,
        padding: '10px 16px', fontSize: 12, fontWeight: 600,
        display: 'flex', alignItems: 'center', gap: 8, borderBottom: `1px solid ${TOKENS.border}`
      }}>
          <span style={{
          width: 18, height: 18, borderRadius: 999,
          background: notice.tone === 'danger' ? TOKENS.danger : TOKENS.success, color: '#fff',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700
        }}>{notice.tone === 'danger' ? '!' : '✓'}</span>
          {notice.text}
        </div>
      }

      {/* Pestañas */}
      <div style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6, padding: '12px 16px 0',
        background: TOKENS.bg, position: 'sticky', top: 0, zIndex: 15
      }}>
        <TabBtn active={tab === 'ruta'} onClick={() => setTab('ruta')}
        label={isAdmin ? 'Ruta' : 'Mi ruta'} count={destinos.length} />
        <TabBtn active={tab === 'planear'} onClick={() => setTab('planear')}
        label="Por planear" count={bandejaCount} />
      </div>

      <div style={{ padding: 16, flex: 1 }}>
        {tab === 'planear' ?
        <PlanearTab
          role={role}
          recogidas={recogidasBandeja}
          entregas={entregasBandeja}
          garantias={garantiasBandeja}
          encargos={encargosBandeja}
          onVerTicket={onVerEntrega ? (t) => { rutasGuardarScroll(); RUTAS_MEMO.volver = true; onVerEntrega(t); } : undefined}
          sel={sel}
          onToggle={toggleSel}
          onToggleMany={toggleMany}
          enRutaKeys={enRutaKeys}
          courierNombre={courierActual.nombre}
          onNueva={() => setShowNew(true)}
          onDescartar={handleDescartarSolicitud} /> :


        <RutaTab
          role={role}
          admin={isAdmin}
          courierNombre={courierActual.nombre}
          destinos={destinos}
          activos={activos}
          completados={completados}
          enCursoDestino={enCursoDestino}
          stats={stats}
          totalDest={totalDest}
          location={location}
          locationStatus={locationStatus}
          requestLocation={requestLocation}
          markers={rutaMarkers}
          onOpen={setSelectedId}
          onIniciar={handleIniciarDestino}
          onRegistrar={handleRegistrarTarea}
          onFinalizar={(d) => setFinalizando(d)}
          onReorder={reorderActivos}
          onReprioritizar={handleReprioritizar}
          onQuitar={handleQuitarDeRuta}
          onSimular={simularAvance}
          enCursoActivo={!!enCursoDestino}
          onIrPlanear={() => setTab('planear')}
          jornadaCerrada={isJornadaCerrada()}
          onCerrarJornada={() => setCerrandoJornada(true)}
          onReabrirJornada={() => {reabrirJornada();setParadas(loadParadas());flash('Jornada reabierta.');}} />

        }
      </div>

      {/* Barra inferior de acción al multiseleccionar en la bandeja */}
      {tab === 'planear' && sel.size > 0 &&
      <div style={{
        position: 'sticky', bottom: 0, zIndex: 30,
        background: TOKENS.surface, borderTop: `1px solid ${TOKENS.border}`,
        padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 12,
        boxShadow: '0 -8px 24px rgba(11,28,48,0.1)'
      }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: TOKENS.text }}>
              {sel.size} {sel.size === 1 ? 'seleccionada' : 'seleccionadas'}
            </div>
            <div style={{ fontSize: 11, color: TOKENS.textMuted, fontWeight: 500 }}>
              {isAdmin ? `Se agregan a la ruta de ${courierActual.nombre} · ` : 'Se agrupan en '}{paradasResultantes} {paradasResultantes === 1 ? 'parada' : 'paradas'}
            </div>
          </div>
          <Button variant="outline" onClick={() => setSel(new Set())}>Limpiar</Button>
          <Button variant="primary" icon={I.plus(16, '#fff')} onClick={agregarARuta}>Agregar</Button>
        </div>
      }

      <BottomNav current="rutas" onNav={onNav || onBack} />

      {selected &&
      <ParadaDetailModal
        parada={selected}
        location={location}
        onDismiss={() => setSelectedId(null)}
        onIniciar={() => handleIniciar(selected)}
        onCompletar={() => handleCompletar(selected)}
        onCancelar={() => handleCancelar(selected)} />

      }

      {showNew &&
      <NuevaSolicitudModal role={role} asignadoA={userId} onDismiss={() => setShowNew(false)} onCreate={handleCreate} />
      }

      {finalizando &&
      <FinalizarDestinoModal
        destino={finalizando}
        onDismiss={() => setFinalizando(null)}
        onConfirm={() => confirmFinalizarDestino(finalizando)} />

      }

      {confirmar && window.ConfirmActionModal &&
      <ConfirmActionModal
        icon={I.trash(24, TOKENS.danger)}
        tone="danger"
        title={confirmar.title}
        message={confirmar.message}
        confirmLabel={confirmar.label}
        onConfirm={() => {const r = confirmar.run;setConfirmar(null);r();}}
        onDismiss={() => setConfirmar(null)} />
      }

      {cerrandoJornada &&
      <CerrarJornadaModal
        activos={activos}
        completados={completados}
        stats={stats}
        onDismiss={() => setCerrandoJornada(false)}
        onConfirm={confirmCerrarJornada} />

      }
    </div>);

}

// ─── Pestaña: Por planear (bandeja) ──────────────────────────────────────
// Por planear (13/11/2026): selector secundario Por recoger · Por entregar (mismas
// palabras de Inicio). Las entregas se agrupan por taller para no traer la lista
// completa: una fila por taller, casilla = todas sus placas, tocar = elegir una a una.
// Mientras Pintura no marque "listo", entra todo lo recogido sin entregar.
// Vista de Por entregar (18/11/2026): por taller (grupos) o por placa (tarjeta de Entregar/Consultar).
// Lo marcado se conserva al cambiar de vista; la elección queda guardada en el equipo.
const LS_PLANEAR_VISTA = 'rodando.planearVista';
function VistaToggle({ vista, onChange }) {
  const ico = (v, c) => v === 'taller' ?
  <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke={c} strokeWidth="1.7"><rect x="2" y="2" width="12" height="5" rx="1.5" /><rect x="2" y="9" width="12" height="5" rx="1.5" /></svg> :
  <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke={c} strokeWidth="1.7" strokeLinecap="round"><path d="M2 3h12M2 8h12M2 13h12" /></svg>;
  const b = (v, label) => {
    const on = vista === v;
    return <button type="button" onClick={() => onChange(v)} aria-pressed={on} style={{
      border: 0, borderRadius: 999, padding: '4px 10px', fontFamily: 'inherit', fontSize: 11.5, fontWeight: 600, cursor: 'pointer',
      display: 'inline-flex', alignItems: 'center', gap: 5,
      background: on ? '#fff' : 'transparent', color: on ? TOKENS.primary : TOKENS.textMuted, boxShadow: on ? '0 1px 3px rgba(22,35,63,.15)' : 'none'
    }}>{ico(v, on ? TOKENS.primary : TOKENS.textMuted)}{label}</button>;
  };
  return <div style={{ display: 'inline-flex', background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 999, padding: 2, gap: 2, flexShrink: 0 }}>{b('taller', 'Taller')}{b('placa', 'Placa')}</div>;
}
function CasillaRuta({ on, part, disabled }) {
  return <div style={{
    width: 22, height: 22, borderRadius: 6, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
    border: `${disabled ? '1.5px dashed' : '2px solid'} ${on || part ? TOKENS.primary : TOKENS.borderInput}`,
    background: on ? TOKENS.primary : part ? TOKENS.primaryBg : disabled ? TOKENS.surfaceLow : TOKENS.surface,
    color: on ? '#fff' : TOKENS.primary, fontSize: 14, fontWeight: 800
  }}>{on ? I.check(14, '#fff') : part ? '–' : null}</div>;
}
const GAR_EST_COLOR = () => [[TOKENS.dangerBg, TOKENS.dangerText], [TOKENS.warningBg, TOKENS.warningText], ['#fff2cc', '#7f6000'], ['#e6f7fa', '#0e7490']];
// Garantía por entregar en la planeación (18/11/2026): la tarjeta de siempre, con casilla.
function garChipRuta(est) {
  const [bg, fg] = GAR_EST_COLOR()[est.orden] || GAR_EST_COLOR()[3];
  return <span style={{ fontSize: 11.5, fontWeight: 500, borderRadius: 999, padding: '3px 9px', whiteSpace: 'nowrap', background: bg, color: fg }}>{est.label}</span>;
}
function GarantiaTarjetaRuta({ x, checked, onToggle, onVer }) {
  const { e, g, est } = x;
  const tk = { ...e, id: e.ticketId, fecha: e.fechaRecogido, items: [{ tipo: 'rin', cantidad: (g.rines || []).length }] };
  return <TarjetaPlaca ticket={tk} selected={checked} lead={<CasillaRuta on={checked} />} chip={garChipRuta(est)} onClick={onToggle} onVer={onVer ? () => onVer(tk) : undefined}
    fechaK="Se espera" fechaV={window.garFechaEstimada ? window.garFechaEstimada(g) : ''} />;
}
// ─── Encargos en la ruta (23/11/2026) ────────────────────────────────────
// Encargos pendientes de un mensajero que pueden ir a la ruta: con taller o con lugar escrito,
// y que no estén ya en una parada.
function encargosPlanDe(usuario, paradas) {
  const enRuta = new Set((paradas || loadParadas()).filter((p) => p.tipo === 'encargo' && p.estado !== 'cancelada' && p.encargoId).map((p) => p.encargoId));
  return (window.loadEncargos ? window.loadEncargos() : []).filter((e) => e.estado !== 'hecho' && (!e.para || e.para === usuario) && !enRuta.has(e.id) && (e.lugarTipo === 'taller' ? !!e.taller : !!String(e.direccion || '').trim()));
}
const encClave = (e) => e.lugarTipo === 'taller' ? `${e.taller}|${e.sede}` : 'o:' + e.id;
function crearParadaEncargo(e, { asignadoA, creadaPor, orden, fecha }) {
  const now = Date.now();
  const co = e.lugarTipo === 'taller' ? tallerCoords(e.taller, e.sede) : {};
  addParada({ id: 'p-enc-' + now + '-' + Math.random().toString(36).slice(2, 6), tipo: 'encargo', encargoId: e.id, encTipo: e.tipo,
    taller: e.lugarTipo === 'taller' ? e.taller : e.direccion, sede: e.cliente ? e.cliente.nombre : e.lugarTipo === 'taller' ? e.sede : '', tallerId: co.tallerId,
    direccion: co.direccion || e.direccion || '', ciudad: co.ciudad, lat: co.lat, lng: co.lng,
    placas: e.placa ? [e.placa] : [], referencia: `${((window.ENC_TIPO || {})[e.tipo] || ['', 'Encargo'])[1]} · ${e.que}`,
    estado: 'pendiente', creadaPor: creadaPor || 'admin', prioridad: e.urgente ? 'alta' : 'normal', notas: e.nota || '', fecha: fecha || fechaDDMMYYYY(), asignadoA, orden: orden || now, createdAt: now, updatedAt: now });
}
// Tarjeta de un encargo en Por planear (celular).
function EncargoBandejaCard({ e, checked, onToggle, chico }) {
  const T = (window.ENC_TIPO || {})[e.tipo] || ['✓', 'Encargo'];
  const donde = window.encDonde ? window.encDonde(e) : '';
  return <div onClick={onToggle} style={chico ? { display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px 10px 44px', borderTop: `1px dashed ${TOKENS.border}`, cursor: 'pointer' } : { display: 'flex', alignItems: 'flex-start', gap: 10, background: TOKENS.surface, border: `1px solid ${checked ? TOKENS.primary : TOKENS.border}`, boxShadow: checked ? `0 0 0 2px ${TOKENS.primaryBg}` : 'none', borderRadius: 14, padding: '12px 13px', cursor: 'pointer' }}>
    <CasillaRuta on={checked} />
    <div style={{ flex: 1, minWidth: 0 }}>
      {window.EncEtiquetas ? <window.EncEtiquetas tipo={e.tipo} /> : null}
      {e.urgente && <span style={{ marginLeft: 6, fontSize: 10.5, fontWeight: 700, color: TOKENS.primary }}>↑ Prioridad</span>}
      <div style={{ fontSize: 14, fontWeight: 700, color: TOKENS.text, marginTop: 6 }}>{e.que}</div>
      {!chico && <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 3 }}>{[donde, window.encParaTxt ? window.encParaTxt(e) : '', e.lugarTipo === 'otro' && 'sin punto en el mapa'].filter(Boolean).join(' · ')}</div>}
    </div>
    {e.placa && <PlacaOrdenChica placa={e.placa} />}
  </div>;
}

function PlanearTab({ role, recogidas, entregas, garantias = [], encargos = [], sel, onToggle, onToggleMany, onNueva, onDescartar, enRutaKeys, courierNombre, onVerTicket }) {
  const [vista, setVistaSt] = React.useState(() => { try { return localStorage.getItem(LS_PLANEAR_VISTA) || 'taller'; } catch (e) { return 'taller'; } });
  const setVista = (v) => { setVistaSt(v); try { localStorage.setItem(LS_PLANEAR_VISTA, v); } catch (e) {} };
  const [query, setQuery] = React.useState(RUTAS_MEMO.query || '');
  const [modo, setModo] = React.useState(RUTAS_MEMO.modo || 'entregar');
  const [abiertos, setAbiertos] = React.useState(() => new Set(RUTAS_MEMO.abiertos || []));
  React.useEffect(() => { RUTAS_MEMO.query = query; RUTAS_MEMO.modo = modo; RUTAS_MEMO.abiertos = [...abiertos]; }, [query, modo, abiertos]);
  const q = query.trim().toLowerCase();

  const entregaHay = (t) => {
    const sum = window.ticketSummary ? window.ticketSummary(t) : {};
    return [t.taller, t.sede, t.placa, t.codigo, t.aseguradora, sum.rines ? 'rines' : '', sum.llantas ? 'llantas' : '', sum.valvulas ? 'valvulas' : ''].join(' ').toLowerCase();
  };
  const solicitudHay = (p) => [p.taller, p.sede, p.referencia, p.notas, ...(p.placas || [])].join(' ').toLowerCase();
  const fEntregas = q ? entregas.filter((t) => entregaHay(t).includes(q)) : entregas;
  const fRecogidas = q ? recogidas.filter((p) => solicitudHay(p).includes(q)) : recogidas;
  const fGar = q ? garantias.filter((x) => [x.e.taller, x.e.sede, x.e.placa, x.e.codigo, x.e.aseguradora, 'garantia'].join(' ').toLowerCase().includes(q)) : garantias;
  const [estF, setEstF] = React.useState(RUTAS_MEMO.estF || 'todas');
  React.useEffect(() => { RUTAS_MEMO.estF = estF; }, [estF]);
  const estOk = (o, x) => estF === 'todas' || (estF === 'x' ? !!x : String(o) === estF);
  const fEncargos = q ? encargos.filter((e) => [e.que, e.taller, e.sede, e.direccion, e.placa, e.nota].join(' ').toLowerCase().includes(q)) : encargos;
  const espera = (t) => !!(window.anulacionEnEspera && window.anulacionEnEspera(t.id));

  // Grupos por taller: primero los que ya están en la ruta, luego por urgencia.
  const est = (t) => window.estadoProcesos ? window.estadoProcesos(t) : { orden: 3, dias: 0 };
  const nEst = (k) => fEntregas.filter((t) => k === 'x' ? t.express : String(est(t).orden) === k).length + fGar.filter((x) => k === 'x' ? x.e.express : String(x.est.orden) === k).length;
  const fEntregasE = fEntregas.filter((t) => estOk(est(t).orden, t.express));
  const fGarE = fGar.filter((x) => estOk(x.est.orden, x.e.express));
  const gm = new Map();
  fEntregasE.forEach((t) => {
    const sd = t.cliente ? t.cliente.nombre : t.sede;
    const k = `${t.taller}|${sd}`;
    if (!gm.has(k)) gm.set(k, { k, taller: t.taller, sede: sd, items: [] });
    gm.get(k).items.push(t);
  });
  // Garantías (18/11/2026): entran al grupo de su taller y a la lista por placa, así les aplican
  // la vista, el buscador y la selección como a cualquier entrega.
  fGarE.forEach((x) => {
    const k = `${x.e.taller}|${x.e.sede}`;
    if (!gm.has(k)) gm.set(k, { k, taller: x.e.taller, sede: x.e.sede, items: [] });
    (gm.get(k).gars = gm.get(k).gars || []).push(x);
  });
  fEncargos.filter((e) => e.lugarTipo === 'taller' && gm.has(`${e.taller}|${e.sede}`)).forEach((e) => { const g = gm.get(`${e.taller}|${e.sede}`); (g.encs = g.encs || []).push(e); });
  const grupos = [...gm.values()].map((g) => {
    g.gars = (g.gars || []).sort((a, b) => a.est.orden - b.est.orden || b.est.dias - a.est.dias);
    g.items.sort((a, b) => est(a).orden - est(b).orden || est(b).dias - est(a).dias);
    g.min = Math.min(...g.items.map((t) => est(t).orden), ...g.gars.map((x) => x.est.orden));
    g.enRuta = enRutaKeys.has(g.k);
    return g;
  }).sort((a, b) => (b.enRuta - a.enRuta) || (a.min - b.min) || (b.items.length + b.gars.length - a.items.length - a.gars.length));

  const pill = (id, label, n) =>
  <button type="button" onClick={() => setModo(id)} style={{
    border: 0, borderRadius: 999, padding: '6px 14px', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 700, cursor: 'pointer',
    background: modo === id ? '#fff' : 'transparent', color: modo === id ? TOKENS.primary : TOKENS.textMuted,
    boxShadow: modo === id ? '0 1px 3px rgba(22,35,63,.15)' : 'none'
  }}>{label}<span style={{ fontSize: 10.5, fontWeight: 800, marginLeft: 5, color: TOKENS.textSubtle }}>{n}</span></button>;

  return (
    <div>
      <div style={{ fontSize: 12.5, color: TOKENS.textMuted, margin: '0 2px 10px' }}>{role === 'admin' ? `Elige qué agregar a la ruta de ${courierNombre || 'el mensajero'}.` : 'Elige lo que vas a hacer hoy y agrégalo a tu ruta.'}</div>
      <div style={{ display: 'inline-flex', background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 999, padding: 3, gap: 2, marginBottom: 10 }}>
        {pill('entregar', 'Por entregar', entregas.length + garantias.length)}
        {pill('recoger', 'Por recoger', recogidas.length)}
        {pill('encargar', 'Por encargar', encargos.length)}
      </div>

      <div style={{ position: 'relative', marginBottom: 14 }}>
        <div style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none', display: 'flex' }}>{I.consultar(16, TOKENS.textMuted)}</div>
        <input type="text" value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Buscar placa, taller o sede" style={{
          width: '100%', boxSizing: 'border-box', border: `1px solid ${TOKENS.borderInput}`, background: TOKENS.surface,
          borderRadius: 12, padding: '11px 40px 11px 38px', fontSize: 14, color: TOKENS.text, fontFamily: 'inherit', outline: 'none'
        }} />
        {query &&
        <button type="button" onClick={() => setQuery('')} aria-label="Limpiar búsqueda" style={{ position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)', background: 'transparent', border: 'none', padding: 6, cursor: 'pointer', display: 'flex' }}>{I.x(16, TOKENS.textMuted)}</button>
        }
      </div>
      {modo === 'entregar' && <div style={{ display: 'flex', gap: 6, overflowX: 'auto', margin: '-4px 0 12px', paddingBottom: 2 }}>
        {[['todas', 'Todas', null], ['0', 'Vencido', TOKENS.danger], ['1', 'Retrasado', TOKENS.warning], ['2', 'Vence hoy', '#f2c037'], ['3', 'En plazo', TOKENS.success], ['x', '⚡ Express', null]].map(([k, l, dot]) => { const on = estF === k; const n = k === 'todas' ? fEntregas.length + fGar.length : nEst(k); return (
          <button key={k} type="button" onClick={() => setEstF(on && k !== 'todas' ? 'todas' : k)} style={{ flexShrink: 0, display: 'inline-flex', alignItems: 'center', gap: 5, border: `1px solid ${on ? (k === 'x' ? '#e879b0' : TOKENS.primary) : TOKENS.borderInput}`, background: on ? (k === 'x' ? '#fce7f3' : TOKENS.primary) : TOKENS.surface, color: on ? (k === 'x' ? '#be185d' : '#fff') : k === 'x' ? '#be185d' : TOKENS.text, borderRadius: 99, padding: '5px 10px', fontFamily: 'inherit', fontSize: 12, fontWeight: 600, cursor: 'pointer', whiteSpace: 'nowrap' }}>
            {dot && <span style={{ width: 7, height: 7, borderRadius: 99, background: on ? '#fff' : dot }} />}{l} <span style={{ opacity: .7, fontWeight: 500 }}>{n}</span></button>); })}
      </div>}

      {modo === 'encargar' ?
      <>
          <div style={{ marginBottom: 10, padding: '0 2px' }}><SectionHeader title="Encargos de la oficina" count={fEncargos.length} inline /></div>
          <div style={{ fontSize: 11, color: TOKENS.textSubtle, margin: '-4px 2px 10px' }}>Los de un taller con placas por entregar también salen dentro de ese taller.</div>
          {encargos.length === 0 ?
        <EmptyHint text="No hay encargos para meter a la ruta." /> :
        fEncargos.length === 0 ?
        <EmptyHint text={`Ningún encargo coincide con “${query.trim()}”.`} /> :
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {fEncargos.map((e) => <EncargoBandejaCard key={e.id} e={e} checked={sel.has('enc:' + e.id)} onToggle={() => onToggle('enc:' + e.id)} />)}
            </div>}
        </> :
      modo === 'recoger' ?
      <>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10, padding: '0 2px' }}>
            <SectionHeader title="Recogidas solicitadas" count={fRecogidas.length} inline />
            <button onClick={onNueva} style={{
            display: 'inline-flex', alignItems: 'center', gap: 4, padding: '6px 12px', borderRadius: 999, fontSize: 11.5, fontWeight: 700,
            background: TOKENS.primary, color: '#fff', border: 'none', cursor: 'pointer', fontFamily: 'inherit'
          }}>{I.plus(13, '#fff')} Nueva solicitud</button>
          </div>
          {recogidas.length === 0 ?
        <EmptyHint text="No hay recogidas solicitadas. Crea una cuando un taller te escriba." /> :
        fRecogidas.length === 0 ?
        <EmptyHint text={`Ninguna recogida coincide con “${query.trim()}”.`} /> :
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {fRecogidas.map((p) =>
          <SolicitudBandejaCard key={p.id} parada={p} checked={sel.has('sol:' + p.id)} onToggle={() => onToggle('sol:' + p.id)} onDescartar={() => onDescartar(p)} />
          )}
            </div>
        }
        </> :

      <>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8, marginBottom: 4, padding: '0 2px' }}>
            <SectionHeader inline title={vista === 'placa' ? 'Por placa' : 'Por taller'}
          count={vista === 'placa' ? fEntregasE.length + fGarE.length : `${grupos.length} · ${fEntregasE.length + fGarE.length} ${fEntregasE.length + fGarE.length === 1 ? 'placa' : 'placas'}`} />
            <VistaToggle vista={vista} onChange={setVista} />
          </div>
          <div style={{ fontSize: 11, color: TOKENS.textSubtle, margin: '0 2px 10px' }}>
            {vista === 'placa' ? 'Las más urgentes primero. Toca la tarjeta para elegirla; “Ver” abre la ficha.' : 'La casilla agrega todas las placas del taller. Toca la fila para elegir una por una.'}
          </div>
          {entregas.length + garantias.length === 0 ?
        <EmptyHint text="No hay placas por entregar." /> :
        fEntregasE.length + fGarE.length === 0 ?
        <EmptyHint text={q ? `Ninguna placa coincide con “${query.trim()}”.` : 'Ninguna placa con ese estado.'} /> :
        vista === 'placa' ?
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {[...fEntregasE.map((t) => ({ t, o: est(t).orden, d: est(t).dias, x: t.express })), ...fGarE.map((g) => ({ g, o: g.est.orden, d: g.est.dias, x: g.e.express }))].
          sort((a, b) => a.o - b.o || b.d - a.d || (b.x ? 1 : 0) - (a.x ? 1 : 0)).map((r) => {
            if (r.g) return <GarantiaTarjetaRuta key={r.g.g.id} x={r.g} checked={sel.has('gar:' + r.g.g.id)} onToggle={() => onToggle('gar:' + r.g.g.id)} onVer={onVerTicket} />;
            const t = r.t;
            const off = espera(t);const on = sel.has('ent:' + t.codigo);
            return <TarjetaPlaca key={t.id} ticket={t} selected={on}
              lead={<CasillaRuta on={on} disabled={off} />}
              chip={off ? window.ChipSolicitud ? <ChipSolicitud /> : null : <EstadoChip e={est(t)} />}
              onClick={off ? undefined : () => onToggle('ent:' + t.codigo)}
              onVer={onVerTicket ? () => onVerTicket(t) : undefined} />;
          })}
            </div> :
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {grupos.map((g) =>
          <GrupoEntregaCard key={g.k} grupo={g} sel={sel} abierto={abiertos.has(g.k) || !!q}
          onAbrir={() => setAbiertos((prev) => {const n = new Set(prev);n.has(g.k) ? n.delete(g.k) : n.add(g.k);return n;})}
          onToggle={onToggle} onToggleMany={onToggleMany} />
          )}
            </div>
        }
        </>
      }
    </div>);

}

// Fila de un taller con sus placas por entregar.
function GrupoEntregaCard({ grupo, sel, abierto, onAbrir, onToggle, onToggleMany }) {
  const espera = (t) => !!(window.anulacionEnEspera && window.anulacionEnEspera(t.id));
  const gars = grupo.gars || [];
  const elegibles = grupo.items.filter((t) => !espera(t));
  const keys = [...elegibles.map((t) => 'ent:' + t.codigo), ...gars.map((x) => 'gar:' + x.g.id)];
  const nSel = keys.filter((k) => sel.has(k)).length;
  const todas = nSel > 0 && nSel === keys.length;
  const parcial = nSel > 0 && !todas;
  const cnt = [0, 0, 0, 0];
  grupo.items.forEach((t) => {const e = window.estadoProcesos ? window.estadoProcesos(t) : null;if (e) cnt[e.orden]++;});
  gars.forEach((x) => cnt[x.est.orden]++);
  const aseg = (t) => window.catAseguradoraCorta ? window.catAseguradoraCorta(t.aseguradora) : t.aseguradora;
  const nExp = grupo.items.filter((t) => t.express).length;
  const LBL = [['vencida', 'vencidas', TOKENS.dangerBg, TOKENS.dangerText], ['retrasada', 'retrasadas', TOKENS.warningBg, TOKENS.warningText], ['vence hoy', 'vencen hoy', '#fff2cc', '#7f6000']];
  const caja = (on, part, disabled) =>
  <div style={{
    width: 22, height: 22, borderRadius: 6, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
    border: `${disabled ? '1.5px dashed' : '2px solid'} ${on || part ? TOKENS.primary : TOKENS.borderInput}`,
    background: on ? TOKENS.primary : part ? TOKENS.primaryBg : disabled ? TOKENS.surfaceLow : TOKENS.surface,
    color: on ? '#fff' : TOKENS.primary, fontSize: 14, fontWeight: 800
  }}>{on ? I.check(14, '#fff') : part ? '–' : null}</div>;
  return (
    <div style={{ background: TOKENS.surface, border: `1px solid ${nSel ? TOKENS.primary : TOKENS.border}`, boxShadow: nSel ? `0 0 0 2px ${TOKENS.primaryBg}` : 'none', borderRadius: 14, overflow: 'hidden' }}>
      <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start', padding: 12 }}>
        <div onClick={() => keys.length && onToggleMany(keys, !todas)} style={{ cursor: keys.length ? 'pointer' : 'default', paddingTop: grupo.enRuta ? 22 : 0 }}>{caja(todas, parcial, !keys.length)}</div>
        <div onClick={onAbrir} style={{ flex: 1, minWidth: 0, cursor: 'pointer' }}>
          {grupo.enRuta &&
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 10.5, fontWeight: 600, color: TOKENS.textMuted, background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 999, padding: '2px 8px', marginBottom: 6 }}>{I.map(11, TOKENS.textMuted)} Ya vas para allá</span>
          }
          <div style={{ fontSize: 14.5, fontWeight: 700, color: TOKENS.text }}>{grupo.taller}{grupo.sede && <span style={{ color: TOKENS.textMuted, fontWeight: 500 }}> · {grupo.sede}</span>}</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', marginTop: 6, fontSize: 12, color: TOKENS.textMuted, fontWeight: 600 }}>
            <span>{grupo.items.length + gars.length} {grupo.items.length + gars.length === 1 ? 'placa' : 'placas'}</span>
            {gars.length > 0 && <span style={{ fontSize: 11, fontWeight: 500, borderRadius: 999, padding: '2px 8px', background: '#e6f7fa', color: '#0e7490', border: '1px solid #b3e3ec' }}>↺ {gars.length}</span>}
            {(grupo.encs || []).length > 0 && <span style={{ fontSize: 11, fontWeight: 600, borderRadius: 999, padding: '2px 8px', background: TOKENS.surfaceLow, color: TOKENS.textMuted, border: `1px solid ${TOKENS.border}` }}>＋ {grupo.encs.length} {grupo.encs.length === 1 ? 'encargo' : 'encargos'}</span>}
            {LBL.map(([s1, s2, bg, fg], o) => cnt[o] > 0 &&
            <span key={o} style={{ fontSize: 11, fontWeight: 500, borderRadius: 999, padding: '2px 8px', background: bg, color: fg }}>{cnt[o]} {cnt[o] === 1 ? s1 : s2}</span>
            )}
            {nExp > 0 && <span style={{ fontSize: 11, fontWeight: 500, borderRadius: 999, padding: '2px 8px', background: '#fce7f3', color: '#be185d', border: '1px solid #f5bfdc' }}>⚡ {nExp}</span>}
            {nSel > 0 && <span style={{ color: TOKENS.primary }}>· {nSel} {nSel === 1 ? 'elegida' : 'elegidas'}</span>}
          </div>
        </div>
        <button type="button" onClick={onAbrir} aria-label={abierto ? 'Cerrar' : 'Ver placas'} style={{ border: 0, background: 'none', padding: 4, cursor: 'pointer', alignSelf: 'center', display: 'flex', transform: abierto ? 'rotate(180deg)' : 'none', transition: 'transform .15s' }}>{I.chev(16, TOKENS.textMuted)}</button>
      </div>
      {abierto && (grupo.encs || []).map((e) => <EncargoBandejaCard key={e.id} e={e} chico checked={sel.has('enc:' + e.id)} onToggle={() => onToggle('enc:' + e.id)} />)}
      {abierto && gars.map((x) => {
        const on = sel.has('gar:' + x.g.id);
        const tk = { ...x.e, id: x.e.ticketId };
        return (
          <div key={x.g.id} onClick={() => onToggle('gar:' + x.g.id)} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px 10px 44px', borderTop: `1px dashed ${TOKENS.border}`, cursor: 'pointer' }}>
            {caja(on, false, false)}
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ ...PLACA_LISTA, fontSize: 14, padding: '3px 7px' }}>{x.e.placa}</span>
                <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 12.5, fontWeight: 700, color: TOKENS.textMuted }}>{x.e.codigo}</span>
                {window.InsigniasPlaca && <window.InsigniasPlaca ticket={tk} alto={24} />}
                <span style={{ flex: 1 }} />
                {garChipRuta(x.est)}
              </div>
              <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 5 }}>{aseg(x.e) ? <span style={{ color: TOKENS.text, fontWeight: 500 }}>{aseg(x.e)}</span> : null}{aseg(x.e) ? ' · ' : ''}{(x.g.rines || []).map((i) => 'Rin ' + (i + 1)).join(', ')} · {x.g.motivo}</div>
            </div>
          </div>);
      })}
      {abierto && grupo.items.map((t) => {
        const off = espera(t);
        const on = sel.has('ent:' + t.codigo);
        const e = window.estadoProcesos ? window.estadoProcesos(t) : null;
        const sm = window.ticketSummary ? window.ticketSummary(t) : {};
        const items = [sm.rines && `${sm.rines} ${sm.rines === 1 ? 'rin' : 'rines'}`, sm.llantas && `${sm.llantas} ${sm.llantas === 1 ? 'llanta' : 'llantas'}`, sm.valvulas && `${sm.valvulas} ${sm.valvulas === 1 ? 'válvula' : 'válvulas'}`].filter(Boolean).join(' · ');
        return (
          <div key={t.id} onClick={off ? undefined : () => onToggle('ent:' + t.codigo)} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px 10px 44px', borderTop: `1px dashed ${TOKENS.border}`, cursor: off ? 'default' : 'pointer' }}>
            {caja(on, false, off)}
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ ...PLACA_LISTA, fontSize: 14, padding: '3px 7px' }}>{t.placa}</span>
                <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 12.5, fontWeight: 700, color: TOKENS.textMuted }}>{t.codigo}</span>
                {t.express && window.PcChipExpress && <window.PcChipExpress solo />}
                <span style={{ flex: 1 }} />
                {off ? (window.ChipSolicitud ? <ChipSolicitud /> : null) : <EstadoChip e={e} />}
              </div>
              <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 5 }}>{aseg(t) ? <span style={{ color: TOKENS.text, fontWeight: 500 }}>{aseg(t)}</span> : null}{aseg(t) && items ? ' · ' : ''}{items}</div>
            </div>
          </div>);
      })}
    </div>);

}

function SectionHeader({ title, count, hint, inline = false }) {
  return (
    <div style={{ marginBottom: inline ? 0 : 10, padding: '0 2px' }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
        <span style={{ fontSize: 10.5, fontWeight: 800, color: TOKENS.textMuted, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
          {title}
        </span>
        {count != null && <span style={{ fontSize: 11.5, fontWeight: 700, color: TOKENS.textSubtle }}>{count}</span>}
      </div>
      {hint && <div style={{ fontSize: 11, color: TOKENS.textSubtle, marginTop: 2 }}>{hint}</div>}
    </div>);

}

function EmptyHint({ text }) {
  return (
    <div style={{
      padding: '18px 16px', textAlign: 'center', color: TOKENS.textMuted, fontSize: 12.5,
      background: TOKENS.surfaceLow, borderRadius: 12, border: `1px dashed ${TOKENS.border}`,
      marginBottom: 18
    }}>{text}</div>);

}

function Checkbox({ checked }) {
  return (
    <div style={{
      width: 24, height: 24, borderRadius: 7, flexShrink: 0,
      border: `2px solid ${checked ? TOKENS.primary : TOKENS.borderInput}`,
      background: checked ? TOKENS.primary : TOKENS.surface,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      transition: 'all 0.12s'
    }}>{checked && I.check(15, '#fff')}</div>);

}

function PlacaTag({ placa, size = 16 }) {
  return <span style={{
    display: 'inline-flex', alignItems: 'center', fontFamily: '"SF Mono",ui-monospace,Menlo,monospace',
    fontWeight: 800, letterSpacing: '0.08em', fontSize: size, color: TOKENS.text,
    background: TOKENS.surfaceLow, border: `1.5px solid ${TOKENS.borderInput}`, borderRadius: 6, padding: '3px 9px', lineHeight: 1
  }}>{placa}</span>;
}
function OrdenPill({ codigo }) {
  return <span style={{
    display: 'inline-flex', alignItems: 'center', gap: 3, fontFamily: '"SF Mono",ui-monospace,Menlo,monospace',
    fontSize: 12, fontWeight: 700, color: TOKENS.primary, background: TOKENS.primaryBg,
    border: `1px solid ${TOKENS.primaryBorder}`, borderRadius: 6, padding: '2px 7px', flexShrink: 0
  }}><span style={{ fontSize: 9, color: TOKENS.textMuted, fontWeight: 700, letterSpacing: '0.04em' }}>N°</span>{codigo}</span>;
}

function EntregaBandejaCard({ ticket, checked, onToggle }) {
  const sum = window.ticketSummary ? window.ticketSummary(ticket) : { rines: 0, llantas: 0, valvulas: 0 };
  const parts = [];
  if (sum.rines) parts.push(`${sum.rines} ${sum.rines === 1 ? 'rin' : 'rines'}`);
  if (sum.llantas) parts.push(`${sum.llantas} ${sum.llantas === 1 ? 'llanta' : 'llantas'}`);
  if (sum.valvulas) parts.push(`${sum.valvulas} ${sum.valvulas === 1 ? 'válvula' : 'válvulas'}`);
  const sev = ticket.severity || { level: 'aldia', dias: 0 };
  const meta = (window.SEVERITY_META || {})[sev.level] || { color: TOKENS.success, soft: TOKENS.successBg, text: TOKENS.successText };
  return (
    <Card style={{ padding: 0, overflow: 'hidden', cursor: 'pointer', borderLeft: `4px solid ${TOKENS.success}` }}>
      <div onClick={onToggle} style={{ padding: '12px 14px', display: 'flex', alignItems: 'flex-start', gap: 12 }}>
        <Checkbox checked={checked} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', marginBottom: 5 }}>
            <span style={{ fontSize: 9, fontWeight: 700, color: TOKENS.blueLiteText, padding: '2px 6px', borderRadius: 4, background: TOKENS.blueLiteBg, letterSpacing: '0.08em' }}>ENTREGAR</span>
            <span style={{
              fontSize: 9, fontWeight: 600, padding: '2px 7px', borderRadius: 999,
              background: meta.soft, color: meta.text, letterSpacing: '0.05em', textTransform: 'uppercase'
            }}>{SLA_LABEL[sev.level] || 'Al día'} · {sev.dias} d</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 5 }}>
            <PlacaTag placa={ticket.placa} />
            <OrdenPill codigo={ticket.codigo} />
          </div>
          <div style={{ fontSize: 13.5, fontWeight: 600, color: TOKENS.text, display: 'flex', alignItems: 'center', gap: 4 }}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke={TOKENS.textMuted} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z" /><circle cx="12" cy="10" r="3" /></svg>
            {ticket.taller}<span style={{ color: TOKENS.textMuted, fontWeight: 500 }}> · {ticket.sede}</span>
          </div>
          <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 3 }}>
            {parts.join(' · ') || 'Sin ítems'}
          </div>
        </div>
      </div>
    </Card>);

}

function SolicitudBandejaCard({ parada, checked, onToggle, onDescartar }) {
  const placas = (parada.placas || []).filter(Boolean);
  return (
    <div style={{ background: TOKENS.surface, border: `1px solid ${checked ? TOKENS.primary : TOKENS.border}`, boxShadow: checked ? `0 0 0 2px ${TOKENS.primaryBg}` : 'none', borderRadius: 14, padding: 12, display: 'flex', gap: 10, alignItems: 'flex-start' }}>
      <div onClick={onToggle} style={{ cursor: 'pointer', display: 'flex', paddingTop: 2 }}><Checkbox checked={checked} /></div>
      <div onClick={onToggle} style={{ flex: 1, minWidth: 0, cursor: 'pointer' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', marginBottom: 7, fontSize: 11, color: TOKENS.textSubtle, fontWeight: 700 }}>
          {parada.prioridad === 'alta' && <PrioridadTag />}
          {parada.arrastrada && <span style={{ fontSize: 10.5, fontWeight: 600, color: TOKENS.textMuted, background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 999, padding: '1px 8px' }}>Sin terminar</span>}
          <span>Solicitó: {parada.creadaPor === 'admin' ? 'Admin' : 'Tú'}</span>
        </div>
        {placas.length ?
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={PLACA_LISTA}>{placas[0]}</span>
            {placas.length > 1 && <span style={{ fontSize: 11.5, color: TOKENS.textMuted, fontWeight: 700 }}>+{placas.length - 1}</span>}
          </div> :
        <span style={{ fontSize: 11, fontWeight: 700, color: TOKENS.textSubtle, border: `1px dashed ${TOKENS.borderInput}`, borderRadius: 6, padding: '3px 7px' }}>Sin placa</span>
        }
        <div style={{ fontSize: 13.5, fontWeight: 500, color: TOKENS.text, marginTop: 8 }}>{parada.taller}</div>
        <div style={{ fontSize: 12.5, color: TOKENS.textMuted, marginTop: 2 }}>{parada.sede}{parada.referencia ? ' · ' + String(parada.referencia).replace(/^Recogida solicitada\s*[—-]\s*/i, '') : ''}</div>
        {parada.notas && <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 5, fontStyle: 'italic' }}>{parada.notas}</div>}
      </div>
      <button onClick={onDescartar} aria-label="Descartar solicitud" style={{ background: 'transparent', border: 'none', cursor: 'pointer', padding: 4, flexShrink: 0 }}>{I.trash(16, TOKENS.textSubtle)}</button>
    </div>);

}

// ─── Pestaña: Mi ruta ────────────────────────────────────────────────────
// Inyecta una vez los keyframes para animaciones de la ruta (pulso/parpadeo).
(function ensureRutaStyles() {
  if (typeof document === 'undefined' || document.getElementById('rd-ruta-styles')) return;
  const s = document.createElement('style');
  s.id = 'rd-ruta-styles';
  s.textContent =
  '@keyframes rdBlink{0%,100%{opacity:1}50%{opacity:.35}}' +
  '@keyframes rdPulse{0%{box-shadow:0 0 0 0 rgba(207,138,51,0.55)}70%{box-shadow:0 0 0 7px rgba(207,138,51,0)}100%{box-shadow:0 0 0 0 rgba(207,138,51,0)}}';
  document.head.appendChild(s);
})();

// Agrupa paradas de la ruta por DESTINO (taller + sede). Una tarjeta = un lugar.
function groupByDestino(paradas) {
  const map = new Map();
  paradas.forEach((p) => {
    const key = `${p.taller}|${p.sede}`;
    if (!map.has(key)) {
      map.set(key, {
        key, taller: p.taller, sede: p.sede, direccion: p.direccion,
        ciudad: p.ciudad, lat: p.lat, lng: p.lng, tareas: []
      });
    }
    map.get(key).tareas.push(p);
  });
  return [...map.values()].map((d) => {
    const estados = d.tareas.map((t) => t.estado);
    const estado = estados.every((e) => e === 'completada') ? 'completada' :
    estados.some((e) => e === 'en_curso') ? 'en_curso' :
    'pendiente';
    const inis = d.tareas.filter((t) => t.iniciadaEn).map((t) => t.iniciadaEn);
    const comps = d.tareas.filter((t) => t.completadaEn).map((t) => t.completadaEn);
    const ordenes = d.tareas.map((t) => t.orden != null ? t.orden : t.createdAt || 0);
    return {
      ...d, estado,
      iniciadaEn: inis.length ? Math.min(...inis) : null,
      completadaEn: comps.length ? Math.max(...comps) : null,
      orden: Math.min(...ordenes),
      prioridad: d.tareas.some((t) => t.prioridad === 'alta') ? 'alta' : 'normal'
    };
  });
}

// Cronómetro en vivo (mm:ss / h:mm:ss). Si 'until' está fijo, congela el valor.
function LiveTimer({ since, until }) {
  const [, force] = React.useState(0);
  React.useEffect(() => {
    if (until || !since) return;
    const id = setInterval(() => force((n) => n + 1), 1000);
    return () => clearInterval(id);
  }, [until, since]);
  if (!since) return null;
  const end = until || Date.now();
  const secs = Math.max(0, Math.floor((end - since) / 1000));
  const pad = (n) => String(n).padStart(2, '0');
  const h = Math.floor(secs / 3600),m = Math.floor(secs % 3600 / 60),s = secs % 60;
  return <>{h > 0 ? `${h}:${pad(m)}:${pad(s)}` : `${pad(m)}:${pad(s)}`}</>;
}

function durTexto(a, b) {
  const s = Math.max(0, Math.floor((b - a) / 1000));
  const m = Math.round(s / 60);
  return m < 1 ? 'menos de 1 min' : `${m} min en sitio`;
}

// Severidad SLA (en vivo) de una tarea de entrega, según su(s) consecutivo(s).
// Devuelve la peor severidad entre las placas que agrupa la tarea.
function tareaSeveridad(tarea) {
  if (!tarea || tarea.tipo !== 'entregar' || !window.ticketSeverity) return null;
  const cods = (tarea.consecutivos || []).map(String);
  if (!cods.length) return null;
  const all = [
  ...(window.loadPendientesSaved ? window.loadPendientesSaved() : []),
  ...(window.PENDIENTES_DEMO || [])];

  const today = new Date();
  const rank = { aldia: 0, atrasado: 1, critico: 2 };
  let worst = null;
  cods.forEach((c) => {
    const t = all.find((x) => String(x.codigo) === c);
    if (!t) return;
    const s = window.ticketSeverity(t, today);
    if (!worst || rank[s.level] > rank[worst.level]) worst = s;
  });
  return worst;
}

// Estado de una tarea de entrega con los términos de PROCESOS (el peor entre sus placas).
function tareaEstado(tarea) {
  if (!tarea || tarea.tipo !== 'entregar' || !window.estadoProcesos) return null;
  const cods = (tarea.consecutivos || []).map(String);
  const all = [...(window.loadPendientesSaved ? window.loadPendientesSaved() : []), ...(window.PENDIENTES_DEMO || [])];
  let worst = null;
  cods.forEach((c) => {
    const t = all.find((x) => String(x.codigo) === c);
    if (!t) return;
    const e = window.estadoProcesos(t);
    if (!worst || e.orden < worst.orden || (e.orden === worst.orden && e.dias > worst.dias)) worst = e;
  });
  // Garantías de la parada (18/11/2026): cuentan con su propio plazo.
  (tarea.garantias || []).forEach((x) => {
    const g = window.garantiasDe ? window.garantiasDe(x.ticketId).find((y) => y.id === x.garId) : null;
    if (!g || g.estado !== 'abierta' || !window.garEstado) return;
    const ge = window.garEstado(g);const [bg, fg] = GAR_EST_COLOR()[ge.orden] || GAR_EST_COLOR()[3];
    const e = { ...ge, bg, fg };
    if (!worst || e.orden < worst.orden || (e.orden === worst.orden && e.dias > worst.dias)) worst = e;
  });
  return worst;
}
function EstadoChip({ e }) {
  if (!e) return null;
  return <span style={{ fontSize: 11, fontWeight: 500, borderRadius: 999, padding: '3px 8px', whiteSpace: 'nowrap', background: e.bg, color: e.fg, flexShrink: 0 }}>{e.label} · {e.dias} d</span>;
}
function TipoTag({ tipo }) {
  const ic = tipo === 'recoger' ? I.recoger : tipo === 'entregar' ? I.truck : null;
  return <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 10, fontWeight: 800, letterSpacing: '0.05em', color: TOKENS.textMuted, background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 6, padding: '2px 6px', flexShrink: 0 }}>{ic ? ic(12, TOKENS.textMuted) : null}{tipoLabel(tipo)}</span>;
}
function PrioridadTag() {
  return <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3, fontSize: 10.5, fontWeight: 600, color: TOKENS.text, border: `1px solid ${TOKENS.borderInput}`, background: TOKENS.surface, borderRadius: 999, padding: '1px 8px' }}>↑ Prioridad</span>;
}
const PLACA_CHICA = { fontFamily: "'JetBrains Mono', monospace", fontWeight: 600, fontSize: 15, background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 7, padding: '4px 8px', color: TOKENS.text, whiteSpace: 'nowrap' };
const PLACA_LISTA = { fontFamily: "'JetBrains Mono', monospace", fontWeight: 600, fontSize: 16, background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 7, padding: '5px 9px', color: TOKENS.text, whiteSpace: 'nowrap' };

// Peor severidad de un destino (entre sus tareas de entrega).
function destinoSeveridad(destino) {
  const rank = { aldia: 0, atrasado: 1, critico: 2 };
  let worst = null;
  (destino.tareas || []).forEach((t) => {
    const s = tareaSeveridad(t);
    if (s && (!worst || rank[s.level] > rank[worst.level])) worst = s;
  });
  return worst;
}

// Píldora de severidad SLA reutilizable (color del nivel + días).
function SlaBadge({ sev, compact }) {
  if (!sev) return null;
  const meta = (window.SEVERITY_META || {})[sev.level];
  if (!meta) return null;
  const label = { aldia: 'Al día', atrasado: 'Atrasado', critico: 'Crítico' }[sev.level] || meta.label;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5, flexShrink: 0,
      fontSize: 9, fontWeight: 800, letterSpacing: '0.04em', textTransform: 'uppercase',
      color: meta.text, background: meta.soft, padding: '2px 7px', borderRadius: 999, whiteSpace: 'nowrap'
    }}>
      <span style={{ width: 6, height: 6, borderRadius: 999, background: meta.color }} />
      {compact ? `${label} · ${sev.dias}d` : `${label} · ${sev.dias} ${sev.dias === 1 ? 'día' : 'días'}`}
    </span>);
}

// ¿Quedó registro de la tarea desde que se inició el destino?
function validarTarea(tarea) {
  if (tarea.tipo === 'entregar') {
    const entregados = window.loadEntregados ? window.loadEntregados() : [];
    const cods = (tarea.consecutivos || []).map(String);
    const hechos = cods.filter((c) => entregados.some((e) => String(e.codigo) === c));
    const gars = tarea.garantias || [];
    const garHechas = gars.filter((x) => { const g = window.garantiasDe ? window.garantiasDe(x.ticketId).find((y) => y.id === x.garId) : null; return g && g.estado === 'entregada'; });
    const total = cods.length + gars.length, nh = hechos.length + garHechas.length;
    return { tipo: 'entregar', ok: total > 0 && nh === total, hechos: nh, total };
  }
  const saved = window.loadPendientesSaved ? window.loadPendientesSaved() : [];
  const since = tarea.iniciadaEn || 0;
  const match = saved.filter((t) =>
  (t.taller || '') === tarea.taller && (t.sede || '') === tarea.sede && (
  !t.createdAt || t.createdAt >= since - 2000));
  return { tipo: 'recoger', ok: match.length > 0, refs: match.map((t) => '' + t.codigo) };
}

// Modo demo (13/11/2026, ahora en Mi perfil del admin › Pruebas): simula al mensajero
// avanzando su ruta de hoy. Cada llamada inicia la siguiente parada o completa la que está en curso.
window.simularAvanceRuta = function (usuario) {
  const hoy = fechaDDMMYYYY();
  const u = usuario || mensajeroPorDefecto();
  const nombre = (window.nombreDeUsuario && window.nombreDeUsuario(u)) || 'El mensajero';
  const mine = loadParadas().filter((p) => p.fecha === hoy && p.asignadoA === u && ['pendiente', 'en_curso', 'completada'].includes(p.estado));
  const destinos = groupByDestino(mine).sort((a, b) => a.orden - b.orden);
  const now = Date.now();
  const cur = destinos.find((d) => d.estado === 'en_curso');
  if (cur) {
    cur.tareas.forEach((t) => updateParada(t.id, { estado: 'completada', completadaEn: now }));
    if (cur.iniciadaEn) {
      try {
        const log = JSON.parse(localStorage.getItem('rodando.tiempos') || '[]');
        log.push({ taller: cur.taller, sede: cur.sede, ms: now - cur.iniciadaEn, fecha: hoy, ts: now });
        localStorage.setItem('rodando.tiempos', JSON.stringify(log));
      } catch (e) {}
    }
    return `${nombre} completó ${cur.taller} · ${cur.sede}.`;
  }
  const next = destinos.find((d) => d.estado === 'pendiente');
  if (next) {
    next.tareas.forEach((t) => updateParada(t.id, { estado: 'en_curso', iniciadaEn: now }));
    return `${nombre} inició ${next.taller} · ${next.sede}.`;
  }
  return 'No quedan paradas por avanzar hoy.';
};

// Helper para la píldora global de "ruta en curso" (la lee la cabecera).
window.getRutaEnCurso = function () {
  try {
    const hoy = fechaDDMMYYYY();
    // Por usuario (13/11/2026): solo la ruta de quien tiene la sesión abierta.
    const yo = ((window.usuarioActual && window.usuarioActual()) || {}).usuario;
    const enc = loadParadas().filter((p) => p.fecha === hoy && p.estado === 'en_curso' && (!yo || p.asignadoA === yo));
    if (!enc.length) return null;
    const inis = enc.filter((p) => p.iniciadaEn).map((p) => p.iniciadaEn);
    return { taller: enc[0].taller, sede: enc[0].sede, iniciadaEn: inis.length ? Math.min(...inis) : null };
  } catch (e) {return null;}
};

// ─── Pestaña: Mi ruta ────────────────────────────────────────────────────
function RutaTab({ role, admin, courierNombre, destinos, activos, completados, enCursoDestino, stats, totalDest, location, locationStatus, requestLocation, markers, onOpen, onIniciar, onRegistrar, onFinalizar, onReorder, onReprioritizar, onQuitar, onSimular, enCursoActivo, onIrPlanear, jornadaCerrada, onCerrarJornada, onReabrirJornada }) {
  const [showMap, setShowMap] = React.useState(false);
  const [showDone, setShowDone] = React.useState(false);

  // ── Arrastrar para reordenar destinos activos ──
  const [dragKey, setDragKey] = React.useState(null);
  const [toIdx, setToIdx] = React.useState(null);
  const [ghostY, setGhostY] = React.useState(0);
  const rowRefs = React.useRef({});
  const dragInfo = React.useRef(null);   // geometría capturada al levantar la tarjeta
  const toIdxRef = React.useRef(null);
  const lpTimer = React.useRef(null);     // temporizador del long-press

  // La parada en curso "asciende" a tarjeta destacada arriba (Opción B): se
  // muestra una sola vez; la secuencia de abajo lista solo lo que falta.
  const visibles = React.useMemo(() => activos.filter((d) => d.estado !== 'en_curso'), [activos]);

  // Levanta una tarjeta: captura su geometría y la de sus vecinas, deja un
  // clon "fantasma" siguiendo el dedo y hace que las demás abran hueco.
  const beginDrag = (key, e) => {
    if (dragInfo.current) return;
    if (e.pointerType === 'mouse' && e.button !== 0) return;
    const idx = visibles.findIndex((d) => d.key === key);
    const el = rowRefs.current[key];
    if (idx < 0 || !el) return;
    const r = el.getBoundingClientRect();
    const rects = visibles.map((d) => {
      const rr = rowRefs.current[d.key]?.getBoundingClientRect();
      return { key: d.key, top: rr ? rr.top : 0, h: rr ? rr.height : 0 };
    });
    dragInfo.current = { fromIdx: idx, h: r.height, w: r.width, left: r.left, grabDY: e.clientY - r.top, gap: 10, rects };
    toIdxRef.current = idx;
    setDragKey(key);
    setToIdx(idx);
    setGhostY(r.top);
    if (navigator.vibrate) { try { navigator.vibrate(12); } catch (err) {} }
  };

  React.useEffect(() => {
    if (!dragKey) return;
    document.body.style.userSelect = 'none';
    // Frenar el gesto de scroll del navegador en táctil (Android/iOS): el scroll
    // se gobierna por touchmove, no por pointermove. Sin esto la tarjeta no arrastra.
    const blockTouch = (e) => { if (e.cancelable) e.preventDefault(); };
    window.addEventListener('touchmove', blockTouch, { passive: false });
    const move = (e) => {
      const di = dragInfo.current;
      if (!di) return;
      const top = e.clientY - di.grabDY;
      setGhostY(top);
      const center = top + di.h / 2;
      let idx = di.rects.length - 1;
      for (let i = 0; i < di.rects.length; i++) {
        const rc = di.rects[i];
        if (center < rc.top + rc.h / 2) { idx = i; break; }
      }
      idx = Math.max(0, idx);
      if (idx !== toIdxRef.current && navigator.vibrate) navigator.vibrate(6);
      toIdxRef.current = idx;
      setToIdx(idx);
      if (e.cancelable) e.preventDefault();
    };
    const up = () => {
      const di = dragInfo.current;
      const from = di ? di.fromIdx : -1;
      const to = toIdxRef.current;
      if (from !== -1 && to != null && to !== from) {
        const keys = visibles.map((d) => d.key);
        const [k] = keys.splice(from, 1);
        keys.splice(to, 0, k);
        onReorder(keys);
        if (navigator.vibrate) navigator.vibrate(16);
      }
      if (di) { // tragarse el click que sigue al soltar (evita abrir la tarjeta)
        const swallow = (ev) => { ev.stopPropagation(); ev.preventDefault(); window.removeEventListener('click', swallow, true); };
        window.addEventListener('click', swallow, true);
        setTimeout(() => window.removeEventListener('click', swallow, true), 80);
      }
      dragInfo.current = null;
      toIdxRef.current = null;
      setDragKey(null);
      setToIdx(null);
    };
    window.addEventListener('pointermove', move, { passive: false });
    window.addEventListener('pointerup', up);
    window.addEventListener('pointercancel', up);
    return () => {
      document.body.style.userSelect = '';
      window.removeEventListener('touchmove', blockTouch);
      window.removeEventListener('pointermove', move);
      window.removeEventListener('pointerup', up);
      window.removeEventListener('pointercancel', up);
    };
  }, [dragKey, visibles, onReorder]);

  // Long-press en toda la tarjeta (además del agarre ≡) para levantarla.
  const cardLongPress = (key, estado) => (e) => {
    if (estado !== 'pendiente' || dragInfo.current) return;
    if (e.pointerType === 'mouse' && e.button !== 0) return;
    const sx = e.clientX, sy = e.clientY, pid = e.pointerId, ptype = e.pointerType;
    clearTimeout(lpTimer.current);
    const cleanup = () => {
      clearTimeout(lpTimer.current);
      window.removeEventListener('pointermove', onMove, { passive: true });
      window.removeEventListener('pointerup', cleanup);
      window.removeEventListener('pointercancel', cleanup);
    };
    const onMove = (ev) => {
      if (Math.abs(ev.clientX - sx) > 8 || Math.abs(ev.clientY - sy) > 8) cleanup();
    };
    lpTimer.current = setTimeout(() => {
      cleanup();
      beginDrag(key, { clientX: sx, clientY: sy, pointerId: pid, pointerType: ptype, button: 0, cancelable: false });
    }, 220);
    window.addEventListener('pointermove', onMove, { passive: true });
    window.addEventListener('pointerup', cleanup);
    window.addEventListener('pointercancel', cleanup);
  };

  return (
    <div>
      <ProgresoRuta role={role} courierNombre={courierNombre} totalDest={totalDest} stats={stats} locationStatus={locationStatus} requestLocation={requestLocation} />

      {totalDest === 0 ?
      jornadaCerrada ?
      <JornadaCerradaBanner stats={stats} onReabrir={onReabrirJornada} /> :

      <div style={{
        padding: 32, textAlign: 'center', color: TOKENS.textMuted, fontSize: 13,
        background: TOKENS.surfaceLow, borderRadius: 12, border: `1px dashed ${TOKENS.border}`
      }}>
          <div style={{ fontWeight: 700, color: TOKENS.text, fontSize: 14, marginBottom: 4 }}>{admin ? `La ruta de ${courierNombre} está vacía` : 'Tu ruta está vacía'}</div>
          <div style={{ marginBottom: 14 }}>{admin ? 'Agrégale tareas desde la bandeja "Por planear".' : 'Arma tu ruta desde la bandeja "Por planear".'}</div>
          <Button variant="primary" icon={I.route(16, '#fff')} onClick={onIrPlanear}>{admin ? 'Agregar tareas' : 'Ir a planear'}</Button>
        </div> :


      <>
          {/* Mapa plegable (de apoyo) */}
          {markers.length > 0 &&
        <div style={{ marginBottom: 14 }}>
              <button onClick={() => setShowMap((s) => !s)} style={{
            width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '10px 14px', borderRadius: 10, cursor: 'pointer', fontFamily: 'inherit',
            background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, color: TOKENS.text,
            fontSize: 13, fontWeight: 600
          }}>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>{I.map(16, TOKENS.primary)} {showMap ? 'Ocultar mapa' : 'Ver mapa de la ruta'}</span>
                <span style={{ transform: showMap ? 'rotate(180deg)' : 'none', transition: 'transform 0.18s', display: 'flex' }}>{I.chev(16, TOKENS.textMuted)}</span>
              </button>
              {showMap &&
          <div style={{ marginTop: 10 }}>
                  <MapView markers={markers} currentLocation={location} height={200} fitBounds />
                </div>
          }
            </div>
        }

          {/* Parada en curso: sube arriba (13/11/2026) */}
          {enCursoDestino &&
        <>
              <SectionHeader title="Parada en curso" />
              <PromotedEnCurso destino={enCursoDestino} admin={admin} role={role}
            onOpen={onOpen} onRegistrar={onRegistrar} onFinalizar={onFinalizar} />
              <div style={{ height: 10 }} />
            </>
        }

          {/* Secuencia del día (lo que falta, arrastrable) */}
          <SectionHeader title={enCursoDestino ? 'Siguientes' : 'Secuencia del día'} count={visibles.length}
        hint={admin ? 'Mantén presionado ≡ para reordenar lo pendiente · lo iniciado o hecho queda bloqueado' : 'Mantén presionado ≡ para cambiar el orden. La de arriba es la próxima.'} />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 18 }}>
            {visibles.map((d, i) => {
            const di = dragInfo.current;
            const isDragged = dragKey === d.key;
            let ty = 0;
            if (dragKey && di && !isDragged && toIdx != null) {
              const blk = di.h + di.gap;
              const from = di.fromIdx, to = toIdx;
              if (from < to && i > from && i <= to) ty = -blk;
              else if (to < from && i >= to && i < from) ty = blk;
            }
            return (
              <div key={d.key}
              ref={(el) => rowRefs.current[d.key] = el}
              onPointerDown={d.estado === 'pendiente' && !isDragged ? cardLongPress(d.key, d.estado) : undefined}
              style={{
                borderRadius: 14,
                transform: `translateY(${ty}px)`,
                transition: dragKey ? 'transform 0.2s cubic-bezier(0.2,0.8,0.2,1)' : 'none',
                opacity: isDragged ? 0 : (dragKey ? 0.9 : 1),
                touchAction: dragKey ? 'none' : 'auto',
                WebkitUserSelect: 'none', userSelect: 'none', WebkitTouchCallout: 'none',
              }}>
                  <DestinoCard
                  destino={d} index={i + 1}
                  admin={admin}
                  isEnCurso={false}
                  canStart={!enCursoDestino}
                  dragging={isDragged}
                  onDragStart={d.estado === 'pendiente' ? (e) => beginDrag(d.key, e) : undefined}
                  onOpen={onOpen} onIniciar={onIniciar} onRegistrar={onRegistrar} onFinalizar={onFinalizar}
                  onReprioritizar={onReprioritizar} onQuitar={onQuitar} />
                </div>);

          })}
            {visibles.length === 0 &&
          <EmptyHint text={enCursoDestino ? 'Esta es tu última parada. ¡Vas terminando!' : 'No quedan paradas activas. ¡Buen trabajo!'} />
          }
          </div>

          {/* Clon "fantasma" que sigue el dedo mientras reordenas */}
          {dragKey && dragInfo.current && (() => {
            const dd = visibles.find((x) => x.key === dragKey);
            if (!dd) return null;
            const di = dragInfo.current;
            return (
              <div style={{
                position: 'fixed', left: Math.round(di.left), width: di.w, top: Math.round(ghostY),
                zIndex: 9999, pointerEvents: 'none', borderRadius: 14,
                transform: 'scale(1.02)', transformOrigin: '50% 50%',
                boxShadow: '0 18px 40px rgba(11,28,48,0.30), 0 4px 12px rgba(11,28,48,0.18)',
                willChange: 'transform, top',
              }}>
                <DestinoCard destino={dd} index={(toIdx != null ? toIdx : di.fromIdx) + 1}
                  admin={admin} isEnCurso={false} canStart={false} dragging />
              </div>);
          })()}

          {/* Completadas (plegable) */}
          {completados.length > 0 &&
        <div>
              <button onClick={() => setShowDone((s) => !s)} style={{
            width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '11px 14px', borderRadius: 10, cursor: 'pointer', fontFamily: 'inherit',
            background: TOKENS.surface, border: `1px solid ${TOKENS.border}`,
            color: TOKENS.textMuted, fontSize: 13, fontWeight: 700, marginBottom: showDone ? 10 : 0
          }}>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                  {I.check(16, TOKENS.textMuted)} Completadas · {completados.length}
                </span>
                <span style={{ transform: showDone ? 'rotate(180deg)' : 'none', transition: 'transform 0.18s', display: 'flex' }}>{I.chev(16, TOKENS.textMuted)}</span>
              </button>
              {showDone &&
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                  {completados.map((d) =>
            <DestinoCard key={d.key} destino={d} index={null} done admin={admin}
            onOpen={onOpen} onIniciar={onIniciar} onRegistrar={onRegistrar} onFinalizar={onFinalizar} />
            )}
                </div>
          }
            </div>
        }

          {/* Cierre de jornada — solo el mensajero cierra su día */}
          {!admin &&
        <div style={{ marginTop: 22, paddingTop: 18, borderTop: `1px solid ${TOKENS.border}` }}>
            {jornadaCerrada ?
          <JornadaCerradaBanner stats={stats} onReabrir={onReabrirJornada} compact /> :

          <>
                <div style={{ fontSize: 12, color: TOKENS.textMuted, lineHeight: 1.5, marginBottom: 10 }}>
                  Al terminar tu día, cierra la jornada. Lo que no completaste vuelve a <b style={{ color: TOKENS.text }}>Por planear</b> — nada se arrastra solo a mañana.
                </div>
                <Button variant="outline" full icon={I.check(16, TOKENS.text)} onClick={onCerrarJornada}>
                  Cerrar jornada
                </Button>
              </>
          }
          </div>
        }

        </>
      }
    </div>);

}

// Banner dinámico: progreso + parada actual + cronómetro en vivo.
function BannerRuta({ role, totalDest, stats, enCursoDestino, locationStatus, requestLocation }) {
  const done = stats.completada;
  const pct = totalDest ? Math.round(done / totalDest * 100) : 0;
  const pos = Math.min(done + 1, totalDest);
  return (
    <div style={{ background: TOKENS.heroGradient, color: '#fff', borderRadius: 14, padding: '16px 16px 14px', marginBottom: 14, position: 'relative', overflow: 'hidden' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
        <div style={{ fontSize: 10, opacity: 0.72, letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 700 }}>
          {role === 'admin' ? (window.userName ? window.userName() : 'Juan Diego') + ' · ' : ''}Hoy · {fechaCorta()}
        </div>
        {role !== 'admin' &&
        <button onClick={requestLocation} style={{
          padding: '6px 10px', borderRadius: 8, fontSize: 11, fontWeight: 700,
          background: locationStatus === 'ok' ? TOKENS.success : 'rgba(255,255,255,0.15)',
          color: '#fff', border: 'none', cursor: 'pointer', fontFamily: 'inherit',
          display: 'inline-flex', alignItems: 'center', gap: 5, letterSpacing: '0.04em', flexShrink: 0
        }}>
            {I.map(13, '#fff')}
            {locationStatus === 'ok' ? 'Ubicado' : locationStatus === 'asking' ? '…' : 'Estoy aquí'}
          </button>
        }
      </div>

      {enCursoDestino ?
      <div>
          <div style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#ffd9a0', display: 'flex', alignItems: 'center', gap: 7 }}>
            <span style={{ width: 8, height: 8, borderRadius: 999, background: '#ffce86', animation: 'rdPulse 1.8s infinite' }} />
            En curso ahora
          </div>
          <div style={{ fontSize: 22, fontWeight: 800, marginTop: 5, letterSpacing: '-0.01em' }}>
            {enCursoDestino.taller}<span style={{ opacity: 0.65, fontWeight: 600 }}> · {enCursoDestino.sede}</span>
          </div>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, marginTop: 9, background: 'rgba(255,206,134,0.16)', border: '1px solid rgba(255,206,134,0.45)', borderRadius: 999, padding: '6px 13px' }}>
            {I.clock(15, '#ffd9a0')}
            <span style={{ fontFamily: 'monospace', fontSize: 19, fontWeight: 800, color: '#ffe6c2', letterSpacing: '0.02em' }}>
              <LiveTimer since={enCursoDestino.iniciadaEn} />
            </span>
          </div>
        </div> :

      <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: '-0.01em' }}>
          {totalDest > 0 ? `Parada ${pos} de ${totalDest}` : 'Sin paradas en la ruta'}
        </div>
      }

      {totalDest > 0 &&
      <div style={{ marginTop: 14 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, fontWeight: 700, opacity: 0.85, marginBottom: 6 }}>
            <span>{done} de {totalDest} completadas</span><span>{pct}%</span>
          </div>
          <div style={{ height: 9, borderRadius: 999, background: 'rgba(255,255,255,0.16)', overflow: 'hidden' }}>
            <div style={{ width: pct + '%', height: '100%', background: 'linear-gradient(90deg,#7fe0a8,#36c97f)', borderRadius: 999, transition: 'width .45s cubic-bezier(.2,.8,.2,1)' }} />
          </div>
        </div>
      }

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8, marginTop: 14 }}>
        <MiniNavyStat n={stats.pendiente} label="Pendientes" />
        <MiniNavyStat n={stats.enCurso} label="En curso" />
        <MiniNavyStat n={stats.completada} label="Completadas" />
      </div>
    </div>);

}

// ── Color del estado "en curso" (ligado a Tweaks) + derivados (Tonos) ──
function _rutaH2r(h){h=String(h||'#e67c0a').replace('#','');if(h.length===3)h=h.split('').map(c=>c+c).join('');return [parseInt(h.slice(0,2),16),parseInt(h.slice(2,4),16),parseInt(h.slice(4,6),16)];}
function _rutaMix(hex,to,amt){const c=_rutaH2r(hex);const m=(a,b)=>Math.round(a+(b-a)*amt);return `rgb(${m(c[0],to[0])},${m(c[1],to[1])},${m(c[2],to[2])})`;}
const rutaLite=(hex,amt)=>_rutaMix(hex,[255,255,255],amt);
const rutaDark=(hex,amt)=>_rutaMix(hex,[0,0,0],amt);
function enCursoColor(){ return (window.TOKENS && window.TOKENS.enCurso) || '#e67c0a'; }

// Tarjeta "en curso" ASCENDIDA (Opción B): la parada actual se muestra una sola
// vez, destacada arriba como tarjeta clara con acentos del color en curso.
function PromotedEnCurso({ destino, admin, role, onOpen, onRegistrar, onFinalizar }) {
  return (
    <div style={{ background: TOKENS.surface, borderRadius: 14, border: `1.5px solid ${TOKENS.caution}`, boxShadow: `0 0 0 3px ${TOKENS.cautionBg}`, padding: '12px 13px 13px', marginBottom: 6 }}>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11.5, fontWeight: 500, color: TOKENS.cautionText, background: TOKENS.cautionBg, borderRadius: 999, padding: '3px 10px' }}>
        <span style={{ width: 7, height: 7, borderRadius: 999, background: TOKENS.cautionText, animation: 'rdBlink 1.4s infinite' }} />
        En curso · <span style={{ fontFamily: "'JetBrains Mono', monospace" }}><LiveTimer since={destino.iniciadaEn} /></span>
      </span>
      {destino.prioridad === 'alta' && <div style={{ marginTop: 6 }}><PrioridadTag /></div>}
      <div style={{ fontSize: 17, fontWeight: 700, color: TOKENS.text, marginTop: 7 }}>
        {destino.taller}{destino.sede && <span style={{ color: TOKENS.textMuted, fontWeight: 500 }}> · {destino.sede}</span>}
      </div>
      {destino.direccion && <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>{destino.direccion}</div>}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginTop: 10 }}>
        {destino.tareas.map((t) =>
        <TareaRow key={t.id} tarea={t} canRegister={!admin} done={false}
        onOpen={() => onOpen(t.id)} onRegistrar={() => onRegistrar(t)} />
        )}
      </div>
      {!admin && <UbicacionSedeAviso taller={destino.taller} sede={destino.sede} />}
      {admin ?
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 12, padding: '9px 12px', borderRadius: 10, background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, fontSize: 12, fontWeight: 600, color: TOKENS.textMuted }}>
          {I.lock ? I.lock(14, TOKENS.textMuted) : null} La maneja el mensajero — no editable
        </div> :
      <div style={{ display: 'grid', gap: 8, marginTop: 12 }}>
          <Button variant="primary" full icon={I.check(16, '#fff')} onClick={() => onFinalizar(destino)} style={{ padding: '13px' }}>Finalizar parada</Button>
          {destino.lat != null && <Button variant="outline" full icon={I.map(16, TOKENS.primary)} onClick={() => openInMaps(destino)} style={{ color: TOKENS.primary }}>Abrir en Maps</Button>}
        </div>
      }
    </div>);

}

// Línea de progreso de la ruta (13/11/2026): reemplaza el cuadro azul grande.
function ProgresoRuta({ role, totalDest, stats, locationStatus, requestLocation, courierNombre }) {
  const done = stats.completada;
  const pct = totalDest ? Math.round(done / totalDest * 100) : 0;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 12, padding: '10px 12px', marginBottom: 10 }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: TOKENS.text }}>{totalDest ? `${done} de ${totalDest} completadas` : 'Sin paradas en la ruta'}</div>
        <div style={{ fontSize: 11.5, color: TOKENS.textMuted, fontWeight: 600, marginTop: 1 }}>{role === 'admin' && courierNombre ? courierNombre + ' · ' : ''}Hoy · {fechaCorta()}</div>
        {totalDest > 0 &&
        <div style={{ height: 6, borderRadius: 999, background: TOKENS.surfaceLow, overflow: 'hidden', marginTop: 6 }}>
            <div style={{ width: pct + '%', height: '100%', background: TOKENS.primary, borderRadius: 999, transition: 'width .45s cubic-bezier(.2,.8,.2,1)' }} />
          </div>
        }
      </div>
      {role !== 'admin' &&
      <button onClick={requestLocation} style={{
        display: 'inline-flex', alignItems: 'center', gap: 5, padding: '7px 10px', borderRadius: 9, flexShrink: 0,
        border: `1px solid ${TOKENS.borderInput}`, background: TOKENS.surface, color: TOKENS.primary,
        fontFamily: 'inherit', fontSize: 12, fontWeight: 700, cursor: 'pointer'
      }}>{I.map(13, TOKENS.primary)}{locationStatus === 'ok' ? 'Ubicado' : locationStatus === 'asking' ? '…' : 'Estoy aquí'}</button>
      }
    </div>);

}

// Tarjeta de un DESTINO (lugar) con sus tareas y acciones.
// 25/11/2026: si el taller no tiene ubicación guardada, César la guarda con un toque al llegar.
function UbicacionSedeAviso({ taller, sede }) {
  const [est, setEst] = React.useState('idle'); // idle | buscando | ok | err | no
  const u = window.catUbicacion ? window.catUbicacion(taller, sede) : null;
  if (!u || est === 'no' || (u.lat != null && u.lng != null && est !== 'ok')) return null;
  if (est === 'ok') return <div style={{ marginTop: 10, fontSize: 12.5, fontWeight: 600, color: TOKENS.successText, background: TOKENS.successBg, borderRadius: 10, padding: '8px 11px' }}>✓ Ubicación del taller guardada</div>;
  const guardar = () => {
    if (!navigator.geolocation) { setEst('err'); return; }
    setEst('buscando');
    navigator.geolocation.getCurrentPosition((p) => { const ok = window.catGuardarUbicacion && window.catGuardarUbicacion(taller, sede, +p.coords.latitude.toFixed(6), +p.coords.longitude.toFixed(6)); setEst(ok ? 'ok' : 'err'); },
      () => setEst('err'), { enableHighAccuracy: true, timeout: 12000 });
  };
  return (
    <div style={{ marginTop: 10, border: `1px solid ${TOKENS.border}`, background: TOKENS.surfaceLow, borderRadius: 11, padding: '10px 11px' }}>
      <div style={{ fontSize: 12.5, color: TOKENS.text, lineHeight: 1.4 }}>Este taller no tiene ubicación guardada. Si estás en la puerta, guárdala con un toque.</div>
      {est === 'err' && <div style={{ fontSize: 12, color: TOKENS.dangerText, marginTop: 5 }}>No se pudo tomar la ubicación. Revisa que la ubicación del celular esté activada.</div>}
      <div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
        <button type="button" onClick={guardar} disabled={est === 'buscando'} style={{ flex: 1, border: 0, borderRadius: 9, padding: '9px 10px', fontFamily: 'inherit', fontSize: 13, fontWeight: 700, background: TOKENS.primary, color: '#fff', cursor: 'pointer', opacity: est === 'buscando' ? 0.6 : 1 }}>{est === 'buscando' ? 'Tomando ubicación…' : '📍 Guardar ubicación aquí'}</button>
        <button type="button" onClick={() => setEst('no')} style={{ border: `1px solid ${TOKENS.borderInput}`, borderRadius: 9, padding: '9px 12px', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, background: TOKENS.surface, color: TOKENS.textMuted, cursor: 'pointer' }}>Ahora no</button>
      </div>
    </div>);
}
function DestinoCard({ destino, index, admin, isEnCurso, canStart, done, dragging, onDragStart, onOpen, onIniciar, onRegistrar, onFinalizar, onReprioritizar, onQuitar }) {
  const yellow = isEnCurso;
  return (
    <Card style={{ padding: 0, overflow: 'hidden', background: TOKENS.surface, border: yellow ? `1.5px solid ${TOKENS.caution}` : undefined }}>
      <div style={{ padding: '12px 12px 13px 6px', display: 'flex', alignItems: 'flex-start', gap: 8 }}>
        {/* handle + número */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, flexShrink: 0, paddingTop: 1 }}>
          {!done && onDragStart &&
          <div onPointerDown={(e) => { e.stopPropagation(); onDragStart && onDragStart(e); }} title="Arrastrar para reordenar" style={{
            cursor: dragging ? 'grabbing' : 'grab', padding: 2, color: TOKENS.textSubtle,
            touchAction: 'none', display: 'flex', lineHeight: 1
          }}>{I.drag ? I.drag(16, TOKENS.textSubtle) : <span style={{ fontSize: 15, fontWeight: 700 }}>≡</span>}</div>
          }
          <div style={{
            width: 30, height: 30, borderRadius: 999, flexShrink: 0,
            background: yellow ? TOKENS.cautionBg : TOKENS.surfaceLow,
            color: yellow ? TOKENS.cautionText : done ? TOKENS.textMuted : TOKENS.primary,
            display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 13
          }}>{done ? I.check(16, TOKENS.textMuted) : index}</div>
        </div>

        <div style={{ flex: 1, minWidth: 0 }}>
          {(yellow || (destino.prioridad === 'alta' && !done)) &&
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', marginBottom: 5 }}>
            {yellow &&
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 9, fontWeight: 600, color: TOKENS.cautionText, background: TOKENS.cautionBg, padding: '2px 7px', borderRadius: 999, letterSpacing: '0.06em' }}>
                <span style={{ width: 6, height: 6, borderRadius: 999, background: TOKENS.caution, animation: 'rdBlink 1.4s infinite' }} />EN CURSO
              </span>
            }
            {destino.prioridad === 'alta' && !done && <PrioridadTag />}
          </div>}

          <div style={{ fontSize: 16, fontWeight: 700, color: TOKENS.text, letterSpacing: '-0.01em' }}>
            {destino.taller}{destino.sede && <span style={{ color: TOKENS.textMuted, fontWeight: 500 }}> · {destino.sede}</span>}
          </div>
          <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>{destino.direccion}</div>

          {/* tareas del destino */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginTop: 9 }}>
            {destino.tareas.map((t) =>
            <TareaRow key={t.id} tarea={t} canRegister={yellow && !admin} done={done}
            onOpen={() => onOpen(t.id)} onRegistrar={() => onRegistrar(t)} />
            )}
          </div>

          {yellow && !admin && <UbicacionSedeAviso taller={destino.taller} sede={destino.sede} />}
          {yellow &&
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7, marginTop: 10, background: TOKENS.cautionBg, border: `1px solid ${TOKENS.caution}`, borderRadius: 999, padding: '4px 11px' }}>
              {I.clock(13, TOKENS.cautionText)}
              <span style={{ fontFamily: 'monospace', fontSize: 14, fontWeight: 800, color: TOKENS.cautionText }}>
                <LiveTimer since={destino.iniciadaEn} until={destino.completadaEn} />
              </span>
            </div>
          }

          {done && destino.completadaEn &&
          <div style={{ fontSize: 11.5, color: TOKENS.textMuted, marginTop: 9, display: 'inline-flex', alignItems: 'center', gap: 6, fontWeight: 600 }}>
              {I.check(13, TOKENS.textMuted)} {new Date(destino.completadaEn).toLocaleTimeString('es-CO', { hour: '2-digit', minute: '2-digit' })}
              {destino.iniciadaEn && <> · {durTexto(destino.iniciadaEn, destino.completadaEn)}</>}
            </div>
          }

          {!done && (
          admin ?
          destino.estado === 'pendiente' ?
          <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
                  <button onClick={() => onReprioritizar(destino)} style={{
              flex: 1, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
              padding: '9px 10px', borderRadius: 10, fontSize: 12.5, fontWeight: 700, fontFamily: 'inherit', cursor: 'pointer',
              border: `1px solid ${destino.prioridad === 'alta' ? TOKENS.text : TOKENS.borderInput}`,
              background: TOKENS.surface,
              color: TOKENS.text
            }}>
                    ↑ {destino.prioridad === 'alta' ? 'Con prioridad' : 'Dar prioridad'}
                  </button>
                  <button onClick={() => onQuitar(destino)} style={{
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
              padding: '9px 12px', borderRadius: 10, fontSize: 12.5, fontWeight: 700, fontFamily: 'inherit', cursor: 'pointer',
              border: `1px solid ${TOKENS.borderInput}`, background: TOKENS.surface, color: TOKENS.textMuted
            }}>{I.trash ? I.trash(15, TOKENS.textMuted) : I.x(15, TOKENS.textMuted)} Quitar</button>
                </div> :

          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 12, padding: '9px 12px', borderRadius: 10, background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, fontSize: 12, fontWeight: 600, color: TOKENS.textMuted }}>
                  {I.lock ? I.lock(14, TOKENS.textMuted) : null}
                  En curso · la maneja el mensajero — no editable
                </div> :


          <div style={{ marginTop: 12 }}>
              {destino.estado === 'pendiente' ?
            <Button variant="primary" full icon={(destino.tareas || []).every((t) => t.tipo === 'recoger') ? I.recoger(16, canStart ? '#fff' : TOKENS.textMuted) : I.truck(16, canStart ? '#fff' : TOKENS.textMuted)} disabled={!canStart} onClick={() => onIniciar(destino)}>
                  Iniciar parada
                </Button> :

            <Button variant="primary" full icon={I.check(16, '#fff')} onClick={() => onFinalizar(destino)}>
                  Finalizar parada
                </Button>
            }
            </div>)

          }
        </div>
      </div>
    </Card>);

}

// Placa(s) de una tarea de entrega, buscadas por consecutivo.
function tareaPlacas(tarea) {
  if (!tarea || tarea.tipo !== 'entregar') return [];
  const cods = (tarea.consecutivos || []).map(String);
  const all = [
  ...(window.loadPendientesSaved ? window.loadPendientesSaved() : []),
  ...(window.PENDIENTES_DEMO || [])];

  return [...cods.map((c) => {
    const t = all.find((x) => String(x.codigo) === c);
    return { codigo: c, placa: t ? t.placa : null };
  }), ...(tarea.garantias || []).map((x) => ({ codigo: x.codigo, placa: x.placa, gar: true }))];
}

// 23/11/2026: encargo dentro de una parada. "Hecho" abre la hoja del encargo (foto, nota y, si es
// Entregar con placa, factura o remisión).
function TareaEncargoRow({ tarea, canRegister, done }) {
  if (window.useEncargos) window.useEncargos();
  const e = (window.loadEncargos ? window.loadEncargos() : []).find((x) => x.id === tarea.encargoId);
  const [abierto, setAbierto] = React.useState(false);
  const hecho = e && e.estado === 'hecho';
  const T = (window.ENC_TIPO || {})[(e && e.tipo) || tarea.encTipo] || ['✓', 'Encargo']; const encTipo = (e && e.tipo) || tarea.encTipo;
  return (
    <div style={{ padding: '9px 10px', background: TOKENS.surfaceLow, borderRadius: 11, border: `1px solid ${TOKENS.border}` }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 6 }}>
        {window.EncEtiquetas ? <window.EncEtiquetas tipo={encTipo} fondo={TOKENS.surface} /> : null}
        {hecho && <span style={{ fontSize: 11, fontWeight: 600, borderRadius: 999, padding: '3px 8px', background: TOKENS.successBg, color: TOKENS.successText }}>✓ Hecho</span>}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 7 }}>
        <span style={{ flex: 1, minWidth: 0, fontSize: 13, fontWeight: 600, color: hecho ? TOKENS.textSubtle : TOKENS.text, textDecoration: hecho ? 'line-through' : 'none' }}>{(e && e.que) || tarea.referencia}</span>
        {e && e.placa && <PlacaOrdenChica placa={e.placa} fondo={TOKENS.surface} />}
        {canRegister && !done && !hecho && e && <button onClick={() => setAbierto(true)} style={{ flexShrink: 0, display: 'inline-flex', alignItems: 'center', gap: 4, padding: '6px 11px', borderRadius: 7, fontSize: 11.5, fontWeight: 700, background: TOKENS.primary, color: '#fff', border: 'none', cursor: 'pointer', fontFamily: 'inherit' }}>✓ Hecho</button>}
      </div>
      {e && e.nota && <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 5 }}>{e.nota}</div>}
      {abierto && e && window.EncargoHechoSheet && ReactDOM.createPortal(<window.EncargoHechoSheet e={e} onClose={() => setAbierto(false)} />, document.body)}
    </div>);
}
// Fila de una tarea dentro de un destino. Cuando el destino está en curso,
// ofrece "Registrar" (abre Recoger/Entregar); si no, abre el detalle.
// Tarea dentro de un destino (13/11/2026): tipo (neutro) + estado arriba; placa en
// recuadro con el consecutivo pequeño; abajo ítems o referencia. "Registrar" si está en curso.
function TareaRow({ tarea, canRegister, done, onOpen, onRegistrar }) {
  if (tarea.tipo === 'encargo') return <TareaEncargoRow tarea={tarea} canRegister={canRegister} done={done} />;
  const isEnt = tarea.tipo === 'entregar';
  const placas = isEnt ? tareaPlacas(tarea) : (tarea.placas || []).map((p) => ({ placa: p }));
  const e = done ? null : tareaEstado(tarea);
  let items = tarea.referencia || (isEnt ? '' : 'Recogida');
  if (isEnt) {
    const all = [...(window.loadPendientesSaved ? window.loadPendientesSaved() : []), ...(window.PENDIENTES_DEMO || [])];
    const tk = all.find((x) => placas[0] && String(x.codigo) === String(placas[0].codigo));
    if (tk && window.ticketSummary) {
      const sm = window.ticketSummary(tk);
      items = [sm.rines && `${sm.rines} ${sm.rines === 1 ? 'rin' : 'rines'}`, sm.llantas && `${sm.llantas} ${sm.llantas === 1 ? 'llanta' : 'llantas'}`, sm.valvulas && `${sm.valvulas} ${sm.valvulas === 1 ? 'válvula' : 'válvulas'}`].filter(Boolean).join(' · ');
    }
  }
  const nGar = (tarea.garantias || []).length;
  if (nGar) items = [items && (tarea.consecutivos || []).length ? items : '', `↺ ${nGar} ${nGar === 1 ? 'garantía' : 'garantías'}`].filter(Boolean).join(' · ');
  const action = canRegister && !done ?
  <button onClick={onRegistrar} style={{
    flexShrink: 0, display: 'inline-flex', alignItems: 'center', gap: 4, padding: '6px 11px', borderRadius: 7,
    fontSize: 11.5, fontWeight: 700, background: TOKENS.primary, color: '#fff', border: 'none', cursor: 'pointer', fontFamily: 'inherit'
  }}>{tarea.tipo === 'recoger' ? I.recoger(12, '#fff') : I.truck(12, '#fff')} Registrar</button> :
  <button onClick={onOpen} aria-label="Ver detalle" style={{ flexShrink: 0, background: 'transparent', border: 'none', cursor: 'pointer', padding: 4, display: 'flex' }}>{I.chevRight(14, TOKENS.textMuted)}</button>;
  return (
    <div style={{ padding: '9px 10px', background: TOKENS.surfaceLow, borderRadius: 11, border: `1px solid ${TOKENS.border}` }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 6 }}>
        <span style={{ display: 'inline-flex', gap: 5, alignItems: 'center' }}><TipoTag tipo={tarea.tipo} />{isEnt && window.catMensajeroRecoge && !window.catMensajeroRecoge(tarea.taller, tarea.sede) && <span title="Deja los rines en la transportadora y registra la guía" style={{ fontSize: 10, fontWeight: 800, letterSpacing: '0.04em', color: '#8a5a00', background: '#fdf0d5', border: '1px solid #f0d9a8', borderRadius: 6, padding: '2px 6px' }}>POR TRANSPORTADORA</span>}</span>
        <EstadoChip e={e} />
      </div>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 8, marginTop: 7 }}>
        {placas.length ?
        <PlacaOrdenChica placa={placas[0].placa} codigo={isEnt ? placas[0].codigo : null} fondo={TOKENS.surface} /> :
        <span style={{ fontSize: 11, fontWeight: 700, color: TOKENS.textSubtle, border: `1px dashed ${TOKENS.borderInput}`, borderRadius: 6, padding: '3px 7px' }}>Sin placa</span>}
        {placas.length > 1 && <span style={{ fontSize: 11.5, color: TOKENS.textMuted, fontWeight: 700 }}>+{placas.length - 1}</span>}
        <span style={{ flex: 1 }} />
        {action}
      </div>
      {items && <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 5 }}>{items}</div>}
    </div>);

}

// Modal de validación al finalizar un destino.
function FinalizarDestinoModal({ destino, onDismiss, onConfirm }) {
  const checks = destino.tareas.map((t) => ({ tarea: t, val: validarTarea(t) }));
  const allOk = checks.every((c) => c.val.ok);
  return (
    <div onClick={onDismiss} style={{
      position: 'fixed', inset: 0, background: 'rgba(11,28,48,0.5)', zIndex: 1000,
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center'
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: TOKENS.surface, borderRadius: '18px 18px 0 0',
        width: '100%', maxWidth: 440, padding: 18, paddingBottom: 24, maxHeight: '85vh', overflow: 'auto'
      }}>
        <div style={{ width: 36, height: 4, borderRadius: 2, background: TOKENS.border, margin: '0 auto 14px' }} />
        <div style={{ fontSize: 20, fontWeight: 800, color: TOKENS.text, letterSpacing: '-0.01em' }}>Finalizar parada</div>
        <div style={{ fontSize: 13, color: TOKENS.textMuted, marginTop: 2 }}>{destino.taller}{destino.sede ? ' · ' + destino.sede : ''}</div>

        {destino.iniciadaEn &&
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7, marginTop: 12, background: TOKENS.cautionBg, border: `1px solid ${TOKENS.caution}`, borderRadius: 999, padding: '5px 12px' }}>
            {I.clock(14, TOKENS.cautionText)}
            <span style={{ fontFamily: 'monospace', fontSize: 15, fontWeight: 800, color: TOKENS.cautionText }}>
              <LiveTimer since={destino.iniciadaEn} />
            </span>
            <span style={{ fontSize: 11, color: TOKENS.cautionText, fontWeight: 700 }}>en sitio</span>
          </div>
        }

        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 16 }}>
          {checks.map(({ tarea, val }, i) => {
            const msg = val.tipo === 'entregar' ?
            val.ok ? `Entrega registrada · ${val.hechos}/${val.total} órdenes` : `Entrega incompleta · ${val.hechos}/${val.total} registrados` :
            val.ok ? `Recogida registrada${val.refs.length ? ' · ' + val.refs.join(', ') : ''}` : 'Sin registro de recogida desde que iniciaste';
            return (
              <div key={i} style={{
                display: 'flex', alignItems: 'flex-start', gap: 10, padding: '10px 12px', borderRadius: 10,
                background: val.ok ? TOKENS.successBg : TOKENS.warningBg,
                border: `1px solid ${val.ok ? TOKENS.successBorder || TOKENS.border : TOKENS.warning}`
              }}>
                <div style={{ flexShrink: 0, width: 22, height: 22, borderRadius: 999, background: val.ok ? TOKENS.success : TOKENS.warning, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 800 }}>
                  {val.ok ? I.check(14, '#fff') : '!'}
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 700, color: TOKENS.text }}>
                    {tipoLabel(tarea.tipo)} · {tarea.taller}
                  </div>
                  <div style={{ fontSize: 12, color: val.ok ? TOKENS.successText : TOKENS.warningText, marginTop: 2, fontWeight: 600 }}>{msg}</div>
                </div>
              </div>);

          })}
        </div>

        {!allOk &&
        <div style={{ marginTop: 12, fontSize: 12, color: TOKENS.warningText, background: TOKENS.warningBg, border: `1px solid ${TOKENS.warning}`, borderRadius: 10, padding: '10px 12px', lineHeight: 1.45 }}>
            Hay tareas sin registro. Puedes registrarlas antes de cerrar, o finalizar de todos modos si ya no aplican.
          </div>
        }

        <div style={{ marginTop: 18, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <Button variant="outline" full onClick={onDismiss}>Volver</Button>
          <Button variant="primary" full icon={I.check(16, '#fff')} onClick={onConfirm}
          style={{ background: allOk ? TOKENS.success : TOKENS.warning, borderColor: allOk ? TOKENS.success : TOKENS.warning }}>
            {allOk ? 'Finalizar' : 'Finalizar igual'}
          </Button>
        </div>
      </div>
    </div>);

}

// ─── Componentes auxiliares ─────────────────────────────────────────────
// Banner de jornada cerrada (en "Mi ruta", tras cerrar el día).
function JornadaCerradaBanner({ stats, onReabrir, compact }) {
  return (
    <div style={{
      background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 14,
      padding: compact ? '14px 16px' : '24px 20px', textAlign: 'center'
    }}>
      <div style={{
        width: 44, height: 44, borderRadius: 999, background: TOKENS.successBg,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 10
      }}>{I.check(24, TOKENS.primary)}</div>
      <div style={{ fontSize: 16, fontWeight: 800, color: TOKENS.text, letterSpacing: '-0.01em' }}>Jornada cerrada</div>
      <div style={{ fontSize: 12.5, color: TOKENS.textMuted, marginTop: 4, lineHeight: 1.5 }}>
        {stats.completada} {stats.completada === 1 ? 'parada completada' : 'paradas completadas'} hoy.
        Lo que quedó pendiente está en <b style={{ color: TOKENS.text }}>Por planear</b>.
      </div>
      <button onClick={onReabrir} style={{
        marginTop: 14, padding: '8px 16px', borderRadius: 999, fontSize: 12, fontWeight: 700,
        background: 'transparent', border: `1px solid ${TOKENS.borderInput}`, color: TOKENS.text,
        cursor: 'pointer', fontFamily: 'inherit'
      }}>Reabrir jornada</button>
    </div>);

}

// Modal de cierre de jornada: resumen del día + destino de lo no terminado.
function CerrarJornadaModal({ activos, completados, stats, onDismiss, onConfirm }) {
  const sinTerminar = activos || [];
  const hechas = completados || [];
  return (
    <div onClick={onDismiss} style={{
      position: 'fixed', inset: 0, background: 'rgba(11,28,48,0.5)', zIndex: 1000,
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center'
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: TOKENS.surface, borderRadius: '18px 18px 0 0',
        width: '100%', maxWidth: 440, padding: 18, paddingBottom: 24, maxHeight: '85vh', overflow: 'auto'
      }}>
        <div style={{ width: 36, height: 4, borderRadius: 2, background: TOKENS.border, margin: '0 auto 14px' }} />
        <div style={{ fontSize: 20, fontWeight: 800, color: TOKENS.text, letterSpacing: '-0.01em' }}>Cerrar jornada</div>
        <div style={{ fontSize: 13, color: TOKENS.textMuted, marginTop: 2 }}>Hoy · {fechaCorta()}</div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 16 }}>
          <div style={{ background: TOKENS.successBg, border: `1px solid ${TOKENS.successBorder || TOKENS.border}`, borderRadius: 12, padding: '14px 12px' }}>
            <div style={{ fontSize: 26, fontWeight: 800, color: TOKENS.successText, lineHeight: 1 }}>{hechas.length}</div>
            <div style={{ fontSize: 11, fontWeight: 700, color: TOKENS.successText, marginTop: 5, letterSpacing: '0.04em', textTransform: 'uppercase' }}>Completadas</div>
          </div>
          <div style={{ background: sinTerminar.length ? TOKENS.warningBg : TOKENS.surfaceLow, border: `1px solid ${sinTerminar.length ? TOKENS.warning : TOKENS.border}`, borderRadius: 12, padding: '14px 12px' }}>
            <div style={{ fontSize: 26, fontWeight: 800, color: sinTerminar.length ? TOKENS.warningText : TOKENS.textMuted, lineHeight: 1 }}>{sinTerminar.length}</div>
            <div style={{ fontSize: 11, fontWeight: 700, color: sinTerminar.length ? TOKENS.warningText : TOKENS.textMuted, marginTop: 5, letterSpacing: '0.04em', textTransform: 'uppercase' }}>Sin terminar</div>
          </div>
        </div>

        {sinTerminar.length > 0 ?
        <div style={{ marginTop: 16 }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: TOKENS.textMuted, letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 8 }}>Volverán a “Por planear”</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {sinTerminar.map((d) =>
            <div key={d.key} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderRadius: 10, background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}` }}>
                  <span style={{ width: 8, height: 8, borderRadius: 999, flexShrink: 0, background: d.estado === 'en_curso' ? TOKENS.caution : TOKENS.primary }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 700, color: TOKENS.text }}>{d.taller}{d.sede && <span style={{ color: TOKENS.textMuted, fontWeight: 500 }}> · {d.sede}</span>}</div>
                    <div style={{ fontSize: 11.5, color: TOKENS.textMuted, marginTop: 1 }}>{d.tareas.map((t) => tipoLabel(t.tipo).toLowerCase()).join(' · ')}</div>
                  </div>
                  {d.estado === 'en_curso' &&
              <span style={{ fontSize: 9, fontWeight: 600, color: TOKENS.cautionText, background: TOKENS.cautionBg, padding: '2px 7px', borderRadius: 999, letterSpacing: '0.05em', flexShrink: 0 }}>EN CURSO</span>
              }
                </div>
            )}
            </div>
            <div style={{ marginTop: 12, fontSize: 12, color: TOKENS.textMuted, lineHeight: 1.5, background: TOKENS.surfaceLow, border: `1px dashed ${TOKENS.border}`, borderRadius: 10, padding: '10px 12px' }}>
              No se arrastran solas a la ruta de mañana. Las retomas desde la bandeja cuando quieras.
            </div>
          </div> :

        <div style={{ marginTop: 16, fontSize: 13, color: TOKENS.successText, background: TOKENS.successBg, border: `1px solid ${TOKENS.successBorder || TOKENS.border}`, borderRadius: 10, padding: '12px 14px', fontWeight: 600 }}>
            Terminaste todo lo de hoy. ¡Buen trabajo!
          </div>
        }

        <div style={{ marginTop: 18, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <Button variant="outline" full onClick={onDismiss}>Volver</Button>
          <Button variant="primary" full icon={I.check(16, '#fff')} onClick={onConfirm}>Cerrar jornada</Button>
        </div>
      </div>
    </div>);

}

function TabBtn({ active, onClick, label, count }) {
  return (
    <button onClick={onClick} style={{
      padding: '10px 8px', borderRadius: 10, fontSize: 13, fontWeight: 700, cursor: 'pointer',
      fontFamily: 'inherit', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 7,
      border: `1px solid ${active ? TOKENS.primary : TOKENS.border}`,
      background: active ? TOKENS.primary : TOKENS.surface,
      color: active ? '#fff' : TOKENS.textMuted, letterSpacing: '0.01em'
    }}>
      {label}
      {count > 0 &&
      <span style={{
        fontSize: 11, fontWeight: 800, minWidth: 18, height: 18, lineHeight: '18px', textAlign: 'center',
        borderRadius: 999, padding: '0 5px',
        background: active ? 'rgba(255,255,255,0.22)' : TOKENS.primaryBg,
        color: active ? '#fff' : TOKENS.primary
      }}>{count}</span>
      }
    </button>);

}

function MiniNavyStat({ n, label }) {
  return (
    <div style={{ borderRadius: 10, padding: '8px 10px', textAlign: 'center', background: "rgba(53, 166, 255, 0.3)" }}>
      <div style={{ fontSize: 18, fontWeight: 700, lineHeight: 1 }}>{n}</div>
      <div style={{ fontSize: 9, opacity: 0.75, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', marginTop: 3 }}>{label}</div>
    </div>);

}

function ParadaRow({ parada, index, location, onClick }) {
  const dist = location ? distanceMeters(location, parada) : null;
  const c = estadoColor(parada.estado);
  return (
    <Card style={{ padding: 0, overflow: 'hidden', cursor: 'pointer', borderLeft: `4px solid ${c}` }}>
      <div onClick={onClick} style={{ padding: '12px 14px', display: 'flex', alignItems: 'flex-start', gap: 12 }}>
        <div style={{
          width: 36, height: 36, borderRadius: 999, background: estadoBg(parada.estado), color: estadoText(parada.estado), flexShrink: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: 14
        }}>{parada.estado === 'completada' ? I.check(18, estadoText(parada.estado)) : index}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', marginBottom: 3 }}>
            <span style={{ fontSize: 9, fontWeight: 700, color: tipoChip(parada.tipo).fg, padding: '2px 6px', borderRadius: 4, background: tipoChip(parada.tipo).bg, letterSpacing: '0.08em' }}>{tipoLabel(parada.tipo)}</span>
            <span style={{ fontSize: 9, fontWeight: 700, color: estadoText(parada.estado), padding: '2px 6px', borderRadius: 4, background: estadoBg(parada.estado), letterSpacing: '0.08em' }}>{estadoLabel(parada.estado)}</span>
            {parada.prioridad === 'alta' && parada.estado !== 'completada' &&
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 10, fontWeight: 700, color: TOKENS.dangerText }}><span style={{ width: 7, height: 7, borderRadius: 999, background: TOKENS.danger }} />Alta</span>
            }
          </div>
          <div style={{ fontSize: 15, fontWeight: 700, color: TOKENS.text, letterSpacing: '-0.01em' }}>
            {parada.taller}<span style={{ color: TOKENS.textMuted, fontWeight: 500 }}> · {parada.sede}</span>
          </div>
          <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 3 }}>{parada.direccion}</div>
          {parada.referencia && <div style={{ fontSize: 12, color: TOKENS.text, marginTop: 5, fontWeight: 500 }}>{parada.referencia}</div>}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 6, flexShrink: 0 }}>
          {dist !== null && parada.estado !== 'completada' &&
          <div style={{
            fontSize: 11, fontWeight: 700, color: TOKENS.text, padding: '3px 8px', borderRadius: 999,
            background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, fontFamily: 'monospace'
          }}>{formatDistance(dist)}</div>
          }
          <div style={{ color: TOKENS.textMuted, marginTop: 'auto' }}>{I.chevRight(14, TOKENS.textMuted)}</div>
        </div>
      </div>
    </Card>);

}

// ─── Detalle de parada (bottom-sheet modal) ─────────────────────────────
function ParadaDetailModal({ parada, location, onDismiss, onIniciar, onCompletar, onCancelar }) {
  const c = estadoColor(parada.estado);
  return (
    <div onClick={onDismiss} style={{
      position: 'fixed', inset: 0, background: 'rgba(11,28,48,0.5)', zIndex: 1000,
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center', padding: 0
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: TOKENS.surface, borderRadius: '18px 18px 0 0',
        width: '100%', maxWidth: 440, padding: 18, paddingBottom: 24, maxHeight: '88vh', overflow: 'auto'
      }}>
        <div style={{ width: 36, height: 4, borderRadius: 2, background: TOKENS.border, margin: '0 auto 14px' }} />

        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
          <div style={{ padding: '4px 9px', borderRadius: 6, background: tipoBg(parada.tipo), color: '#fff', fontSize: 10, fontWeight: 700, letterSpacing: '0.08em' }}>{tipoLabel(parada.tipo)}</div>
          <div style={{ padding: '4px 9px', borderRadius: 6, background: estadoBg(parada.estado), color: c, fontSize: 10, fontWeight: 700, letterSpacing: '0.08em', border: `1px solid ${c}` }}>{estadoLabel(parada.estado)}</div>
          {parada.prioridad === 'alta' && <div style={{ padding: '4px 9px', borderRadius: 6, background: TOKENS.danger, color: '#fff', fontSize: 10, fontWeight: 700, letterSpacing: '0.08em' }}>ALTA</div>}
        </div>

        <div style={{ fontSize: 22, fontWeight: 700, color: TOKENS.text, letterSpacing: '-0.01em' }}>{parada.taller}</div>
        <div style={{ fontSize: 13, color: TOKENS.textMuted, marginTop: 2 }}>{parada.sede} · {parada.direccion}</div>

        <div style={{ marginTop: 14 }}>
          <MapView markers={[{ lat: parada.lat, lng: parada.lng, label: '★', color: c, popup: `<b>${parada.taller}</b>` }]} currentLocation={location} height={170} fitBounds={!!location} />
        </div>

        {/* Consecutivos (entregas) */}
        {parada.tipo === 'entregar' && (parada.consecutivos || []).length > 0 &&
        <div style={{ marginTop: 12 }}>
            <div style={{ fontSize: 10, fontWeight: 700, color: TOKENS.textMuted, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 6 }}>
              {parada.consecutivos.length === 1 ? 'Orden a entregar' : `${parada.consecutivos.length} órdenes a entregar`}
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {parada.consecutivos.map((co) =>
            <span key={co} style={{
              fontFamily: 'monospace', fontSize: 13, fontWeight: 700, color: TOKENS.text,
              background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 8, padding: '5px 10px'
            }}>{co}</span>
            )}
            </div>
          </div>
        }

        {parada.tipo !== 'entregar' && parada.referencia &&
        <div style={{ marginTop: 12 }}>
            <div style={{ fontSize: 10, fontWeight: 700, color: TOKENS.textMuted, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 4 }}>Referencia</div>
            <div style={{ padding: '10px 12px', background: TOKENS.surfaceLow, borderRadius: 8, fontSize: 14, color: TOKENS.text, fontWeight: 600 }}>{parada.referencia}</div>
          </div>
        }

        {parada.notas &&
        <div style={{ marginTop: 12 }}>
            <div style={{ fontSize: 10, fontWeight: 700, color: TOKENS.textMuted, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 4 }}>Notas</div>
            <div style={{ padding: '10px 12px', background: TOKENS.surfaceLow, borderRadius: 8, fontSize: 13, color: TOKENS.text, fontStyle: 'italic', lineHeight: 1.5 }}>{parada.notas}</div>
          </div>
        }

        <div style={{ marginTop: 14, padding: '8px 10px', background: TOKENS.surfaceLow, borderRadius: 8, fontSize: 12, color: TOKENS.textMuted }}>
          Creada por <b style={{ color: TOKENS.text }}>{parada.creadaPor === 'admin' ? 'Admin' : 'Mensajero'}</b>
          {parada.iniciadaEn && <> · Iniciada {new Date(parada.iniciadaEn).toLocaleTimeString('es-CO', { hour: '2-digit', minute: '2-digit' })}</>}
          {parada.completadaEn && <> · Completada {new Date(parada.completadaEn).toLocaleTimeString('es-CO', { hour: '2-digit', minute: '2-digit' })}</>}
        </div>

        <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 8 }}>
          {/* Navegación opcional: el mensajero ya conoce casi todos los talleres */}
          <Button variant="outline" full icon={I.map(16, TOKENS.text)} onClick={() => openInMaps(parada)}>
            Abrir en Maps
          </Button>
          <Button variant="primary" full icon={WA_ICON(16, '#fff')} onClick={() => shareParadaToWhatsApp(parada, false)} style={{ background: '#25D366', borderColor: '#25D366' }}>
            Compartir en WhatsApp
          </Button>
          {(parada.estado === 'pendiente' || parada.estado === 'en_curso') &&
          <Button variant="outline" full icon={I.x(16, TOKENS.danger)} onClick={onCancelar} style={{ color: TOKENS.danger, borderColor: TOKENS.borderInput, borderWidth: 1.5 }}>
              Quitar de la ruta
            </Button>
          }
          <Button variant="outline" full onClick={onDismiss}>Cerrar</Button>
        </div>
      </div>
    </div>);

}

// ─── Modal: Nueva solicitud de recogida ─────────────────────────────────
function NuevaSolicitudModal({ role, onDismiss, onCreate, asignadoA }) {
  const [tallerNombre, setTallerNombre] = React.useState('');
  const [sede, setSede] = React.useState('');
  const [tipo, setTipo] = React.useState('recoger');
  const [referencia, setReferencia] = React.useState('');
  const [notas, setNotas] = React.useState('');
  const [prioridad, setPrioridad] = React.useState('normal');
  const [placasTxt, setPlacasTxt] = React.useState('');
  const [cuando, setCuando] = React.useState('hoy');
  const [cli, setCli] = React.useState({ nombre: '', telefono: '', direccion: '' });
  const partic = !!(window.esParticular && window.esParticular(tallerNombre));
  // Placas de la recogida (una o varias, separadas por coma). Obligatoria.
  const placas = placasTxt.split(/[,\s]+/).map((x) => x.trim().toUpperCase()).filter(Boolean);

  // Toda recogida lleva placa (decidido 11/11/2026).
  const cliOk = !partic || (cli.nombre.trim() && cli.telefono.trim().length >= 7 && cli.direccion.trim());
  const canSave = !!tallerNombre && (!!sede || partic) && cliOk && referencia.trim().length > 0 && (tipo !== 'recoger' || placas.length > 0);

  const buildParada = () => {
    const now = Date.now();
    const co = partic ? { lat: null, lng: null, direccion: cli.direccion.trim(), ciudad: 'Cali' } : tallerCoords(tallerNombre, sede);
    const d = new Date(); if (cuando === 'manana') d.setDate(d.getDate() + 1);
    return {
      id: 'p-' + now, fecha: fechaDDMMYYYY(d), asignadoA: asignadoA || mensajeroPorDefecto(), tipo,
      tallerId: co.tallerId, taller: tallerNombre, sede: partic ? cli.nombre.trim() : sede, ...(partic ? { cliente: { nombre: cli.nombre.trim(), telefono: cli.telefono.trim(), direccion: cli.direccion.trim() } } : {}),
      direccion: co.direccion, ciudad: co.ciudad, lat: co.lat, lng: co.lng,
      referencia: referencia.trim(), estado: 'solicitud',
      placas: tipo === 'recoger' ? placas : [],
      creadaPor: role === 'admin' ? 'admin' : 'mensajero',
      prioridad, notas: notas.trim(), createdAt: now, updatedAt: now
    };
  };
  const handleSave = (alsoShare = false) => {
    if (!canSave) return;
    const p = buildParada();
    onCreate(p);
    if (alsoShare) shareParadaToWhatsApp(p);
  };

  return (
    <div onClick={onDismiss} style={{
      position: 'fixed', inset: 0, background: 'rgba(11,28,48,0.5)', zIndex: 1000,
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center'
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: TOKENS.surface, borderRadius: '18px 18px 0 0',
        width: '100%', maxWidth: 440, padding: 18, paddingBottom: 24, maxHeight: '90vh', overflow: 'auto'
      }}>
        <div style={{ width: 36, height: 4, borderRadius: 2, background: TOKENS.border, margin: '0 auto 14px' }} />
        <div style={{ fontSize: 20, fontWeight: 700, color: TOKENS.text, letterSpacing: '-0.01em' }}>Nueva tarea</div>
        <div style={{ fontSize: 13, color: TOKENS.textMuted, marginTop: 2, marginBottom: 16 }}>
          Recoger placas para reparar · entra a Por planear › Por recoger.
        </div>

        <FieldLabel>Taller</FieldLabel>
        <Select value={tallerNombre} options={[...talleresSedes().filter((t) => sedesRutaM(t.nombre).length).map((t) => ({ value: t.nombre, label: t.nombre })), ...(window.CLIENTE_PARTICULAR ? [{ value: window.CLIENTE_PARTICULAR, label: window.CLIENTE_PARTICULAR }] : [])]} onChange={(v) => {setTallerNombre(v);const ss = sedesRutaM(v);setSede(ss.length === 1 ? ss[0] : '');}} placeholder="Seleccionar taller" searchable />

        <div style={{ height: 14 }} />
        <FieldLabel>Sede</FieldLabel>
        {partic ? <div style={{ border: `1px solid ${TOKENS.border}`, background: TOKENS.surfaceLow, borderRadius: 10, padding: '11px 12px', fontSize: 14, color: TOKENS.textSubtle }}>No aplica</div> :
        <Select value={sede} options={sedesRutaM(tallerNombre).map((s) => ({ value: s, label: s }))} onChange={setSede} placeholder="Seleccionar sede" />}
        {partic && <>
          <div style={{ height: 14 }} />
          <FieldLabel>Cliente *</FieldLabel>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            <TextInput value={cli.nombre} onChange={(v) => setCli((c) => ({ ...c, nombre: v }))} placeholder="Nombre" />
            <TextInput value={cli.telefono} onChange={(v) => setCli((c) => ({ ...c, telefono: v.replace(/[^\d ]/g, '') }))} placeholder="Teléfono" />
          </div>
          <div style={{ height: 8 }} />
          <TextInput value={cli.direccion} onChange={(v) => setCli((c) => ({ ...c, direccion: v }))} placeholder="Dirección" />
        </>}

        {tipo === 'recoger' &&
        <React.Fragment>
          <div style={{ height: 14 }} />
          <FieldLabel>Placa(s) *</FieldLabel>
          <TextInput value={placasTxt} onChange={(v) => setPlacasTxt(v.toUpperCase())} placeholder="Ej: KLM123 · varias separadas por coma" />
          {placas.length === 0 && <div style={{ fontSize: 11.5, color: TOKENS.dangerText, marginTop: 5, fontWeight: 600 }}>Escribe al menos una placa para poder crear la recogida.</div>}
        </React.Fragment>}

        <div style={{ height: 14 }} />
        <FieldLabel>{tipo === 'recoger' ? 'Qué recoger *' : 'Descripción *'}</FieldLabel>
        <TextInput value={referencia} onChange={setReferencia} placeholder={tipo === 'recoger' ? 'Ej: 4 rines y llantas' : 'Descripción'} />

        <div style={{ height: 14 }} />
        <FieldLabel>¿Para cuándo?</FieldLabel>
        <div style={{ display: 'flex', gap: 6 }}>
          {[['hoy', 'Hoy'], ['manana', 'Mañana']].map(([k, l]) => <button key={k} type="button" onClick={() => setCuando(k)} style={{ flex: 1, padding: '10px 8px', borderRadius: 8, fontSize: 13, fontWeight: 700, border: `1px solid ${cuando === k ? TOKENS.primary : TOKENS.borderInput}`, background: cuando === k ? TOKENS.primary : TOKENS.surfaceLow, color: cuando === k ? '#fff' : TOKENS.text, cursor: 'pointer', fontFamily: 'inherit' }}>{l}</button>)}
          <button type="button" onClick={() => setPrioridad(prioridad === 'alta' ? 'normal' : 'alta')} style={{ flex: 1, padding: '10px 8px', borderRadius: 8, fontSize: 13, fontWeight: 700, border: `1px solid ${prioridad === 'alta' ? TOKENS.primaryBorder : TOKENS.borderInput}`, background: prioridad === 'alta' ? TOKENS.primaryBg : TOKENS.surfaceLow, color: prioridad === 'alta' ? TOKENS.primary : TOKENS.text, cursor: 'pointer', fontFamily: 'inherit' }}>↑ Prioridad</button>
        </div>

        <div style={{ height: 14 }} />
        <FieldLabel>Notas (opcional)</FieldLabel>
        <textarea value={notas} onChange={(e) => setNotas(e.target.value)} placeholder="Detalles adicionales para el mensajero…" rows={3} style={{
          width: '100%', boxSizing: 'border-box', border: `1px solid ${TOKENS.borderInput}`, background: TOKENS.surfaceLow,
          borderRadius: 10, padding: '10px 14px', fontSize: 13, color: TOKENS.text, fontFamily: 'inherit', outline: 'none', resize: 'vertical'
        }} />

        <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
          <Button variant="outline" full onClick={onDismiss}>Cancelar</Button>
          <Button variant="primary" full icon={I.plus(16, '#fff')} disabled={!canSave} onClick={() => handleSave(false)}>Crear</Button>
        </div>
        <div style={{ marginTop: 8 }}>
          <Button variant="primary" full icon={WA_ICON(16, '#fff')} disabled={!canSave} onClick={() => handleSave(true)} style={{ background: '#25D366', borderColor: '#25D366' }}>
            Crear y compartir en WhatsApp
          </Button>
        </div>
      </div>
    </div>);

}

// ─── Helpers de estilo según estado/tipo ─────────────────────────────────
function estadoColor(estado) {
  return estado === 'completada' ? TOKENS.success :
  estado === 'en_curso' ? TOKENS.primary :
  estado === 'cancelada' ? TOKENS.danger :
  TOKENS.caution;
}
function estadoBg(estado) {
  return estado === 'completada' ? TOKENS.successBg :
  estado === 'en_curso' ? TOKENS.primaryBg :
  estado === 'cancelada' ? TOKENS.dangerBg :
  TOKENS.cautionBg;
}
function estadoText(estado) {
  return estado === 'completada' ? TOKENS.successText :
  estado === 'en_curso' ? TOKENS.primaryText :
  estado === 'cancelada' ? TOKENS.dangerText :
  TOKENS.cautionText;
}
function estadoLabel(estado) {
  return estado === 'completada' ? 'COMPLETADA' :
  estado === 'en_curso' ? 'EN CURSO' :
  estado === 'cancelada' ? 'CANCELADA' :
  'PENDIENTE';
}
function tipoBg(tipo) {
  return tipo === 'recoger' ? TOKENS.primary :
  tipo === 'entregar' ? TOKENS.blueLite :
  TOKENS.otro;
}
// Regla de color (13/11/2026): el tipo de tarea solo informa → neutro (el ícono lo distingue).
function tipoChip(tipo) {
  return { bg: TOKENS.surfaceLow, fg: TOKENS.textMuted };
}
function tipoLabel(tipo) {
  return tipo === 'recoger' ? 'RECOGER' :
  tipo === 'entregar' ? 'ENTREGAR' :
  tipo === 'encargo' ? 'ENCARGO' :
  'OTRO';
}

Object.assign(window, { tareaWhatsAppTexto, buildParadaWhatsAppText, encargosPlanDe, crearParadaEncargo, EncargoBandejaCard,
  RutasScreen, MapView, NuevaSolicitudModal,
  loadParadas, saveParadas, addParada, updateParada, removeParada, clearParadas,
  seedDemoParadasIfEmpty, TALLERES_COORDS, tallerCoords,
  rolloverParadasIfNeeded, devolverParadaABandeja,
  isJornadaCerrada, marcarJornadaCerrada, reabrirJornada
});