// ─── Entregar screen ─────────────────────────────────────────────────────
// Lista de registros pendientes por entregar, con buscador.

// Persisted (localStorage) pendientes — saved when user closes a ticket in Recoger
const LS_PENDIENTES_KEY = 'rodando.pendientes';
function loadPendientesSaved() {
  try {return JSON.parse(localStorage.getItem(LS_PENDIENTES_KEY) || '[]').map(window.catCanonObj || ((x) => x));}
  catch {return [];}
}
// Quién está usando la app (usuario de la sesión).
function quien() { const u = window.usuarioActual ? window.usuarioActual() : null; return { usuario: (u && u.usuario) || '', nombre: (u && u.nombre) || '' }; }
// Al guardar un registro demo (o cualquiera con otro id) como pendiente propio,
// su id cambia a 'saved-<código>'. Todo lo que cuelga del id viejo (servicios,
// garantías, entregas deshechas, anulaciones y sus solicitudes) se muda al nuevo
// para que no se pierda al editar.
function migrarIdTicket(viejo, nuevo) {
  if (!viejo || !nuevo || viejo === nuevo) return;
  const leer = (k, def) => { try { return JSON.parse(localStorage.getItem(k) || def); } catch (e) { return JSON.parse(def); } };
  const escribir = (k, v) => (window.safeSetItem ? window.safeSetItem(k, JSON.stringify(v)) : localStorage.setItem(k, JSON.stringify(v)));
  ['rodando.servicios.v1', 'rodando.garantias.v1', 'rodando.entregasDeshechas'].forEach((k) => {
    const m = leer(k, '{}');
    if (!m || Array.isArray(m) || !(viejo in m)) return;
    m[nuevo] = Array.isArray(m[viejo]) ? [...(Array.isArray(m[nuevo]) ? m[nuevo] : []), ...m[viejo]] : { ...m[viejo], ...(m[nuevo] || {}) };
    delete m[viejo];
    escribir(k, m);
  });
  ['rodando.anulaciones', 'rodando.solicitudesAnulacion'].forEach((k) => {
    const l = leer(k, '[]');
    if (!Array.isArray(l) || !l.some((x) => x.ticketId === viejo)) return;
    escribir(k, l.map((x) => x.ticketId === viejo ? { ...x, ticketId: nuevo } : x));
  });
}
function savePendienteTicket(ticket) {
  if (!ticket || !ticket.codigo || !(ticket.items || []).length) return;
  if (ticket.id) migrarIdTicket(ticket.id, 'saved-' + ticket.codigo);
  const list = loadPendientesSaved();
  const filtered = list.filter((t) => t.codigo !== ticket.codigo);
  const saved = {
    id: 'saved-' + ticket.codigo,
    codigo: ticket.codigo,
    placa: ticket.placa,
    idType: ticket.idType || 'placa',
    fecha: ticket.fecha,
    horaRecogida: ticket.horaRecogida || '',
    taller: ticket.taller,
    sede: ticket.sede,
    aseguradora: ticket.aseguradora,
    items: (ticket.items || []).map((it) => ({ ...it })),
    fotosPlaca: (ticket.fotosPlaca || []).filter(Boolean),
    recogidoPor: ticket.recogidoPor != null ? ticket.recogidoPor : quien().usuario,
    recogidoPorNombre: ticket.recogidoPorNombre != null ? ticket.recogidoPorNombre : quien().nombre,
    // Registro desde el PC (13/11/2026): cómo llegó y quién lo digitó.
    comoLlego: ticket.comoLlego || '', transportadoraLlegada: ticket.transportadoraLlegada || '', guiaLlegada: ticket.guiaLlegada || '',
    digitadoPor: ticket.digitadoPor || '', digitadoPorNombre: ticket.digitadoPorNombre || '',
    express: !!ticket.express,
    ...(ticket.cliente ? { cliente: { nombre: ticket.cliente.nombre || '', telefono: ticket.cliente.telefono || '', direccion: ticket.cliente.direccion || '' } } : {}),
    // Encargo asignado desde el PC (21/11/2026)
    ...(ticket.encargo ? { encargo: true, nota: ticket.nota || '', fechaLimite: ticket.fechaLimite || '', fechaLimiteIso: ticket.fechaLimiteIso || '' } : {}),
    diasPendiente: 0,
    createdAt: Date.now(),
    userSaved: true
  };
  filtered.unshift(saved);
  if (!window.safeSetItem(LS_PENDIENTES_KEY, JSON.stringify(filtered))) {
    // Cuota llena: quita las fotos de los registros más antiguos y, si hace falta,
    // descarta los más viejos — conservando siempre el recién guardado.
    const pruned = filtered.map((t, i) => i === 0 ? t : { ...t, fotosPlaca: [], items: (t.items || []).map((it) => ({ ...it, photos: [] })) });
    let ok = window.safeSetItem(LS_PENDIENTES_KEY, JSON.stringify(pruned));
    let trimmed = pruned;
    while (!ok && trimmed.length > 1) {
      trimmed = trimmed.slice(0, trimmed.length - 1);
      ok = window.safeSetItem(LS_PENDIENTES_KEY, JSON.stringify(trimmed));
    }
  }
}
function clearPendientesSaved() {
  localStorage.removeItem(LS_PENDIENTES_KEY);
}
function removePendienteTicket(id) {
  const list = loadPendientesSaved();
  localStorage.setItem(LS_PENDIENTES_KEY, JSON.stringify(list.filter((t) => t.id !== id)));
}

// Delivered tickets log (works for both saved AND demo tickets) ─────────
const LS_ENTREGADOS_KEY = 'rodando.entregados';
function loadEntregados() {
  try { return JSON.parse(localStorage.getItem(LS_ENTREGADOS_KEY) || '[]').map(window.catCanonObj || ((x) => x)); }
  catch { return []; }
}
function loadDeliveredIds() {
  return new Set(loadEntregados().map((e) => e.ticketId));
}
function markTicketDelivered(ticket, { factura, comprobanteTipo, fotos, foto, recibePor, despacho, sinReparar }) {
  // 13/11/2026: varias hojas por comprobante (fotos / guiaFotos). foto y guiaFoto = primera hoja (compatibilidad).
  const hojas = (fotos || (foto ? [foto] : [])).filter(Boolean);
  const list = loadEntregados();
  const now = new Date();
  const d = despacho || {};
  const entry = {
    ticketId: ticket.id,
    codigo: ticket.codigo,
    placa: ticket.placa,
    idType: ticket.idType,
    aseguradora: ticket.aseguradora,
    taller: ticket.taller,
    sede: ticket.sede,
    fechaRecogido: ticket.fecha,
    horaRecogida: ticket.horaRecogida || '',
    fechaEntrega: fechaDDMMYYYY(now),
    horaEntrega: `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`,
    factura: factura || '',
    comprobanteTipo: comprobanteTipo || '',
    fotos: hojas,
    foto: hojas[0] || null,
    recibePor: recibePor || '',
    despachado: !!d.despachado,
    transportadora: d.transportadora || '',
    guia: d.guia || '',
    guiaFotos: (d.guiaFotos || (d.guiaFoto ? [d.guiaFoto] : [])).filter(Boolean),
    guiaFoto: (d.guiaFotos && d.guiaFotos[0]) || d.guiaFoto || null,
    estado: 'entregado',
    recogidoPor: ticket.recogidoPor || '',
    recogidoPorNombre: ticket.recogidoPorNombre || '',
    comoLlego: ticket.comoLlego || '', transportadoraLlegada: ticket.transportadoraLlegada || '', guiaLlegada: ticket.guiaLlegada || '',
    digitadoPor: ticket.digitadoPor || '', digitadoPorNombre: ticket.digitadoPorNombre || '',
    express: !!ticket.express,
    encargo: !!ticket.encargo,
    ...(ticket.cliente ? { cliente: ticket.cliente } : {}),
    // 21/11/2026: rines que salen sin reparar (no se cobran).
    sinReparar: (sinReparar || []).map((x) => ({ i: x.i, motivo: x.motivo, foto: x.foto || null })),
    // 23/11/2026: lo que se suministró con la entrega (llanta nueva, etc.).
    suministros: window.suministrosDe ? window.suministrosDe(ticket.id) : [],
    entregadoPor: quien().usuario,
    entregadoPorNombre: quien().nombre,
    fotosPlaca: (ticket.fotosPlaca || []).filter(Boolean),
    items: ticket.items,
    createdAt: Date.now(),
  };
  list.unshift(entry);
  if (!window.safeSetItem(LS_ENTREGADOS_KEY, JSON.stringify(list))) {
    // Cuota llena: primero quita las fotos de los registros más antiguos; si aún
    // no entra, descarta los más viejos — conservando siempre la entrega actual.
    const pruned = list.map((e, i) => i === 0 ? e : { ...e, foto: null, fotos: [], guiaFoto: null, guiaFotos: [], fotosPlaca: [] });
    let ok = window.safeSetItem(LS_ENTREGADOS_KEY, JSON.stringify(pruned));
    let trimmed = pruned;
    while (!ok && trimmed.length > 1) {
      trimmed = trimmed.slice(0, trimmed.length - 1);
      ok = window.safeSetItem(LS_ENTREGADOS_KEY, JSON.stringify(trimmed));
    }
  }
  if (ticket.userSaved) removePendienteTicket(ticket.id);
  if (sinReparar && sinReparar.length && window.servMarcarSinReparar) window.servMarcarSinReparar(ticket, sinReparar);
  return entry;
}
function clearEntregados() {
  localStorage.removeItem(LS_ENTREGADOS_KEY);
}

// Update helpers for edit-existing flow (admin) ──────────────────────────
function updateSavedPendiente(ticket) {
  const list = loadPendientesSaved();
  const idx = list.findIndex(t => t.id === ticket.id);
  if (idx === -1) return false;
  list[idx] = {
    ...list[idx],
    placa: ticket.placa,
    idType: ticket.idType,
    aseguradora: ticket.aseguradora,
    taller: ticket.taller,
    sede: ticket.sede,
    items: (ticket.items || []).map(it => ({ ...it })),
    express: !!ticket.express,
  };
  localStorage.setItem(LS_PENDIENTES_KEY, JSON.stringify(list));
  return true;
}
function updateEntregaTicket(ticketId, patch) {
  const list = loadEntregados();
  const idx = list.findIndex(e => e.ticketId === ticketId);
  if (idx === -1) return false;
  list[idx] = { ...list[idx], ...patch };
  localStorage.setItem(LS_ENTREGADOS_KEY, JSON.stringify(list));
  return true;
}

// ─── Anulaciones (estado reversible) ─────────────────────────────────────
// Un registro pendiente puede anularse (con motivo) y reactivarse. Guardamos
// un registro por ticket con su historial completo de eventos; el estado
// actual = último evento. Vive aparte (como entregados) para funcionar igual
// con registros guardados Y demo. La reactivación reinicia el reloj de SLA.
const LS_ANULACIONES_KEY = 'rodando.anulaciones';
const MOTIVOS_ANULACION = ['Recogida cancelada', 'Registro duplicado', 'Error en los datos', 'Otro'];
function loadAnulaciones() {
  try { return JSON.parse(localStorage.getItem(LS_ANULACIONES_KEY) || '[]'); }
  catch { return []; }
}
function saveAnulaciones(list) {
  window.safeSetItem(LS_ANULACIONES_KEY, JSON.stringify(list));
  window.dispatchEvent(new Event('rodando-anulaciones'));
}
function loadAnulacionMap() {
  const m = new Map();
  for (const a of loadAnulaciones()) m.set(a.ticketId, a);
  return m;
}
function anulacionFor(ticketId) {
  return loadAnulaciones().find((a) => a.ticketId === ticketId) || null;
}
function _nowFechaHora() {
  const d = new Date();
  return {
    fecha: fechaDDMMYYYY(d),
    hora: `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`,
    ts: Date.now(),
  };
}
function anularTicket(ticket, { motivo, nota, por }) {
  const list = loadAnulaciones();
  const ev = { tipo: 'anulado', motivo: motivo || '', nota: nota || '', por: por || '', ..._nowFechaHora() };
  const idx = list.findIndex((a) => a.ticketId === ticket.id);
  if (idx === -1) {
    list.unshift({
      ticketId: ticket.id, codigo: ticket.codigo, placa: ticket.placa,
      fechaRecogido: ticket.fecha, horaRecogida: ticket.horaRecogida || '',
      estadoActual: 'anulado', historial: [ev],
    });
  } else {
    list[idx] = { ...list[idx], estadoActual: 'anulado', historial: [...(list[idx].historial || []), ev] };
  }
  saveAnulaciones(list);
}
function reactivarTicket(ticket, { por }) {
  const list = loadAnulaciones();
  const idx = list.findIndex((a) => a.ticketId === ticket.id);
  if (idx === -1) return;
  const ev = { tipo: 'reactivado', por: por || '', ..._nowFechaHora() };
  list[idx] = { ...list[idx], estadoActual: 'reactivado', historial: [...(list[idx].historial || []), ev] };
  saveAnulaciones(list);
}
// ─── Solicitudes de anulación (13/11/2026) ──────────────────────────────
// El mensajero no anula: pide la anulación (motivo + nota). Le llega al
// administrador, que la acepta o la rechaza explicando por qué. Mientras está
// en espera, la placa no se puede entregar. El mensajero puede retirarla.
const LS_SOLANU_KEY = 'rodando.solicitudesAnulacion';
function loadSolicitudesAnulacion() {
  try { return JSON.parse(localStorage.getItem(LS_SOLANU_KEY) || '[]'); } catch (e) { return []; }
}
function saveSolicitudesAnulacion(list) {
  window.safeSetItem(LS_SOLANU_KEY, JSON.stringify(list));
  window.dispatchEvent(new Event('rodando-anulaciones'));
}
// Última solicitud vigente de un registro (la retirada no cuenta).
function solicitudAnulacionFor(ticketId) {
  return loadSolicitudesAnulacion().find((x) => x.ticketId === ticketId && x.estado !== 'retirada') || null;
}
function anulacionEnEspera(ticketId) {
  const x = solicitudAnulacionFor(ticketId);
  return !!(x && x.estado === 'espera');
}
function solicitarAnulacion(ticket, { motivo, nota }) {
  const yo = quien();
  const now = _nowFechaHora();
  const sol = {
    id: 'sa-' + now.ts, ticketId: ticket.id, codigo: ticket.codigo, placa: ticket.placa,
    taller: ticket.taller, sede: ticket.sede, fechaRecogido: ticket.fecha, horaRecogida: ticket.horaRecogida || '',
    motivo: motivo || '', nota: (nota || '').trim(), por: yo.usuario, porNombre: yo.nombre,
    fecha: now.fecha, hora: now.hora, createdAt: now.ts, estado: 'espera'
  };
  const list = loadSolicitudesAnulacion().filter((x) => !(x.ticketId === ticket.id && x.estado === 'espera'));
  saveSolicitudesAnulacion([sol, ...list]);
  if (window.addNotif) window.addNotif({
    id: 'n-sa-' + now.ts, tipo: 'anulacion', para: 'admin', estado: 'pendiente',
    taller: ticket.taller, sede: ticket.sede, accion: 'otro', referencia: `${ticket.codigo} · ${ticket.placa}`,
    motivo: sol.nota ? `${sol.motivo}: ${sol.nota}` : sol.motivo,
    titulo: `Solicitud de anulación · ${ticket.taller}`,
    mensaje: `${yo.nombre || 'El mensajero'} pidió anular un registro · Sede ${ticket.sede || '—'}`,
    solicitudId: sol.id, actor: yo.usuario, createdAt: now.ts, resolucion: null
  });
  return sol;
}
function retirarSolicitudAnulacion(solId) {
  const list = loadSolicitudesAnulacion().map((x) => x.id === solId ? { ...x, estado: 'retirada', retiradaEn: Date.now() } : x);
  saveSolicitudesAnulacion(list);
  // El aviso al administrador queda resuelto (ya no hay nada que decidir).
  if (window.loadNotifs && window.updateNotif) {
    window.loadNotifs().filter((n) => n.solicitudId === solId && n.estado === 'pendiente').
    forEach((n) => window.updateNotif(n.id, { estado: 'resuelta', resolucion: 'vista', resolvedAt: Date.now() }));
  }
}
// Respuesta del administrador (la pantalla del admin se diseña en la fase admin).
function responderSolicitudAnulacion(solId, { aceptar, respuesta }) {
  const yo = quien();
  const list = loadSolicitudesAnulacion();
  const sol = list.find((x) => x.id === solId);
  if (!sol || sol.estado !== 'espera') return;
  const upd = { ...sol, estado: aceptar ? 'aceptada' : 'rechazada', respuesta: (respuesta || '').trim(), respondidoPor: yo.usuario, respondidoPorNombre: yo.nombre, respondidoEn: Date.now() };
  saveSolicitudesAnulacion(list.map((x) => x.id === solId ? upd : x));
  if (aceptar) anularTicket({ id: sol.ticketId, codigo: sol.codigo, placa: sol.placa, fecha: sol.fechaRecogido, horaRecogida: sol.horaRecogida }, { motivo: sol.motivo, nota: sol.nota, por: yo.nombre });
  if (window.loadNotifs && window.updateNotif) {
    window.loadNotifs().filter((n) => n.solicitudId === solId && n.estado === 'pendiente').
    forEach((n) => window.updateNotif(n.id, { estado: 'resuelta', resolucion: aceptar ? 'aceptada' : 'rechazada', resolvedAt: Date.now() }));
  }
  if (window.addNotif) window.addNotif({
    id: 'n-sar-' + Date.now(), tipo: 'anulacion', para: 'mensajero', paraUsuario: sol.por || null, estado: 'pendiente',
    taller: sol.taller, sede: sol.sede, accion: 'otro', referencia: `${sol.codigo} · ${sol.placa}`,
    motivo: upd.respuesta,
    titulo: aceptar ? `Anulación aceptada · ${sol.placa}` : `Anulación rechazada · ${sol.placa}`,
    mensaje: aceptar ? `${yo.nombre || 'El administrador'} anuló el registro ${sol.codigo}` : `${yo.nombre || 'El administrador'} no anuló el registro ${sol.codigo}`,
    solicitudId: sol.id, actor: 'admin', createdAt: Date.now(), resolucion: null
  });
}
function clearAnulaciones() {
  localStorage.removeItem(LS_ANULACIONES_KEY);
  window.dispatchEvent(new Event('rodando-anulaciones'));
}
// Última anulación / reactivación dentro del historial
function lastEventoTipo(anu, tipo) {
  if (!anu || !anu.historial) return null;
  for (let i = anu.historial.length - 1; i >= 0; i--) {
    if (anu.historial[i].tipo === tipo) return anu.historial[i];
  }
  return null;
}
// Enriquece un ticket pendiente con su anulación (y, si fue reactivado,
// la fecha de reactivación para que el SLA arranque desde ahí).
function withAnulacion(t, anuMap) {
  const anu = (anuMap && anuMap.get(t.id)) || anulacionFor(t.id);
  if (!anu) return t;
  const out = { ...t, _anulacion: anu };
  if (anu.estadoActual === 'reactivado') {
    const r = lastEventoTipo(anu, 'reactivado');
    if (r) { out.reactivadoFecha = r.fecha; out.reactivadoHora = r.hora; }
  }
  return out;
}

// Sin datos de ejemplo después de “Borrar datos de prueba” (19/11/2026).
const PENDIENTES_DEMO = (() => { try { return localStorage.getItem('rodando.sinDemo') === '1'; } catch (e) { return false; } })() ? [] : [
{ id: 't1', codigo: '6024', placa: 'GYU555', idType: 'placa',
  fecha: '28 / 05 / 2026', horaRecogida: '09:15', taller: 'Almotores', sede: 'Kia',
  aseguradora: 'Mapfre', diasPendiente: 1,
  items: [
  { id: 'a1', tipo: 'rin', cantidad: 4, tamano: '16', material: 'Maquinado', huecos: '4H', tapa: 'No', tapaValvula: 'Sí', fotos: 4 },
  { id: 'a2', tipo: 'llanta', cantidad: 4, marca: 'Michelin', referencia: '205/55 R16', dot: '1223', calidad: 'Nueva', fotos: 3 },
  { id: 'a3', tipo: 'valvula', cantidad: 4, valvulaSensor: 'Sí', fotos: 2 }]
},
{ id: 't2', codigo: '6023', placa: 'ABC123', idType: 'placa',
  fecha: '28 / 05 / 2026', horaRecogida: '16:40', taller: 'Mazko', sede: 'Sur',
  aseguradora: 'Sura', diasPendiente: 1,
  items: [
  { id: 'b1', tipo: 'rin', cantidad: 4, tamano: '17', material: 'Pintado', huecos: '5H', tapa: 'Sí', tapaValvula: 'Sí', fotos: 4 }]
},
{ id: 't3', codigo: '6022', placa: 'XYZ99A', idType: 'placa',
  fecha: '27 / 05 / 2026', horaRecogida: '10:30', taller: 'Autopacífico', sede: 'Norte',
  aseguradora: 'Allianz', diasPendiente: 2,
  items: [
  { id: 'c1', tipo: 'llanta', cantidad: 2, marca: 'Bridgestone', referencia: '110/70 R17', dot: '0824', calidad: 'Usada', fotos: 3 }]
},
{ id: 't4', codigo: '6021', placa: 'JKM402', idType: 'placa',
  fecha: '25 / 05 / 2026', horaRecogida: '11:00', taller: 'Autosuperior', sede: 'Norte',
  aseguradora: 'Bolívar', diasPendiente: 2,
  items: [
  { id: 'd1', tipo: 'rin', cantidad: 2, tamano: '15', material: 'Cromado', huecos: '4H', tapa: 'Sí', tapaValvula: 'No', fotos: 4 },
  { id: 'd2', tipo: 'llanta', cantidad: 2, marca: 'Goodyear', referencia: '185/65 R15', dot: '4523', calidad: 'Nueva', fotos: 2 },
  { id: 'd3', tipo: 'valvula', cantidad: 1, valvulaSensor: 'No', fotos: 1 }]
},
{ id: 't5', codigo: '6019', placa: '321385', idType: 'vin',
  fecha: '22 / 05 / 2026', horaRecogida: '09:00', taller: 'Almotores', sede: 'Volkswagen',
  aseguradora: 'Axa', diasPendiente: 3,
  items: [
  { id: 'e1', tipo: 'rin', cantidad: 4, tamano: '18', material: 'Maquinado', huecos: '5H', tapa: 'Sí', tapaValvula: 'Sí', fotos: 4 },
  { id: 'e2', tipo: 'valvula', cantidad: 2, valvulaSensor: 'Sí', fotos: 2 }]
},
{ id: 't6', codigo: '6018', placa: 'R12345', idType: 'placa',
  fecha: '20 / 05 / 2026', horaRecogida: '08:30', taller: 'Coches de la Sabana', sede: '8va',
  aseguradora: 'HDI', diasPendiente: 4,
  items: [
  { id: 'f1', tipo: 'rin', cantidad: 4, tamano: '14', material: 'Pintado', huecos: '4H', tapa: 'No', tapaValvula: 'No', fotos: 3 },
  { id: 'f2', tipo: 'llanta', cantidad: 4, marca: 'Pirelli', referencia: '175/70 R14', dot: '0124', calidad: 'Reencauchada', fotos: 4 }]
},
{ id: 't7', codigo: '6015', placa: 'A1234', idType: 'placa',
  fecha: '15 / 05 / 2026', horaRecogida: '10:00', taller: 'Mazko', sede: 'Norte',
  aseguradora: 'Mapfre', diasPendiente: 5,
  items: [
  { id: 'g1', tipo: 'rin', cantidad: 4, tamano: '20', material: 'Maquinado', huecos: '6H', tapa: 'Sí', tapaValvula: 'Sí', fotos: 4 }]
}];


// ¿La orden trae un daño adicional aún por aprobar? Bloquea la entrega (monto retenido).
function ticketDAporAprobar(t) { return Array.isArray(t && t.servicios) && t.servicios.some((s) => s && s.da && s.daEstado === 'por-aprobar'); }
// Aggregate counts helper (since items now is an array of objects)
function ticketSummary(t) {
  const items = t.items || [];
  const total = items.reduce((s, it) => s + Number(it.cantidad || 0), 0);
  const rines = items.filter((i) => i.tipo === 'rin').reduce((s, it) => s + Number(it.cantidad), 0);
  const llantas = items.filter((i) => i.tipo === 'llanta').reduce((s, it) => s + Number(it.cantidad), 0);
  const valvulas = items.filter((i) => i.tipo === 'valvula').reduce((s, it) => s + Number(it.cantidad), 0);
  return { total, rines, llantas, valvulas };
}

function EntregarScreen({ onBack, onNav, initialEntregaCodigo, initialEntregaVer, onInitialConsumed, onExitToRutas }) {
  const [verGar, setVerGar] = React.useState(null); // entrega con garantía abierta: se ve su ficha
  const verGarExit = React.useRef(false);
  const [query, setQuery] = React.useState('');
  const [selectedId, setSelectedId] = React.useState(null);
  const [savedTickets, setSavedTickets] = React.useState(loadPendientesSaved());
  const [deliveredIds, setDeliveredIds] = React.useState(loadDeliveredIds());
  const [anuMap, setAnuMap] = React.useState(loadAnulacionMap());
  const [view, setView] = React.useState('list'); // 'list' | 'resumen' | 'entrega' | 'success'
  const [entregaFrom, setEntregaFrom] = React.useState('resumen'); // a dónde vuelve Cancelar en el flujo de entrega
  const entregaFromRef = React.useRef('resumen'); // fuente de verdad (sin stale closure)

  // Resetear scroll al cambiar de sub-vista (list/resumen/entrega/imprimir/success).
  React.useEffect(() => { if (window.rdScrollTop) window.rdScrollTop(); }, [view, selectedId]);
  const [lastDelivered, setLastDelivered] = React.useState(null);

  React.useEffect(() => {
    setSavedTickets(loadPendientesSaved());
    setDeliveredIds(loadDeliveredIds());
    setAnuMap(loadAnulacionMap());
    const onStorage = () => { setSavedTickets(loadPendientesSaved()); setDeliveredIds(loadDeliveredIds()); setAnuMap(loadAnulacionMap()); };
    window.addEventListener('storage', onStorage);
    window.addEventListener('focus', onStorage);
    window.addEventListener('rodando-anulaciones', onStorage);
    return () => {
      window.removeEventListener('storage', onStorage);
      window.removeEventListener('focus', onStorage);
      window.removeEventListener('rodando-anulaciones', onStorage);
    };
  }, []);

  const allPendientes = [...savedTickets, ...PENDIENTES_DEMO]
    .filter((t) => { const a = anuMap.get(t.id); return !a || a.estadoActual !== 'anulado'; })
    .map((t) => withAnulacion(t, anuMap));
  const pendientes = allPendientes.filter((t) => !deliveredIds.has(t.id));
  const q = query.trim().toLowerCase();
  const filtered = q ?
  pendientes.filter((t) =>
  t.placa.toLowerCase().includes(q) ||
  t.codigo.toLowerCase().includes(q) ||
  t.taller.toLowerCase().includes(q) ||
  t.aseguradora.toLowerCase().includes(q) ||
  (t.sede || '').toLowerCase().includes(q)
  ) :
  pendientes;

  const selected = selectedId ? allPendientes.find((t) => t.id === selectedId) : null;

  // Parada en curso (13/11/2026): si es de entrega, sus placas salen primero en "En este taller".
  const enCurso = window.getRutaEnCurso ? window.getRutaEnCurso() : null;
  const mismoDestino = (t, d) => !!d && t.taller === d.taller && (t.sede || '') === (d.sede || '');
  let enCursoEntrega = null;
  try {
    if (enCurso && window.loadParadas) {
      const hoy = fechaDDMMYYYY();
      if (window.loadParadas().some((p) => p.fecha === hoy && p.estado === 'en_curso' && p.tipo === 'entregar' && mismoDestino(p, enCurso))) enCursoEntrega = enCurso;
    }
  } catch (e) {}

  // Deep-link desde Rutas: abre directo la entrega de un consecutivo concreto.
  React.useEffect(() => {
    if (!initialEntregaCodigo) return;
    const tk = allPendientes.find((t) => String(t.codigo) === String(initialEntregaCodigo) && !deliveredIds.has(t.id));
    // Garantía (18/11/2026): la orden ya está entregada; se abre su ficha y "Volver" regresa a Rutas.
    const entG = !tk && initialEntregaVer ? (window.loadEntregados ? window.loadEntregados() : []).find((x) => String(x.codigo) === String(initialEntregaCodigo)) : null;
    if (entG) { verGarExit.current = true; setVerGar(entG); }
    if (tk) {
      setSelectedId(tk.id);
      entregaFromRef.current = 'exit';
      setEntregaFrom('exit');
      setView(initialEntregaVer || anulacionEnEspera(tk.id) ? 'resumen' : 'entrega');
    }
    onInitialConsumed && onInitialConsumed();
    // eslint-disable-next-line
  }, [initialEntregaCodigo]);

  // Orden por urgencia con los términos de PROCESOS (13/11/2026): Vencido → Retrasado → Vence hoy → En plazo.
  const est = (t) => window.estadoProcesos ? window.estadoProcesos(t) : { orden: 3, dias: 0 };
  // Urgencia (19/11/2026): Vencido → Retrasado → Vence hoy → En plazo, más días primero; Express solo desempata.
  const ordenUrg = (a, b) => est(a).orden - est(b).orden || est(b).dias - est(a).dias || (b.express ? 1 : 0) - (a.express ? 1 : 0);

  if (verGar) {
    return <ResumenEntregadoScreen entrega={(window.loadEntregados ? window.loadEntregados() : []).find((x) => x.ticketId === verGar.ticketId) || verGar} onBack={() => { setVerGar(null); if (verGarExit.current && onExitToRutas) { verGarExit.current = false; onExitToRutas(); } }} onImprimir={() => {}} admin={false} />;
  }

  if (selected && view === 'success' && lastDelivered) {
    const quedan = pendientes.filter((t) => t.id !== lastDelivered.ticketId && mismoDestino(t, lastDelivered) && !anulacionEnEspera(t.id)).sort(ordenUrg);
    const volverLista = () => {
      setSelectedId(null); setView('list'); setLastDelivered(null);
      setDeliveredIds(loadDeliveredIds());
      if (entregaFromRef.current === 'exit' && onExitToRutas) onExitToRutas();
    };
    return <EntregaSuccessScreen
      entrega={lastDelivered}
      quedan={quedan.length}
      siguiente={quedan[0] || null}
      enParada={!!enCursoEntrega && mismoDestino(lastDelivered, enCursoEntrega)}
      volverLabel={entregaFromRef.current === 'exit' ? 'Volver a Rutas' : 'Volver a la lista'}
      onSiguientePlaca={(t) => {
        setLastDelivered(null); setDeliveredIds(loadDeliveredIds());
        setSelectedId(t.id); entregaFromRef.current = 'resumen'; setEntregaFrom('resumen'); setView('entrega');
      }}
      onMenu={volverLista}
      onSiguiente={volverLista}
    />;
  }

  if (selected && view === 'entrega') {
    return <EntregaConfirmScreen
      ticket={selected}
      onBack={() => {
        if (entregaFromRef.current === 'exit' && onExitToRutas) { setSelectedId(null); setView('list'); onExitToRutas(); }
        else if (entregaFromRef.current === 'list') { setSelectedId(null); setView('list'); }
        else { setView('resumen'); }
      }}
      onSaved={(entry) => {
        setLastDelivered(entry);
        setDeliveredIds(loadDeliveredIds());
        setView('success');
      }}
    />;
  }

  if (selected && view === 'imprimir') {
    return <ImprimirScreen
      ticket={selected}
      onBack={() => setView('resumen')}
      onPrint={() => alert('Enviado a impresora Bluetooth.')}
    />;
  }

  if (selected) {
    return <ResumenEntregaScreen
      ticket={selected}
      onBack={() => { const aRutas = entregaFromRef.current === 'exit' && onExitToRutas; setSelectedId(null); setView('list'); if (aRutas) onExitToRutas(); }}
      onEntregar={() => { entregaFromRef.current = 'resumen'; setEntregaFrom('resumen'); setView('entrega'); }}
      onImprimir={() => setView('imprimir')}
    />;
  }

  const ordenados = [...filtered].sort(ordenUrg);
  const aqui = enCursoEntrega ? ordenados.filter((t) => mismoDestino(t, enCursoEntrega)) : [];
  const otros = ordenados.filter((t) => !aqui.includes(t));
  const abrir = (t) => setSelectedId(t.id);
  const titulo = (txt, n, unidad) =>
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', margin: '16px 2px 8px' }}>
      <span style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: '0.06em', color: TOKENS.textMuted, textTransform: 'uppercase' }}>{txt}</span>
      <span style={{ fontSize: 11.5, fontWeight: 700, color: TOKENS.textSubtle }}>{n}{unidad ? ` ${n === 1 ? 'placa' : 'placas'}` : ''}</span>
    </div>;

  return (
    <div style={{ background: TOKENS.bg, display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
      <AppHeader title="Entregar" onBack={onBack} hideRuta={!!enCurso} />
      <div style={{ padding: '12px 16px 18px', flex: 1 }}>

        {/* Contexto de ruta: parada en curso (mismo estilo que Recoger) */}
        {enCurso &&
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10,
          background: TOKENS.cautionBg, border: `1px solid ${TOKENS.caution}`, color: TOKENS.cautionText,
          borderRadius: 10, padding: '7px 10px', fontSize: 12, fontWeight: 700
        }}>
            <span style={{ width: 7, height: 7, borderRadius: 999, background: TOKENS.cautionText, animation: 'rdBlink 1.4s infinite', flexShrink: 0 }} />
            En curso: {enCurso.taller}{enCurso.sede ? ' · ' + enCurso.sede : ''}
          </div>
        }

        {/* Buscador */}
        <div style={{ position: 'relative' }}>
          <div style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none', display: 'flex' }}>{I.consultar(16, TOKENS.textMuted)}</div>
          <input
            type="text"
            className="ad-search"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Buscar placa, taller o aseguradora"
            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>

        {/* Garantías por entregar (18/11/2026): debajo del buscador, con la tarjeta de siempre */}
        {window.GarantiasPorEntregarMovil && <window.GarantiasPorEntregarMovil q={q} onVer={(e) => setVerGar(e)} />}

        {enCursoEntrega && !q &&
        <>
            {titulo('En este taller', aqui.length, true)}
            {aqui.length === 0 ?
            <div style={{ background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 14, padding: '14px 12px', textAlign: 'center', fontSize: 13, color: TOKENS.textMuted, lineHeight: 1.45 }}>
                ✓ No quedan placas por entregar en este taller.<br />Recuerda finalizar la parada en Inicio.
              </div> :
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>{aqui.map((t) => <PendienteRow key={t.id} ticket={t} onClick={() => abrir(t)} />)}</div>
            }
            {titulo('Otros talleres', otros.length)}
          </>
        }
        {(!enCursoEntrega || q) && titulo(q ? 'Resultados' : 'Por entregar', q ? ordenados.length : otros.length, true)}

        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {(q ? ordenados : otros).map((t) => <PendienteRow key={t.id} ticket={t} onClick={() => abrir(t)} />)}
          {(q ? ordenados : otros).length === 0 &&
          <div style={{ padding: '22px 14px', textAlign: 'center', color: TOKENS.textMuted, fontSize: 13, background: TOKENS.surfaceLow, borderRadius: 12, border: `1px dashed ${TOKENS.border}` }}>
              {q ? 'No hay placas por entregar que coincidan con tu búsqueda.' : 'No hay placas por entregar.'}
            </div>
          }
        </div>
      </div>
      <BottomNav current="entregar" onNav={onNav || onBack} />
    </div>);

}

function ChipSolicitud() {
  return <span style={{ display: 'inline-block', fontSize: 11.5, fontWeight: 500, borderRadius: 999, padding: '3px 9px', whiteSpace: 'nowrap', background: TOKENS.anuladoBg, color: TOKENS.anuladoText, border: '1px dashed ' + TOKENS.anuladoBorder }}>⏳ Anulación solicitada</span>;
}

// Placa en el mismo recuadro gris de Inicio (13/11/2026, opción C).
const PLACA_BOX = { 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' };

// ─── Identidad de la placa (18/11/2026) ─────────────────────────────────
// Placa y orden en dos recuadros con etiqueta (igual que el PC); a la derecha, centradas con los
// recuadros, las insignias: ⚡ Express y ↺ garantía (con circulito de días si está abierta:
// cian en plazo; amarillo/naranja/rojo si hay que actuar). Los íconos solo avisan.
const ENTREGADO_COLOR = { bg: '#1c7c46', fg: '#fff' }; // Entregado: verde oscuro sólido (≠ "En plazo")
const ChipEntregado = ({ txt = 'Entregado', size = 11.5 }) => <span style={{ fontSize: size, fontWeight: 500, borderRadius: 999, padding: '3px 9px', whiteSpace: 'nowrap', background: ENTREGADO_COLOR.bg, color: ENTREGADO_COLOR.fg }}>{txt}</span>;
const GAR_BADGE = ['#c0392b', '#d9772b', '#e0b100', '#0e7490']; // por garEstado().orden
function GarantiaInsignia({ g }) {
  const GC = window.GAR_COLOR || { bg: '#e6f7fa', fg: '#0e7490', bd: '#b3e3ec' };
  const ge = g && window.garEstado ? window.garEstado(g) : null;
  return (
    <span title={g ? `Garantía abierta · ${ge ? ge.label : ''}` : 'Tuvo garantía (ya entregada)'} style={{ position: 'relative', display: 'inline-flex' }}>
      <span style={{ fontSize: 11.5, fontWeight: 500, borderRadius: 999, padding: '2px 8px', lineHeight: 1.4, background: GC.bg, color: GC.fg, border: `1px solid ${GC.bd}` }}>↺</span>
      {ge && <b style={{ position: 'absolute', top: -10, right: -13, fontSize: 10.5, fontWeight: 600, borderRadius: 999, padding: '0 5px', lineHeight: '16px', whiteSpace: 'nowrap', boxShadow: '0 0 0 2px #fff', background: GAR_BADGE[ge.orden] || GC.fg, color: ge.orden === 2 ? '#3d2e00' : '#fff' }}>{ge.dias}d</b>}
    </span>);
}
// Encargo (21/11/2026): entrega que asignó el admin sin recogida (ej. una llanta que llegó de un proveedor).
const ChipEncargo = () => <span title="Encargo asignado desde el PC" style={{ display: 'inline-flex', alignItems: 'center', fontSize: 11.5, fontWeight: 500, borderRadius: 999, padding: '2px 8px', whiteSpace: 'nowrap', background: '#eef1f6', color: '#3c4a66', border: '1px solid #d5deeb' }}>Encargo</span>;
function InsigniasPlaca({ ticket, alto = 34 }) {
  const gs = window.garantiasDe && ticket.id ? window.garantiasDe(ticket.id) : [];
  const ab = gs.find((g) => g.estado === 'abierta') || null;
  if (!ticket.express && !gs.length && !ticket.encargo) return null;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, height: alto, flexShrink: 0 }}>
      {ticket.encargo && <ChipEncargo />}
      {ticket.express && window.PcChipExpress && <window.PcChipExpress solo />}
      {gs.length > 0 && <GarantiaInsignia g={ab} />}
    </div>);
}
function CabeceraPlaca({ ticket, lead, grande }) {
  const caja = (l, v) =>
  <div style={{ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 }}>
      <i style={{ fontStyle: 'normal', fontSize: 9, fontWeight: 800, letterSpacing: '0.07em', color: TOKENS.textSubtle, textTransform: 'uppercase', paddingLeft: 2 }}>{l}</i>
      <span style={{ ...PLACA_BOX, fontSize: grande ? 18 : 16 }}>{v || '—'}</span>
    </div>;
  const alto = grande ? 38 : 34;
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 8, flexWrap: 'wrap' }}>
      {lead && <div style={{ height: alto, display: 'flex', alignItems: 'center' }}>{lead}</div>}
      {caja('Placa', ticket.placa)}
      {caja('Orden', ticket.codigo)}
      <InsigniasPlaca ticket={ticket} alto={alto} />
    </div>);
}
// Versión chica para filas y tarjetas (19/11/2026): los mismos dos recuadros con etiqueta mínima arriba.
function PlacaOrdenChica({ placa, codigo, fondo }) {
  const caja = (l, v) => <div style={{ display: 'flex', flexDirection: 'column', gap: 1, minWidth: 0 }}>
      <i style={{ fontStyle: 'normal', fontSize: 8.5, fontWeight: 800, letterSpacing: '0.07em', color: TOKENS.textSubtle, textTransform: 'uppercase', paddingLeft: 2 }}>{l}</i>
      <span style={{ fontFamily: "'JetBrains Mono', monospace", fontWeight: 700, fontSize: 13.5, background: fondo || TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 6, padding: '2px 7px', color: TOKENS.text, whiteSpace: 'nowrap' }}>{v || '—'}</span>
    </div>;
  return <span style={{ display: 'inline-flex', alignItems: 'flex-end', gap: 6 }}>{caja('Placa', placa)}{codigo ? caja('Orden', codigo) : null}</span>;
}
// Tabla de datos con la columna gris de etiquetas (misma que la ficha del PC).
function FichaTabla({ filas, style }) {
  return (
    <div style={{ border: `1px solid ${TOKENS.border}`, borderRadius: 12, overflow: 'hidden', ...style }}>
      {filas.filter(Boolean).map(([k, v], i) =>
      <div key={k} style={{ display: 'grid', gridTemplateColumns: '112px 1fr', borderTop: i ? `1px solid ${TOKENS.border}` : 'none' }}>
          <span style={{ background: TOKENS.surfaceLow, padding: '8px 11px', fontSize: 12, color: TOKENS.textMuted, fontWeight: 700 }}>{k}</span>
          <span style={{ padding: '8px 11px', fontWeight: 600, fontSize: 13.5, display: 'flex', alignItems: 'center', gap: 7, flexWrap: 'wrap', minWidth: 0, overflowWrap: 'anywhere', color: TOKENS.text }}>{v == null || v === '' ? '—' : v}</span>
        </div>)}
    </div>);
}
const fichaSub = (t) => <span style={{ fontWeight: 500, color: TOKENS.textSubtle, fontSize: 12.5 }}>{t}</span>;
const fichaChip = (label, bg, fg, bd) => <span style={{ fontSize: 11.5, fontWeight: 500, borderRadius: 999, padding: '3px 9px', whiteSpace: 'nowrap', background: bg, color: fg, border: bd ? `1px solid ${bd}` : 'none' }}>{label}</span>;
const fichaSla = (express) => express ? (window.loadCatServicios ? window.loadCatServicios().slaExpress : 2) : (window.loadSlaConfig ? window.loadSlaConfig().slaHabiles : 3);
function filaPrioridad(t) {
  if (t.encargo) return ['Prioridad', <><ChipEncargo />{t.express && window.PcChipExpress && <window.PcChipExpress solo />}{fichaSub(t.fechaLimite ? `para el ${t.fechaLimite}` : `plazo ${fichaSla(!!t.express)} días hábiles`)}</>];
  return ['Prioridad', t.express ?
  <>{window.PcChipExpress && <window.PcChipExpress />}{fichaSub(`plazo ${fichaSla(true)} días hábiles`)}</> :
  <span style={{ fontWeight: 500, color: TOKENS.textMuted }}>Normal · plazo {fichaSla(false)} días hábiles</span>];
}
// Plazo de una entregada: días hábiles de la recogida (o de la última autorización) a la entrega.
function plazoEntrega(e) {
  try {
    const re = window.reinicioPlazo ? window.reinicioPlazo(e.ticketId) : null;
    const ini = re ? window.effectiveStart(re.fecha, re.hora) : window.effectiveStart(e.fechaRecogido, e.horaRecogida);
    const fin = window.parseFechaHora ? window.parseFechaHora(e.fechaEntrega, e.horaEntrega) : null;
    const d = fin ? window.businessDaysElapsed(ini, fin) : 0;
    const S = fichaSla(!!e.express);
    return { dias: d, k: d < S ? 3 : d === S ? 2 : 1, re };
  } catch (x) { return { dias: 0, k: 3 }; }
}
const chipPlazoEntrega = (k) => k === 3 ? fichaChip('A tiempo', TOKENS.successBg, TOKENS.successText) : k === 2 ? fichaChip('Justo en el plazo', '#fff2cc', '#7f6000') : fichaChip('Tarde', TOKENS.dangerBg, TOKENS.dangerText);
// Tarjeta "Garantía" de la ficha (celular): título con la insignia, tabla y fotos.
function GarantiaFichaCard({ ticket, g, onFoto }) {
  const [conf, setConf] = React.useState(false);
  const [, refrescar] = React.useState(0);
  const ab = g.estado === 'abierta';
  const ge = ab && window.garEstado ? window.garEstado(g) : null;
  const EC = [[TOKENS.dangerBg, TOKENS.dangerText], [TOKENS.warningBg, TOKENS.warningText], ['#fff2cc', '#7f6000'], ['#e6f7fa', '#0e7490']];
  const f12 = (h) => h ? (window.formatHora12 ? window.formatHora12(h) : h) : '';
  const fotos = (g.fotos || []).filter(Boolean);
  return (
    <Card style={{ marginTop: 12, padding: '14px 14px', background: TOKENS.surface }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
        <GarantiaInsignia g={ab ? g : null} />
        <div style={{ fontSize: 15, fontWeight: 700, color: TOKENS.text, marginLeft: ab ? 6 : 0 }}>Garantía</div>
        <span style={{ flex: 1 }} />
        {ab ? fichaChip(ge.label, EC[ge.orden][0], EC[ge.orden][1]) : <ChipEntregado txt={`Entregada ${String((g.entrega && g.entrega.fecha) || '').replace(/\s/g, '').slice(0, 5)}`} />}
      </div>
      <FichaTabla filas={[
      ['Rines', (g.rines || []).map((i) => 'Rin ' + (i + 1)).join(', ')],
      ['Motivo', g.motivo],
      g.desc && ['Qué reclaman', <span style={{ fontWeight: 500 }}>“{g.desc}”</span>],
      ['Registrada', <>{String(g.fecha || '').replace(/\s/g, '')}{g.hora ? ' · ' + f12(g.hora) : ''} {g.porNombre && fichaSub(g.porNombre)}</>],
      ab ? ['Se espera', window.garFechaEstimada ? window.garFechaEstimada(g) : ''] :
      ['Entregada', <>{String((g.entrega && g.entrega.fecha) || '').replace(/\s/g, '')}{g.entrega && g.entrega.hora ? ' · ' + f12(g.entrega.hora) : ''} {g.entrega && g.entrega.porNombre && fichaSub(g.entrega.porNombre)}</>]]} />
      {fotos.length > 0 &&
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, marginTop: 10 }}>
          {fotos.map((src, i) => <img key={i} src={src} alt={`Foto garantía ${i + 1}`} onClick={() => onFoto && onFoto({ src, list: fotos })} style={{ width: '100%', aspectRatio: '1', objectFit: 'cover', borderRadius: 10, display: 'block', cursor: 'zoom-in' }} />)}
        </div>}
      {ab && window.entregarGarantia &&
      <Button variant="primary" full icon={I.check(17, '#fff')} onClick={() => setConf(true)} style={{ marginTop: 12 }}>Entregar garantía</Button>}
      {conf && window.ConfirmActionModal && <window.ConfirmActionModal tone="primary" icon={I.check(24, TOKENS.primary)} title="Entregar garantía" confirmLabel="Entregar"
      ticket={ticket} message={`${(g.rines || []).length} ${(g.rines || []).length === 1 ? 'rin' : 'rines'} de garantía. No se cobra ni genera factura.`}
      onDismiss={() => setConf(false)} onConfirm={() => { window.entregarGarantia(ticket.ticketId || ticket.id, g.id); setConf(false); refrescar((n) => n + 1); }} />}
    </Card>);
}

// ─── Ficha por secciones (18/11/2026) ────────────────────────────────────
// Fijos arriba: placa/orden · Aseguradora|Taller|Sede · Cumplimiento. Debajo, según el caso:
// pendiente → Recogida; entregada → Entrega, Recogida; con garantía → Garantía, Entrega, Recogida.
function TriDatos({ aseguradora, taller, sede }) {
  const c = (k, v, i) =>
  <div style={{ padding: '11px 12px', borderLeft: i ? `1px solid ${TOKENS.border}` : 'none', minWidth: 0 }}>
      <div style={{ fontSize: 9.5, fontWeight: 800, letterSpacing: '0.06em', color: TOKENS.textMuted, textTransform: 'uppercase', marginBottom: 3 }}>{k}</div>
      <div style={{ fontSize: 14, fontWeight: 700, color: TOKENS.text, overflowWrap: 'anywhere' }}>{v || '—'}</div>
    </div>;
  return (
    <div style={{ marginTop: 12, background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 14, display: 'grid', gridTemplateColumns: '1fr 1fr 1fr' }}>
      {c('Aseguradora', window.catAseguradoraCorta ? window.catAseguradoraCorta(aseguradora) : aseguradora, 0)}
      {c('Taller', taller, 1)}
      {c('Sede', sede, 2)}
    </div>);
}
function FichaSeccion({ titulo, derecha, icono, children }) {
  return (
    <Card style={{ marginTop: 12, padding: '14px 14px', background: TOKENS.surface }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
        {icono}
        <div style={{ fontSize: 15, fontWeight: 700, color: TOKENS.text }}>{titulo}</div>
        <span style={{ flex: 1 }} />
        {derecha}
      </div>
      {children}
    </Card>);
}
const fichaSubt = (t, top = 14) => <div style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: '0.06em', color: TOKENS.textMuted, textTransform: 'uppercase', margin: `${top}px 0 6px` }}>{t}</div>;
function fichaFotosGrid(fotos, onFoto, doc) {
  if (!fotos.length) return <div style={{ fontSize: 12.5, color: TOKENS.textSubtle }}>Sin fotos.</div>;
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
      {fotos.map((src, i) =>
      <div key={i} style={{ position: 'relative', aspectRatio: doc ? '3 / 4' : '1' }}>
          <img src={src} alt={`${doc ? 'Hoja' : 'Foto'} ${i + 1}`} onClick={() => onFoto && onFoto({ src, list: fotos })} style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: 10, border: doc ? `1px solid ${TOKENS.border}` : 'none', display: 'block', cursor: 'zoom-in' }} />
          {doc && <span style={{ position: 'absolute', left: 5, bottom: 5, background: 'rgba(22,35,63,.82)', color: '#fff', fontSize: 10, fontWeight: 800, borderRadius: 6, padding: '2px 6px' }}>Hoja {i + 1}</span>}
        </div>)}
    </div>);
}
function RecogidaSeccion({ fecha, hora, por, items, fotos, onFoto }) {
  const total = (items || []).reduce((s, it) => s + (Number(it.cantidad) || 0), 0);
  const f12 = (h) => h ? (window.formatHora12 ? window.formatHora12(h) : h) : '';
  return (
    <FichaSeccion titulo="Recogida" derecha={<span style={{ fontSize: 12.5, fontWeight: 600, color: TOKENS.textMuted, textAlign: 'right' }}>{String(fecha || '').replace(/\s/g, '')}{hora ? ' · ' + f12(hora) : ''}{por ? ' · ' + por : ''}</span>}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        {fichaSubt('Ítems', 0)}
        <span style={{ fontSize: 11, fontWeight: 800, background: TOKENS.navyDark, color: '#fff', borderRadius: 999, padding: '3px 9px', letterSpacing: '0.04em' }}>TOTAL: {total}</span>
      </div>
      {window.TotalesPlaca && <TotalesPlaca items={items || []} />}
      {(items || []).map((it, i) => window.FichaItem ? <FichaItem key={it.id || i} item={it} index={i} /> : null)}
      {!(items || []).length && <div style={{ fontSize: 12.5, color: TOKENS.textSubtle }}>Sin ítems registrados.</div>}
      {fichaSubt(`Fotos · ${fotos.length}`)}
      {fichaFotosGrid(fotos, onFoto)}
    </FichaSeccion>);
}

// Tarjeta de placa compartida (13/11/2026, "Mezcla 2 ajustada"): placa + chip; datos con
// etiqueta pegada (Taller/Sede/Aseguradora) y la fecha de recogida a la derecha; ítems en
// Comprobante (19/11/2026): el prefijo va fijo en el campo. Factura → "SE" (se guarda "SE 21010");
// Remisión → "Remisión" (se guarda solo el número; el tipo lo dice).
const DOC_PREFIJO = { Factura: 'SE', 'Remisión': 'Remisión' };
const docLimpio = (doc, v) => { let s = String(v || '').toUpperCase().replace(/\s+/g, ' ').trimStart(); if (doc === 'Factura') s = s.replace(/^SE[\s-]*/, ''); else s = s.replace(/^REMISI[OÓ]N[\s-]*/, ''); return s; };
const docGuardar = (doc, n) => { const x = docLimpio(doc, n).trim(); return x && doc === 'Factura' ? `SE ${x}` : x; };
function fmtComprobante(e) {
  if (!e) return '';
  if (e.despachado) return `Guía ${e.guia || ''}`.trim();
  if (!e.factura) return '';
  if (/remisi/i.test(e.comprobanteTipo || '')) return `Remisión ${e.factura}`;
  if (!e.comprobanteTipo || e.comprobanteTipo === 'Factura') return /^SE/i.test(e.factura) ? e.factura.replace(/^SE[\s-]*/i, 'SE ') : `SE ${e.factura}`;
  return `${e.comprobanteTipo} ${e.factura}`;
}
function DocNumInput({ doc, value, onChange, style, invalid, onBlur }) {
  const pre = DOC_PREFIJO[doc] || '';
  return <div style={{ display: 'flex', alignItems: 'stretch', border: `1px solid ${invalid ? TOKENS.danger : TOKENS.borderInput}`, background: TOKENS.surfaceLow, borderRadius: 10, overflow: 'hidden', ...style }}>
    <span style={{ display: 'flex', alignItems: 'center', padding: '0 11px', background: TOKENS.surface, borderRight: `1px solid ${TOKENS.border}`, fontFamily: "'JetBrains Mono', monospace", fontWeight: 800, fontSize: 14, color: TOKENS.textMuted, whiteSpace: 'nowrap' }}>{pre}</span>
    <input value={value} onBlur={onBlur} onChange={(ev) => onChange(docLimpio(doc, ev.target.value))} placeholder={doc === 'Factura' ? 'Ej. 21010' : 'Ej. 4512'} inputMode="text"
    style={{ flex: 1, minWidth: 0, border: 0, background: 'transparent', padding: '10px 11px', fontFamily: "'JetBrains Mono', monospace", fontSize: 14.5, fontWeight: 700, color: TOKENS.text, outline: 'none' }} />
  </div>;
}
// celdas (número arriba, palabra abajo) y "Ver ›" en azul claro. Usada en Entregar y Consultar.
// Rutas (18/11/2026): `lead` (casilla a la izquierda de la placa), `selected` (borde azul) y
// `onVer` (el botón "Ver ›" abre la ficha sin marcar la tarjeta). Express se muestra junto a la placa.
function TarjetaPlaca({ ticket, chip, extra, onClick, lead, selected, onVer, fechaK = 'Recogida', fechaV }) {
  const sum = ticketSummary(ticket);
  const fecha = fechaV != null ? fechaV : String(ticket.fecha || '').replace(/\s/g, '');
  // Entregadas (18/11/2026): el comprobante va en la tarjeta. Factura = solo el número (ej. "SE 16555");
  // remisión = "Remisión …"; por transportadora = "Guía …".
  const ent = ticket._entrega;
  const docEnt = fmtComprobante(ent);
  const sums = (ent && ent.suministros) || (window.suministrosDe && ticket.id ? window.suministrosDe(ticket.id) : []);
  const dato = (k, v) => v ? <div><span style={{ color: TOKENS.textMuted, fontWeight: 600 }}>{k}:</span> <b style={{ fontWeight: 700 }}>{v}</b></div> : null;
  const celda = (n, label, i) =>
  <div key={label} style={{ flex: 1, textAlign: 'center', lineHeight: 1.15, borderLeft: i ? `1px solid ${TOKENS.border}` : 'none' }}>
      <b style={{ display: 'block', fontSize: 15, color: n ? TOKENS.text : TOKENS.textSubtle }}>{n}</b>
      <span style={{ fontSize: 9.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.04em', color: n ? TOKENS.textMuted : TOKENS.textSubtle }}>{label}</span>
    </div>;
  return (
    <div role="button" tabIndex={0} onClick={onClick} onKeyDown={(e) => {if (e.key === 'Enter') onClick && onClick();}} style={{
      background: TOKENS.surface, border: `1px solid ${selected ? TOKENS.primary : TOKENS.border}`, boxShadow: selected ? `0 0 0 2px ${TOKENS.primaryBg}` : 'none', borderRadius: 14, padding: '13px 14px', color: TOKENS.text, cursor: 'pointer'
    }}>
      <CabeceraPlaca ticket={ticket} lead={lead} />
      {extra && <div style={{ marginTop: 8 }}>{extra}</div>}
      {sums.length > 0 && <div style={{ marginTop: 10, background: '#e6f7fa', border: '1px solid #b3e3ec', borderRadius: 10, padding: '7px 10px', fontSize: 12.5, color: '#0e7490', lineHeight: 1.4 }}><b>{ent ? 'Se entregó además:' : 'Lleva además:'}</b> {window.sumLista(sums)}</div>}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 10, marginTop: 12, paddingBottom: 4, alignItems: 'start' }}>
        <div style={{ fontSize: 12.5, lineHeight: 1.55, minWidth: 0, overflowWrap: 'anywhere' }}>
          {dato('Taller', ticket.taller)}
          {dato('Sede', ticket.sede)}
          {dato('Aseguradora', window.catAseguradoraCorta ? window.catAseguradoraCorta(ticket.aseguradora) : ticket.aseguradora)}
          {docEnt && <div style={{ fontFamily: "'JetBrains Mono', monospace", fontWeight: 700, marginTop: 2 }}>{docEnt}</div>}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 8, flexShrink: 0 }}>
          {chip}
          {fecha &&
          <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 9.5, fontWeight: 800, letterSpacing: '0.06em', color: TOKENS.textSubtle, textTransform: 'uppercase' }}>{ticket.encargo && fechaK === 'Recogida' ? 'Asignado' : fechaK}</div>
              <b style={{ fontSize: 12.5 }}>{fecha}</b>
            </div>}
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', marginTop: 12, paddingTop: 10, borderTop: `1px solid ${TOKENS.border}` }}>
        {celda(sum.rines, 'Rines', 0)}
        {celda(sum.llantas, 'Llantas', 1)}
        {celda(sum.valvulas, 'Válvulas', 2)}
        <span onClick={onVer ? (e) => { e.stopPropagation(); onVer(); } : undefined} style={{ flexShrink: 0, marginLeft: 10, border: `1px solid ${TOKENS.primaryBorder}`, background: TOKENS.primaryBg, color: TOKENS.primary, borderRadius: 9, padding: '7px 12px', fontSize: 12.5, fontWeight: 800 }}>Ver ›</span>
      </div>
    </div>);
}

function PendienteRow({ ticket, onClick }) {
  const daBloqueo = ticketDAporAprobar(ticket);
  const e = window.estadoProcesos ? window.estadoProcesos(ticket) : null;
  const espera = anulacionEnEspera(ticket.id);
  const extras = [espera && <ChipSolicitud key="s" />,
  daBloqueo && <span key="d" style={{ display: 'inline-block', fontSize: 11, fontWeight: 500, borderRadius: 999, padding: '3px 9px', background: '#fff2cc', color: '#7f6000' }}>⏳ Daño adicional por aprobar</span>].filter(Boolean);
  return <TarjetaPlaca ticket={ticket} onClick={onClick}
    chip={e && <span style={{ fontSize: 11.5, fontWeight: 500, borderRadius: 999, padding: '3px 9px', whiteSpace: 'nowrap', background: e.bg, color: e.fg }}>{e.label} · {e.dias} d</span>}
    extra={extras.length ? <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>{extras}</div> : null} />;
}

function MiniStat({ n, label }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'baseline', gap: 4,
      padding: '3px 8px', background: TOKENS.surfaceLow,
      border: `1px solid ${TOKENS.border}`, borderRadius: 999,
      fontSize: 11, fontWeight: 600, color: TOKENS.text
    }}>
      <span style={{ fontFamily: 'monospace', fontWeight: 700, color: TOKENS.primary }}>{n}</span>
      <span style={{ color: TOKENS.textMuted, fontSize: 10 }}>{label}</span>
    </div>);

}

Object.assign(window, {
  EntregarScreen,
  savePendienteTicket, migrarIdTicket, loadPendientesSaved, clearPendientesSaved, removePendienteTicket,
  loadEntregados, markTicketDelivered, clearEntregados,
  updateSavedPendiente, updateEntregaTicket,
  loadAnulaciones, loadAnulacionMap, anulacionFor, anularTicket, reactivarTicket,
  clearAnulaciones, withAnulacion, lastEventoTipo, MOTIVOS_ANULACION,
  loadSolicitudesAnulacion, solicitudAnulacionFor, anulacionEnEspera, solicitarAnulacion, retirarSolicitudAnulacion, responderSolicitudAnulacion,
  AnularTicketModal, AnulacionBlock,
  ticketSummary, PENDIENTES_DEMO,
});

// ─── Modal: anular un registro (motivo obligatorio) ─────────────────────
function AnularTicketModal({ ticket, onConfirm, onDismiss }) {
  const [motivo, setMotivo] = React.useState(null);
  const [nota, setNota] = React.useState('');
  const necesitaNota = motivo === 'Otro';
  const canSend = !!motivo && (!necesitaNota || nota.trim().length > 0);
  return (
    <div onClick={onDismiss} style={{
      position: 'fixed', inset: 0, background: 'rgba(11,28,48,0.5)', zIndex: 1200,
      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: '92vh', overflowY: 'auto',
      }}>
        <div style={{ width: 36, height: 4, borderRadius: 2, background: TOKENS.border, margin: '0 auto 14px' }} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 11, marginBottom: 4 }}>
          <div style={{
            width: 40, height: 40, borderRadius: 11, flexShrink: 0, background: TOKENS.dangerBg,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>{I.ban(21, TOKENS.danger)}</div>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 18, fontWeight: 700, color: TOKENS.text, letterSpacing: '-0.01em' }}>
              Anular registro
            </div>
            <div style={{ fontSize: 12.5, color: TOKENS.textMuted, marginTop: 1 }}>
              <span style={{ fontFamily: 'monospace', fontWeight: 700 }}>{ticket.codigo}</span> · {ticket.placa}
            </div>
          </div>
        </div>
        <div style={{ fontSize: 12.5, color: TOKENS.textMuted, lineHeight: 1.5, margin: '8px 2px 14px' }}>
          Saldrá de la cola de Entregar pero queda registrado en Consultar. Podrás reactivarlo después; el SLA reiniciará desde la reactivación.
        </div>

        <FieldLabel>Motivo *</FieldLabel>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 14 }}>
          {MOTIVOS_ANULACION.map((m) => {
            const on = motivo === m;
            return (
              <button key={m} type="button" onClick={() => setMotivo(m)} style={{
                display: 'flex', alignItems: 'center', gap: 11, width: '100%', textAlign: 'left',
                padding: '12px 14px', borderRadius: 11, cursor: 'pointer', fontFamily: 'inherit',
                border: `1.5px solid ${on ? TOKENS.primary : TOKENS.borderInput}`,
                background: on ? TOKENS.primaryBg : TOKENS.surface,
              }}>
                <span style={{
                  width: 20, height: 20, borderRadius: 999, flexShrink: 0,
                  border: `2px solid ${on ? TOKENS.primary : TOKENS.borderInput}`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  {on && <span style={{ width: 10, height: 10, borderRadius: 999, background: TOKENS.primary }} />}
                </span>
                <span style={{ fontSize: 14, fontWeight: on ? 700 : 600, color: TOKENS.text }}>{m}</span>
              </button>);
          })}
        </div>

        <FieldLabel>{necesitaNota ? 'Detalle del motivo *' : 'Nota (opcional)'}</FieldLabel>
        <textarea
          value={nota}
          onChange={(e) => setNota(e.target.value)}
          placeholder={necesitaNota ? 'Describe por qué se anula…' : 'Información adicional…'}
          rows={3}
          style={{
            width: '100%', boxSizing: 'border-box',
            border: `1px solid ${TOKENS.borderInput}`, background: TOKENS.surfaceLow,
            borderRadius: 10, padding: '10px 14px', fontSize: 14, color: TOKENS.text,
            fontFamily: 'inherit', outline: 'none', resize: 'vertical',
          }} />

        <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
          <Button variant="outline" full onClick={onDismiss}>Cancelar</Button>
          <Button variant="primary" full disabled={!canSend}
            icon={I.ban(16, '#fff')}
            onClick={() => onConfirm({ motivo, nota: nota.trim() })}
            style={{ background: TOKENS.danger, borderColor: TOKENS.danger }}>
            Anular
          </Button>
        </div>
      </div>
    </div>);
}

// ─── Bloque historial de anulación (morado) ─────────────────────────────
// Línea de tiempo: recogido → anulado (motivo) → reactivado → …
function AnulacionBlock({ ticket, anulacion }) {
  if (!anulacion) return null;
  const eventos = [
    { tipo: 'recogido', fecha: anulacion.fechaRecogido || ticket.fecha, hora: anulacion.horaRecogida || ticket.horaRecogida },
    ...(anulacion.historial || []),
  ];
  const meta = {
    recogido: { label: 'Recogido', color: TOKENS.primary, icon: I.recoger },
    anulado: { label: 'Anulado', color: TOKENS.anulado, icon: I.ban },
    reactivado: { label: 'Reactivado', color: TOKENS.success, icon: I.reactivar },
  };
  const isAnulado = anulacion.estadoActual === 'anulado';
  return (
    <Card style={{ marginBottom: 14, padding: 0, overflow: 'hidden' }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '14px 16px', background: isAnulado ? TOKENS.anuladoBg : TOKENS.successBg,
      }}>
        <div style={{
          width: 36, height: 36, borderRadius: 999, flexShrink: 0, color: '#fff',
          background: isAnulado ? TOKENS.anulado : TOKENS.success,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>{isAnulado ? I.ban(20, '#fff') : I.reactivar(20, '#fff')}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontSize: 10, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase',
            color: isAnulado ? TOKENS.anuladoText : TOKENS.successText,
          }}>Estado</div>
          <div style={{ fontSize: 14, fontWeight: 700, color: TOKENS.text, marginTop: 2 }}>
            {isAnulado ? 'Registro anulado' : 'Reactivado · de nuevo pendiente'}
          </div>
        </div>
        <div style={{
          padding: '4px 10px', borderRadius: 999, color: '#fff',
          fontSize: 10, fontWeight: 700, letterSpacing: '0.08em',
          background: isAnulado ? TOKENS.anulado : TOKENS.success,
        }}>{isAnulado ? 'ANULADO' : 'PENDIENTE'}</div>
      </div>

      <div style={{ padding: '14px 16px' }}>
        <div style={{
          fontSize: 10, fontWeight: 700, color: TOKENS.textMuted,
          letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 12,
        }}>Historial</div>
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          {eventos.map((ev, i) => {
            const m = meta[ev.tipo] || meta.anulado;
            const last = i === eventos.length - 1;
            return (
              <div key={i} style={{ display: 'flex', gap: 12 }}>
                {/* Rail */}
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0 }}>
                  <div style={{
                    width: 28, height: 28, borderRadius: 999, flexShrink: 0,
                    background: `${m.color}18`, color: m.color,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>{m.icon(15, m.color)}</div>
                  {!last && <div style={{ width: 2, flex: 1, minHeight: 18, background: TOKENS.border, marginTop: 2 }} />}
                </div>
                {/* Content */}
                <div style={{ flex: 1, minWidth: 0, paddingBottom: last ? 0 : 14 }}>
                  <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 8 }}>
                    <span style={{ fontSize: 13.5, fontWeight: 700, color: TOKENS.text }}>{m.label}</span>
                    <span style={{ fontSize: 11, color: TOKENS.textMuted, fontWeight: 600, whiteSpace: 'nowrap', fontFamily: 'monospace' }}>
                      {ev.fecha}{ev.hora ? ` · ${window.formatHora12(ev.hora)}` : ''}
                    </span>
                  </div>
                  {ev.tipo === 'anulado' && ev.motivo && (
                    <div style={{ fontSize: 12.5, color: TOKENS.anuladoText, fontWeight: 600, marginTop: 3 }}>
                      {ev.motivo}
                    </div>
                  )}
                  {ev.tipo === 'anulado' && ev.nota && (
                    <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 3, lineHeight: 1.45, fontStyle: 'italic' }}>
                      “{ev.nota}”
                    </div>
                  )}
                  {(ev.tipo === 'anulado' || ev.tipo === 'reactivado') && ev.por && (
                    <div style={{ fontSize: 11, color: TOKENS.textSubtle, marginTop: 3 }}>
                      por {ev.por}
                    </div>
                  )}
                </div>
              </div>);
          })}
        </div>
      </div>
    </Card>);
}

// ─── Ficha técnica (detalle de registro pendiente) ──────────────────────
function FichaTecnicaScreen({ ticket, onBack, onEntregar, deliveryInfo, onVerComprobante, onEditar, onImprimir, anulacion, onAnular, onReactivar }) {
  const isDelivered = !!deliveryInfo;
  const daBloqueo = ticketDAporAprobar(ticket);
  const isAnulado = !!(anulacion && anulacion.estadoActual === 'anulado');
  const hasHistorial = !!(anulacion && anulacion.historial && anulacion.historial.length);
  const [confirmEdit, setConfirmEdit] = React.useState(false);
  const WarnModal = window.ConfirmActionModal;
  const sum = ticketSummary(ticket);
  const items = ticket.items || [];
  const rines = items.filter((i) => i.tipo === 'rin');
  const llantas = items.filter((i) => i.tipo === 'llanta');
  const valvulas = items.filter((i) => i.tipo === 'valvula');

  return (
    <div style={{ background: TOKENS.bg, display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
      <AppHeader title="Resumen" onBack={onBack} bell={false} right={
      isDelivered
        ? <Chip tone="success">ENTREGADO</Chip>
        : isAnulado
        ? <Chip tone="anulado">ANULADO</Chip>
        : <Chip tone="pendiente">PENDIENTE</Chip>
      } />
      <div style={{ padding: 16, flex: 1 }}>

        {/* Encabezado: identifica claramente qué registro estamos viendo */}
        <div style={{
            background: TOKENS.heroGradient, color: '#fff', borderRadius: 14,
            padding: '16px 18px', marginBottom: 14
          }}>
          <div style={{ fontSize: 10, opacity: 0.75, letterSpacing: '0.1em', textTransform: 'uppercase', fontWeight: 700 }}>
            Resumen del registro
          </div>
          <div style={{
            display: 'grid', gridTemplateColumns: '1fr 1fr',
            gap: 14, marginTop: 12
          }}>
            <div style={{ minWidth: 0 }}>
              <div style={{
                fontSize: 10,
                letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 4, fontWeight: 600, opacity: 0.7, color: '#fff'
              }}>Orden</div>
              <div style={{
                fontSize: 26, fontWeight: 700, letterSpacing: '0.02em',
                lineHeight: 1, fontFamily: 'monospace', wordBreak: 'break-all'
              }}>
                {ticket.codigo}
              </div>
            </div>
            <div style={{ minWidth: 0, borderLeft: '1px solid rgba(255,255,255,0.2)', paddingLeft: 14 }}>
              <div style={{
                fontSize: 10, opacity: 0.7, fontWeight: 700,
                letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 4
              }}>{ticket.idType === 'vin' ? 'VIN' : 'Placa'}</div>
              <div style={{
                fontSize: 26, fontWeight: 700, letterSpacing: '0.04em',
                lineHeight: 1, wordBreak: 'break-all'
              }}>
                {ticket.placa}
              </div>
            </div>
          </div>
        </div>

        {/* Solicitud de anulación del mensajero: el admin decide aquí (13/11/2026) */}
        {!isDelivered && !isAnulado && <SolicitudAnulacionAdminBox ticket={ticket} />}

        {/* Datos del registro — sin redundar con el header */}
        <SectionTitle>Datos del registro</SectionTitle>

        {/* Bloque 1: estado de entrega / anulación / fechas+días */}
        {isDelivered
          ? <EntregaInfoBlock entrega={deliveryInfo} />
          : isAnulado
          ? <AnulacionBlock ticket={ticket} anulacion={anulacion} />
          : <>
              <FechasBlock fecha={ticket.fecha} hora={ticket.horaRecogida} reactivado={!!ticket.reactivadoFecha} reactivadoFecha={ticket.reactivadoFecha} reactivadoHora={ticket.reactivadoHora} />
              {hasHistorial && <AnulacionBlock ticket={ticket} anulacion={anulacion} />}
            </>
        }

        {/* Bloque 2: Aseguradora / Taller / Sede — visualmente distinto */}
        <Card style={{ marginBottom: 14, padding: 0, overflow: 'hidden' }}>
          <FichaCell label="Aseguradora" value={window.catAseguradoraCorta ? window.catAseguradoraCorta(ticket.aseguradora) : ticket.aseguradora} icon={I.pkg} borderBottom />
          <FichaCell label="Taller" value={ticket.taller} icon={I.dash} borderBottom />
          <FichaCell label="Sede" value={ticket.sede} icon={I.map} />
        </Card>

        {/* Resumen de items */}
        <SectionTitle>
          Resumen de los items recogidos
          <span style={{
            fontSize: 11, fontWeight: 700, color: TOKENS.primary,
            background: TOKENS.surfaceLow, padding: '3px 8px', borderRadius: 6,
            border: `1px solid ${TOKENS.border}`, marginLeft: 8, fontFamily: 'monospace'
          }}>{sum.total} und</span>
        </SectionTitle>

        {/* Mini-summary stats row */}
        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, marginBottom: 12
        }}>
          <SumTile n={sum.rines} label="Rines" icon={I.rin} />
          <SumTile n={sum.llantas} label="Llantas" icon={I.llanta} />
          <SumTile n={sum.valvulas} label="Válvulas" icon={I.ajustes} />
        </div>

        {/* Item groups */}
        {rines.length > 0 && <FichaItemGroup title="RINES" items={rines} />}
        {llantas.length > 0 && <FichaItemGroup title="LLANTAS" items={llantas} />}
        {valvulas.length > 0 && <FichaItemGroup title="VÁLVULAS" items={valvulas} />}
        {items.length === 0 &&
        <div style={{
          padding: 24, textAlign: 'center', color: TOKENS.textMuted, fontSize: 13,
          background: TOKENS.surfaceLow, borderRadius: 12, border: `1px dashed ${TOKENS.border}`
        }}>Sin items registrados.</div>
        }
      </div>

      {/* Sticky action bar */}
      <div style={{
        padding: '12px 16px 16px', borderTop: `1px solid ${TOKENS.border}`,
        background: TOKENS.bg, position: 'sticky', bottom: 0, zIndex: 10,
        display: 'flex', flexDirection: 'column', gap: 10,
      }}>
        {isAnulado ? (
          <>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <Button variant="outline" full onClick={onBack}>Volver</Button>
              <Button variant="primary" full icon={I.reactivar(16, '#fff')} onClick={() => onReactivar && onReactivar()}>
                Reactivar
              </Button>
            </div>
            <Button variant="primary" full icon={I.print(16, '#fff')} onClick={() => onImprimir && onImprimir()}>
              Imprimir
            </Button>
          </>
        ) : (
          <>
            {isDelivered ? (
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                <Button variant="outline" full onClick={onBack}>Volver</Button>
                <Button variant="primary" full icon={I.print(16, '#fff')} onClick={() => onVerComprobante && onVerComprobante()}>
                  Imprimir
                </Button>
                {onEditar && (
                  <Button variant="primary" full icon={I.pencil(16, TOKENS.primary)} onClick={() => setConfirmEdit(true)}
                    style={{ background: TOKENS.primaryBg, borderColor: TOKENS.primaryBorder, color: TOKENS.primary, gridColumn: '1 / -1' }}>
                    Editar
                  </Button>
                )}
              </div>
            ) : (
              <>
                {/* Entregar = acción principal, prominente arriba */}
                {daBloqueo ? (
                  <div>
                    <Button variant="primary" full icon={I.truck(16, '#fff')} disabled>Entregar</Button>
                    <MotivoBloqueo>Daño adicional por aprobar: se podrá entregar cuando el cliente o la aseguradora lo apruebe o se descarte en Recepción.</MotivoBloqueo>
                  </div>
                ) : (
                  <Button variant="primary" full icon={I.truck(16, '#fff')} onClick={() => onEntregar && onEntregar()}>
                    Entregar
                  </Button>
                )}
                <div style={{ display: 'grid', gridTemplateColumns: onEditar ? '1fr 1fr 1fr' : '1fr 1fr', gap: 10 }}>
                  <Button variant="outline" full onClick={onBack}>Volver</Button>
                  {onEditar && (
                    <Button variant="primary" full icon={I.pencil(16, TOKENS.primary)} onClick={() => setConfirmEdit(true)}
                      style={{ background: TOKENS.primaryBg, borderColor: TOKENS.primaryBorder, color: TOKENS.primary }}>
                      Editar
                    </Button>
                  )}
                  <Button variant="outline" full icon={I.print(16, TOKENS.text)} onClick={() => onImprimir && onImprimir()}>
                    Imprimir
                  </Button>
                </div>
              </>
            )}

            {!isDelivered && onAnular && (
              <Button variant="outline" full icon={I.ban(16, TOKENS.anulado)} onClick={() => onAnular()}
                style={{ color: TOKENS.anulado, borderColor: TOKENS.anuladoBorder, background: TOKENS.anuladoBg }}>
                Anular registro
              </Button>
            )}
          </>
        )}
      </div>

      {confirmEdit && WarnModal && (
        <WarnModal
          tone="primary"
          icon={I.pencil(26, TOKENS.primary)}
          title={isDelivered ? 'Editar registro entregado' : 'Editar registro'}
          message={isDelivered
            ? `Vas a editar el registro entregado ${ticket.codigo}. Solo podrás corregir los datos de identificación; los ítems y el comprobante firmado no se modifican. El cambio queda registrado.`
            : `Vas a editar el registro ${ticket.codigo}. Los cambios sobrescribirán la información actual y pueden afectar el comprobante de recogida.`}
          confirmLabel="Editar"
          onConfirm={() => { setConfirmEdit(false); onEditar && onEditar(); }}
          onDismiss={() => setConfirmEdit(false)} />
      )}
    </div>);

}

// ─── Bloque de fechas + días transcurridos ──────────────────────────────
function parseFechaDDMMYYYY(s) {
  if (!s) return null;
  const m = String(s).match(/(\d{1,2})\s*\/\s*(\d{1,2})\s*\/\s*(\d{4})/);
  if (!m) return null;
  const d = new Date(Number(m[3]), Number(m[2]) - 1, Number(m[1]));
  return isNaN(d.getTime()) ? null : d;
}
function daysBetween(a, b) {
  const MS = 24 * 60 * 60 * 1000;
  const da = new Date(a.getFullYear(), a.getMonth(), a.getDate());
  const db = new Date(b.getFullYear(), b.getMonth(), b.getDate());
  return Math.round((db - da) / MS);
}


// ─── Bloque de entrega completada (status delivered) ────────────────────
function EntregaInfoBlock({ entrega }) {
  const [lightboxOpen, setLightboxOpen] = React.useState(false);
  const desp = !!entrega.despachado;
  const foto = desp ? entrega.guiaFoto : entrega.foto;
  return (
    <Card style={{ marginBottom: 14, padding: 0, overflow: 'hidden' }}>
      {lightboxOpen && foto && (
        <PhotoLightbox
          photos={[foto]}
          index={0}
          onIndex={() => {}}
          onClose={() => setLightboxOpen(false)}
          title={desp ? `Guía ${entrega.guia || ''} · ${entrega.transportadora || ''}`.trim() : `Factura ${entrega.factura || ''} · firmada y sellada`.trim()}
        />
      )}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', borderBottom: `1px solid ${TOKENS.border}` }}>
        <FichaCell label="Fecha recogido" value={entrega.fechaRecogido} sub={window.formatHora12(entrega.horaRecogida)} icon={I.doc} borderRight />
        <FichaCell label="Fecha entrega" value={entrega.fechaEntrega} sub={window.formatHora12(entrega.horaEntrega)} icon={I.check} />
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', borderBottom: `1px solid ${TOKENS.border}` }}>
        {desp ? (
          <>
            <FichaCell label="Transportadora" value={entrega.transportadora || '—'} icon={(I.truck || I.pkg)} borderRight />
            <FichaCell label="N.º de guía" value={entrega.guia || '—'} icon={I.doc} mono />
          </>
        ) : (
          <>
            <FichaCell label="Factura / Remisión" value={fmtComprobante(entrega) || '—'} icon={I.doc} mono borderRight />
            <FichaCell label="Recibió" value={entrega.recibePor || '—'} icon={I.user} />
          </>
        )}
      </div>

      {/* Comprobante: foto (factura firmada / guía de transportadora) */}
      {foto && (
        <div style={{ padding: '14px 16px', borderBottom: `1px solid ${TOKENS.border}` }}>
          <div style={{
            fontSize: 10, fontWeight: 700, color: TOKENS.textMuted,
            letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 8,
            display: 'flex', alignItems: 'center', gap: 5,
          }}>
            {I.cam(13, TOKENS.textMuted)}
            <span>{desp ? 'Guía de transportadora' : 'Factura firmada y sellada'}</span>
          </div>
          <button
            type="button"
            onClick={() => setLightboxOpen(true)}
            style={{
              position: 'relative', width: '100%', padding: 0, border: `1px solid ${TOKENS.border}`,
              borderRadius: 12, overflow: 'hidden', cursor: 'pointer', background: '#000',
              display: 'block',
            }}>
            <img src={foto} alt={desp ? 'Guía de transportadora' : 'Factura firmada y sellada'} style={{
              width: '100%', maxHeight: 200, objectFit: 'cover', display: 'block',
            }} />
            <div style={{
              position: 'absolute', bottom: 8, right: 8,
              display: 'flex', alignItems: 'center', gap: 5,
              padding: '5px 10px', borderRadius: 999,
              background: 'rgba(8,12,20,0.72)', color: '#fff',
              fontSize: 11, fontWeight: 600, backdropFilter: 'blur(4px)',
            }}>
              {I.consultar(13, '#fff')}
              <span>Ampliar</span>
            </div>
          </button>
        </div>
      )}

      <div style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '14px 16px', background: TOKENS.successBg,
      }}>
        <div style={{
          width: 36, height: 36, borderRadius: 999,
          background: TOKENS.success, color: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
        }}>{I.check(20, '#fff')}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontSize: 10, fontWeight: 700, color: TOKENS.success,
            letterSpacing: '0.06em', textTransform: 'uppercase',
          }}>Estado</div>
          <div style={{ fontSize: 14, fontWeight: 700, color: TOKENS.text, marginTop: 2 }}>
            Registro entregado correctamente
          </div>
        </div>
        <div style={{
          padding: '4px 10px', borderRadius: 999,
          background: TOKENS.success, color: '#fff',
          fontSize: 10, fontWeight: 700, letterSpacing: '0.08em',
        }}>ENTREGADO</div>
      </div>
    </Card>
  );
}

function FechasBlock({ fecha, hora, reactivado, reactivadoFecha, reactivadoHora }) {
  const basisFecha = reactivado && reactivadoFecha ? reactivadoFecha : fecha;
  const basis = parseFechaDDMMYYYY(basisFecha);
  const hoy = new Date();
  const dias = basis ? daysBetween(basis, hoy) : null;
  const isLate = dias !== null && dias > 3;
  const accent = isLate ? TOKENS.danger : TOKENS.success;
  const accentBg = isLate ? TOKENS.dangerBg : TOKENS.successBg;

  return (
    <Card style={{ marginBottom: 14, padding: 0, overflow: 'hidden' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', borderBottom: `1px solid ${TOKENS.border}` }}>
        <FichaCell label={reactivado ? 'Reloj desde reactivación' : 'Fecha recogido'} value={basisFecha} sub={window.formatHora12(reactivado && reactivadoHora ? reactivadoHora : hora)} icon={reactivado ? I.reactivar : I.doc} borderRight />
        <FichaCell label="Fecha actual" value={fechaDDMMYYYY(hoy)} icon={I.dash} />
      </div>
      {reactivado && (
        <div style={{
          fontSize: 11.5, color: TOKENS.anuladoText, fontWeight: 600,
          padding: '8px 16px', background: TOKENS.anuladoBg,
          borderBottom: `1px solid ${TOKENS.border}`, display: 'flex', alignItems: 'center', gap: 6,
        }}>
          {I.reactivar(13, TOKENS.anulado)}
          <span>Recogido el {fecha} · SLA reiniciado tras reactivación</span>
        </div>
      )}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '14px 16px', background: accentBg
      }}>
        <div style={{
          width: 36, height: 36, borderRadius: 999,
          background: accent, color: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0, fontWeight: 700, fontSize: 16, fontFamily: 'monospace'
        }}>{dias !== null ? dias : '—'}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontSize: 10, fontWeight: 700, color: accent,
            letterSpacing: '0.06em', textTransform: 'uppercase'
          }}>Días pendiente</div>
          <div style={{ fontSize: 14, fontWeight: 700, color: TOKENS.text, marginTop: 2 }}>
            {dias === null ? 'Sin fecha' :
            dias === 0 ? (reactivado ? 'Reactivado hoy' : 'Recogido hoy') :
            dias === 1 ? (reactivado ? '1 día desde la reactivación' : '1 día desde la recogida') :
            `${dias} días desde la ${reactivado ? 'reactivación' : 'recogida'}`}
          </div>
        </div>
        <div style={{
          padding: '4px 10px', borderRadius: 999,
          background: accent, color: '#fff',
          fontSize: 10, fontWeight: 700, letterSpacing: '0.08em'
        }}>{isLate ? 'TARDE' : 'AL DÍA'}</div>
      </div>
    </Card>);

}

function SectionTitle({ children }) {
  return (
    <div style={{
      fontSize: 12, fontWeight: 700, color: TOKENS.textMuted,
      letterSpacing: '0.08em', textTransform: 'uppercase',
      marginBottom: 8, padding: '0 4px',
      display: 'flex', alignItems: 'center'
    }}>{children}</div>);

}

function FichaCell({ label, value, sub, icon, mono, borderRight, borderBottom }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'flex-start', gap: 10,
      padding: '14px 14px',
      borderRight: borderRight ? `1px solid ${TOKENS.border}` : 'none',
      borderBottom: borderBottom ? `1px solid ${TOKENS.border}` : 'none',
      minWidth: 0
    }}>
      <div style={{
        width: 30, height: 30, borderRadius: 8,
        background: TOKENS.surfaceLow, color: TOKENS.primary,
        border: `1px solid ${TOKENS.border}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0
      }}>{icon && icon(15, TOKENS.primary)}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 10, fontWeight: 700, color: TOKENS.textMuted,
          letterSpacing: '0.06em', textTransform: 'uppercase'
        }}>{label}</div>
        <div style={{
          fontSize: 14, fontWeight: 700, color: TOKENS.text, marginTop: 2,
          wordBreak: 'break-all',
          fontFamily: mono ? 'monospace' : 'inherit',
          letterSpacing: mono ? '0.04em' : '0',
          lineHeight: 1.3
        }}>{value || '—'}</div>
        {sub && (
          <div style={{
            fontSize: 11.5, fontWeight: 600, color: TOKENS.textSubtle, marginTop: 2,
            fontFamily: 'monospace', letterSpacing: '0.04em'
          }}>{sub}</div>
        )}
      </div>
    </div>);

}

function FichaRow({ label, value, icon, last, mono }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '14px 16px',
      borderBottom: last ? 'none' : `1px solid ${TOKENS.border}`
    }}>
      <div style={{
        width: 32, height: 32, borderRadius: 8,
        background: TOKENS.surfaceLow, color: TOKENS.primary,
        border: `1px solid ${TOKENS.border}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0
      }}>{icon && icon(16, TOKENS.primary)}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 10, fontWeight: 700, color: TOKENS.textMuted,
          letterSpacing: '0.08em', textTransform: 'uppercase'
        }}>{label}</div>
        <div style={{
          fontSize: 15, fontWeight: 700, color: TOKENS.text, marginTop: 2,
          wordBreak: 'break-all',
          fontFamily: mono ? 'monospace' : 'inherit',
          letterSpacing: mono ? '0.04em' : '0'
        }}>{value || '—'}</div>
      </div>
    </div>);

}

function SumTile({ n, label, icon }) {
  return (
    <div style={{
      background: TOKENS.surface, border: `1px solid ${TOKENS.border}`,
      borderRadius: 12, padding: '12px 10px', textAlign: 'center',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4
    }}>
      <div style={{ color: n > 0 ? TOKENS.primary : TOKENS.textSubtle }}>{icon && icon(18, 'currentColor')}</div>
      <div style={{ fontSize: 22, fontWeight: 700, color: n > 0 ? TOKENS.text : TOKENS.textSubtle, lineHeight: 1, fontFamily: 'monospace' }}>{n}</div>
      <div style={{ fontSize: 10, fontWeight: 700, color: TOKENS.textMuted, letterSpacing: '0.08em', textTransform: 'uppercase' }}>{label}</div>
    </div>);

}

function FichaItemGroup({ title, items }) {
  const total = items.reduce((s, i) => s + Number(i.cantidad), 0);
  return (
    <Card style={{ marginBottom: 12, padding: '14px 16px' }}>
      <div style={{
        fontSize: 11, fontWeight: 700, color: TOKENS.primary,
        letterSpacing: '0.08em', marginBottom: 10,
        display: 'flex', justifyContent: 'space-between', alignItems: 'center'
      }}>
        <span>{title}</span>
        <span style={{ color: TOKENS.textMuted, fontWeight: 600 }}>{total} und</span>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {items.map((it, idx) => <FichaItemRow key={it.id} item={it} idx={idx} />)}
      </div>
    </Card>);

}

// Real attached photo thumbnail (dataURL from Recoger flow) ─────────────
function PhotoReal({ src, idx, onClick }) {
  return (
    <button
      type="button"
      onClick={onClick}
      style={{
        width: 56, height: 56, borderRadius: 10, padding: 0,
        border: `1px solid ${TOKENS.border}`, background: '#000',
        position: 'relative', overflow: 'hidden', flexShrink: 0,
        cursor: 'pointer', boxShadow: '0 2px 6px rgba(11,28,48,0.18)',
      }}>
      <img src={src} alt={`Foto ${idx}`} style={{
        width: '100%', height: '100%', objectFit: 'cover', display: 'block'
      }} />
      <div style={{
        position: 'absolute', bottom: 2, right: 4,
        fontSize: 9, fontWeight: 700, color: 'rgba(255,255,255,0.95)',
        fontFamily: 'monospace', letterSpacing: '0.04em',
        textShadow: '0 1px 2px rgba(0,0,0,0.6)'
      }}>0{idx}</div>
    </button>
  );
}

// Lightbox modal: navigable gallery with prev/next + close ───────────────
function PhotoLightbox({ photos, index, onClose, onIndex, title }) {
  const total = photos.length;
  const go = React.useCallback((dir) => {
    onIndex((index + dir + total) % total);
  }, [index, total, onIndex]);

  // Track the phone column's horizontal bounds so the modal sits inside it,
  // not across the whole browser viewport.
  const [frameBox, setFrameBox] = React.useState(() => {
    if (typeof document === 'undefined') return null;
    const el = document.getElementById('rd-phone-frame');
    if (!el) return null;
    const r = el.getBoundingClientRect();
    return { left: r.left, width: r.width };
  });
  React.useEffect(() => {
    const update = () => {
      const el = document.getElementById('rd-phone-frame');
      if (!el) return;
      const r = el.getBoundingClientRect();
      setFrameBox({ left: r.left, width: r.width });
    };
    update();
    window.addEventListener('resize', update);
    window.addEventListener('scroll', update, true);
    return () => {
      window.removeEventListener('resize', update);
      window.removeEventListener('scroll', update, true);
    };
  }, []);

  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      else if (e.key === 'ArrowRight') go(1);
      else if (e.key === 'ArrowLeft') go(-1);
    };
    window.addEventListener('keydown', onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = prevOverflow;
    };
  }, [go, onClose]);

  // Touch swipe support
  const touchRef = React.useRef(null);
  const onTouchStart = (e) => { touchRef.current = e.touches[0].clientX; };
  const onTouchEnd = (e) => {
    const start = touchRef.current;
    if (start == null) return;
    const dx = e.changedTouches[0].clientX - start;
    if (Math.abs(dx) > 40) go(dx < 0 ? 1 : -1);
    touchRef.current = null;
  };

  const src = photos[index];

  const content = (
    <div
      onClick={onClose}
      onTouchStart={onTouchStart}
      onTouchEnd={onTouchEnd}
      style={{
        position: 'fixed',
        top: 0, bottom: 0,
        left: frameBox ? frameBox.left : 0,
        width: frameBox ? frameBox.width : '100%',
        background: 'rgba(8,12,20,0.94)',
        display: 'flex', flexDirection: 'column',
        zIndex: 9999, cursor: 'default',
      }}>
      {/* Top bar: title + counter + close */}
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '14px 16px', color: '#fff',
          background: 'linear-gradient(to bottom, rgba(0,0,0,0.55), transparent)',
        }}>
        <div style={{ minWidth: 0, flex: 1 }}>
          {title && (
            <div style={{
              fontSize: 10, fontWeight: 700, letterSpacing: '0.1em',
              textTransform: 'uppercase', opacity: 0.65, marginBottom: 2,
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
            }}>{title}</div>
          )}
          <div style={{ fontSize: 15, fontWeight: 700, fontFamily: 'monospace' }}>
            {String(index + 1).padStart(2, '0')} <span style={{ opacity: 0.5 }}>/ {String(total).padStart(2, '0')}</span>
          </div>
        </div>
        <button
          type="button"
          onClick={onClose}
          aria-label="Cerrar"
          style={{
            display: 'flex', alignItems: 'center', gap: 6,
            padding: '8px 12px', borderRadius: 999,
            background: 'rgba(255,255,255,0.12)', border: '1px solid rgba(255,255,255,0.18)',
            color: '#fff', fontSize: 13, fontWeight: 600, cursor: 'pointer',
          }}>
          {I.x(16, '#fff')}
          <span>Cerrar</span>
        </button>
      </div>

      {/* Image stage */}
      <div
        onClick={onClose}
        style={{
          flex: 1, position: 'relative',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          padding: '8px 60px', minHeight: 0,
        }}>
        <img
          key={index}
          src={src}
          alt={`Foto ${index + 1}`}
          onClick={(e) => e.stopPropagation()}
          style={{
            maxWidth: '100%', maxHeight: '100%', objectFit: 'contain',
            borderRadius: 8, boxShadow: '0 10px 40px rgba(0,0,0,0.5)',
            cursor: 'default',
          }} />

        {total > 1 && (
          <>
            <button
              type="button"
              onClick={(e) => { e.stopPropagation(); go(-1); }}
              aria-label="Foto anterior"
              style={lightboxNavBtn('left')}>
              {I.chevLeft(22, '#fff')}
            </button>
            <button
              type="button"
              onClick={(e) => { e.stopPropagation(); go(1); }}
              aria-label="Foto siguiente"
              style={lightboxNavBtn('right')}>
              {I.chevRight(22, '#fff')}
            </button>
          </>
        )}
      </div>

      {/* Bottom: thumbnail strip */}
      {total > 1 && (
        <div
          onClick={(e) => e.stopPropagation()}
          style={{
            display: 'flex', justifyContent: 'center', gap: 8,
            padding: '12px 16px 20px', flexWrap: 'wrap',
          }}>
          {photos.map((p, i) => (
            <button
              key={i}
              type="button"
              onClick={() => onIndex(i)}
              aria-label={`Ir a foto ${i + 1}`}
              style={{
                width: 48, height: 48, padding: 0, borderRadius: 8,
                overflow: 'hidden', cursor: 'pointer', background: '#000',
                border: i === index ? '2px solid #fff' : '2px solid rgba(255,255,255,0.18)',
                opacity: i === index ? 1 : 0.55,
                transition: 'opacity 0.15s, border-color 0.15s',
              }}>
              <img src={p} alt="" style={{
                width: '100%', height: '100%', objectFit: 'cover', display: 'block'
              }} />
            </button>
          ))}
        </div>
      )}
    </div>
  );

  const portalTarget =
    (typeof document !== 'undefined' && document.getElementById('rd-phone-frame')) ||
    (typeof document !== 'undefined' ? document.body : null);
  return portalTarget ? ReactDOM.createPortal(content, portalTarget) : content;
}

function lightboxNavBtn(side) {
  return {
    position: 'absolute', top: '50%', transform: 'translateY(-50%)',
    [side]: 12,
    width: 44, height: 44, borderRadius: 999,
    background: 'rgba(255,255,255,0.14)', border: '1px solid rgba(255,255,255,0.22)',
    color: '#fff', cursor: 'pointer',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    backdropFilter: 'blur(6px)',
  };
}

// Photo placeholder thumbnail (no real image data, demo only) ────────────
function PhotoThumb({ idx, tipo }) {
  const icon = tipo === 'rin' ? I.rin : tipo === 'llanta' ? I.llanta : I.ajustes;
  const bgs = [
  'linear-gradient(135deg, #4a5568, #2d3748)',
  'linear-gradient(135deg, #2c5282, #1a365d)',
  'linear-gradient(135deg, #2d3748, #1a202c)',
  'linear-gradient(135deg, #4a5568, #1a365d)'];

  const bg = bgs[(idx - 1) % bgs.length];
  return (
    <div style={{
      width: 56, height: 56, borderRadius: 10,
      background: bg, position: 'relative', overflow: 'hidden', flexShrink: 0,
      border: `1px solid rgba(255,255,255,0.18)`,
      boxShadow: '0 2px 6px rgba(11,28,48,0.18)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      cursor: 'pointer'
    }}>
      <div style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(circle at 30% 25%, rgba(255,255,255,0.12), transparent 60%)',
        pointerEvents: 'none'
      }} />
      <div style={{ opacity: 0.85, display: 'flex' }}>{icon(22, 'rgba(255,255,255,0.85)')}</div>
      <div style={{
        position: 'absolute', bottom: 2, right: 4,
        fontSize: 9, fontWeight: 700, color: 'rgba(255,255,255,0.85)',
        fontFamily: 'monospace', letterSpacing: '0.04em'
      }}>0{idx}</div>
    </div>);

}

function FichaItemRow({ item, idx }) {
  const isRin = item.tipo === 'rin';
  const isLlanta = item.tipo === 'llanta';
  const isValvula = item.tipo === 'valvula';
  const icon = isRin ? I.rin : isLlanta ? I.llanta : I.ajustes;
  const [lightboxIdx, setLightboxIdx] = React.useState(null);
  const realPhotos = Array.isArray(item.photos) ? item.photos.filter(Boolean) : [];
  const itemLabel =
    isRin ? `Item ${String(idx + 1).padStart(2, '0')} · Rin ${item.tamano || ''}″`.trim() :
    isLlanta ? `Item ${String(idx + 1).padStart(2, '0')} · ${item.referencia || 'Llanta'}` :
    `Item ${String(idx + 1).padStart(2, '0')} · Válvula`;

  return (
    <div style={{
      background: TOKENS.surfaceLow, borderRadius: 12, padding: '12px 14px',
      display: 'flex', alignItems: 'flex-start', gap: 12
    }}>
      {lightboxIdx != null && realPhotos.length > 0 && (
        <PhotoLightbox
          photos={realPhotos}
          index={lightboxIdx}
          onIndex={setLightboxIdx}
          onClose={() => setLightboxIdx(null)}
          title={itemLabel}
        />
      )}
      {/* Columna izquierda: ícono + cantidad debajo */}
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, flexShrink: 0 }}>
        <div style={{
          width: 34, height: 34, borderRadius: 10, background: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: TOKENS.primary, border: `1px solid ${TOKENS.border}`,
        }}>{icon(18, TOKENS.primary)}</div>
        <div style={{
          fontSize: 13, fontWeight: 700, color: TOKENS.primary,
          background: '#fff', padding: '4px 10px', borderRadius: 6,
          border: `1px solid ${TOKENS.border}`, minWidth: 30, textAlign: 'center', fontFamily: 'monospace'
        }}>×{item.cantidad}</div>
      </div>
      <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column' }}>
        <div style={{
          fontSize: 10, fontWeight: 700, color: TOKENS.navy, letterSpacing: '0.08em',
          marginBottom: 2
        }}>ITEM {String(idx + 1).padStart(2, '0')}</div>
        <div style={{ fontSize: 14, fontWeight: 700, color: TOKENS.text }}>
          {isRin && `Rin ${item.tamano}″${item.material ? ` ${item.material}` : ''}`}
          {isLlanta && `${item.marca ? item.marca + ' ' : ''}${item.referencia || 'Llanta'}`}
          {isValvula && `Válvula ${item.valvulaSensor === 'Sí' ? 'TPMS' : 'estándar'}`}
        </div>
        <div style={{
          fontSize: 12, color: TOKENS.textMuted, marginTop: 6,
          display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 4, lineHeight: 1.5
        }}>
          {isRin && <>
            <span>{item.huecos}</span><span>·</span>
            <span>Tapa</span>
            <Chip tone={item.tapa === 'Sí' ? 'success' : 'danger'}>{item.tapa === 'Sí' ? 'SÍ' : 'NO'}</Chip>
            <span>·</span>
            <span>T. Válvula</span>
            <Chip tone={item.tapaValvula === 'Sí' ? 'success' : 'danger'}>{item.tapaValvula === 'Sí' ? 'SÍ' : 'NO'}</Chip>
          </>}
          {isLlanta && <span>{(() => {
            const g = llantaBreakdown(item, 'dot');
            return g.length > 1 ? `${g.length} DOT distintos` : `DOT ${(g[0] && g[0].value) || item.dot || '—'}`;
          })()}</span>}
          {isLlanta && (() => {
            const g = llantaBreakdown(item, 'calidad');
            return g.length > 1
              ? <Chip tone="neutral">{`${g.length} calidades`}</Chip>
              : <Chip tone={calidadTone((g[0] && g[0].value) || item.calidad)}>{(g[0] && g[0].value) || item.calidad}</Chip>;
          })()}
          {isValvula && <span>{item.valvulaSensor === 'Sí' ? 'Con sensor TPMS' : 'Sin sensor'}</span>}
        </div>

        {/* DOT agrupado cuando difieren */}
        {isLlanta && llantaBreakdown(item, 'dot').length > 1 && (
          <div style={{ marginTop: 8 }}>
            <LlantaDotValue item={item} align="flex-start" />
          </div>
        )}

        {/* Calidad agrupada cuando difieren */}
        {isLlanta && llantaBreakdown(item, 'calidad').length > 1 && (
          <div style={{ marginTop: 8 }}>
            <LlantaCalidadValue item={item} align="flex-start" />
          </div>
        )}

        {/* Fotos adjuntas: alineadas bajo la info, a ancho completo de la columna */}
        {(() => {
          const count = realPhotos.length > 0 ? realPhotos.length : Number(item.fotos) || 0;
          if (count === 0) return null;
          return (
            <div style={{ marginTop: 12 }}>
              <div style={{
                fontSize: 10, fontWeight: 700, color: TOKENS.textMuted,
                letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 6,
                display: 'flex', alignItems: 'center', gap: 5
              }}>
                {I.cam(13, TOKENS.textMuted)}
                <span>{count} {count === 1 ? 'foto adjunta' : 'fotos adjuntas'}</span>
              </div>
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                {realPhotos.length > 0
                  ? realPhotos.map((src, i) =>
                      <PhotoReal key={i} src={src} idx={i + 1} onClick={() => setLightboxIdx(i)} />)
                  : Array.from({ length: count }).map((_, i) =>
                      <PhotoThumb key={i} idx={i + 1} tipo={item.tipo} />
                    )}
              </div>
            </div>);
        })()}
      </div>
    </div>);

}

// ─── Banner de fecha/hora de entrega (en vivo) ──────────────────────────
function FechaEntregaBanner() {
  const [now, setNow] = React.useState(new Date());
  React.useEffect(() => {
    const t = setInterval(() => setNow(new Date()), 1000 * 30);
    return () => clearInterval(t);
  }, []);
  const dias = ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'];
  const meses = ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre'];
  const fechaLarga = `${dias[now.getDay()]}, ${now.getDate()} de ${meses[now.getMonth()]} de ${now.getFullYear()}`;
  const hora = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      background: TOKENS.successBg, border: `1px solid ${TOKENS.successBorder}`,
      borderRadius: 12, padding: '12px 14px', marginBottom: 14,
    }}>
      <div style={{
        width: 40, height: 40, borderRadius: 10,
        background: TOKENS.success, color: '#fff', flexShrink: 0,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>{I.check(22, '#fff')}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 10, fontWeight: 700, color: TOKENS.success,
          letterSpacing: '0.07em', textTransform: 'uppercase', marginBottom: 2,
        }}>Fecha y hora de entrega</div>
        <div style={{
          fontSize: 15, fontWeight: 700, color: TOKENS.text, lineHeight: 1.25,
          textTransform: 'capitalize',
        }}>{fechaLarga}</div>
      </div>
      <div style={{
        textAlign: 'right', flexShrink: 0, paddingLeft: 8,
        borderLeft: `1px solid ${TOKENS.successBorder}`,
      }}>
        <div style={{
          fontSize: 22, fontWeight: 700, color: TOKENS.success,
          fontFamily: 'monospace', lineHeight: 1,
        }}>{window.formatHora12(hora)}</div>
        <div style={{
          fontSize: 9, fontWeight: 700, color: TOKENS.success, opacity: 0.7,
          letterSpacing: '0.08em', textTransform: 'uppercase', marginTop: 3,
        }}>Hora actual</div>
      </div>
    </div>
  );
}

// ─── EntregaConfirm: form para registrar entrega ─────────────────────────

// ─── Resumen de una placa por entregar (13/11/2026) ─────────────────────
// Mismo formato que Revisar recogida: placa + estado, datos, ítems y fotos de la
// recogida. Botones al final (sin barra fija).
function ResumenEntregaScreen({ ticket, onBack, onEntregar, onImprimir, puedeSolicitarAnulacion, anulado, admin, onEditar, onAnular, onReactivar }) {
  const [, refrescar] = React.useState(0);
  React.useEffect(() => {
    const r = () => refrescar((n) => n + 1);
    window.addEventListener('rodando-anulaciones', r);
    return () => window.removeEventListener('rodando-anulaciones', r);
  }, []);
  const sol = anulado ? null : solicitudAnulacionFor(ticket.id);
  const enEspera = !!(sol && sol.estado === 'espera');
  const [pedir, setPedir] = React.useState(false);
  const [retirar, setRetirar] = React.useState(false);
  const [aviso, setAviso] = React.useState(false);
  React.useEffect(() => { if (!aviso) return; const t = setTimeout(() => setAviso(false), 3500); return () => clearTimeout(t); }, [aviso]);
  const items = ticket.items || [];
  const total = items.reduce((s, it) => s + (Number(it.cantidad) || 0), 0);
  const fotos = (ticket.fotosPlaca || []).filter(Boolean);
  const e = anulado ? { label: 'Anulado', bg: TOKENS.anuladoBg, fg: TOKENS.anuladoText, sinDias: true } : window.estadoProcesos ? window.estadoProcesos(ticket) : null;
  const daBloqueo = ticketDAporAprobar(ticket);
  const [verFoto, setVerFoto] = React.useState(null);
  const sumsF = window.suministrosDe ? window.suministrosDe(ticket.id) : [];
  const nRinesF = window.servDe ? window.servDe(ticket).rines.length : 0;
  const [srDlg, setSrDlg] = React.useState(false);
  const [, bumpSv] = React.useReducer((n) => n + 1, 0);
  const fecha = String(ticket.fecha || '').replace(/\s/g, '');
  const hora = ticket.horaRecogida ? (window.formatHora12 ? window.formatHora12(ticket.horaRecogida) : ticket.horaRecogida) : '';
  // Días hábiles: explicación como en el PC (pausa / desde la autorización / desde la recogida).
  const diasTxt = (() => {
    try {
      const sv = window.servDe ? window.servDe(ticket) : { rines: [] };
      const esp = (sv.rines || []).map((x, i) => ({ x, i })).filter((o) => o.x.aut && o.x.aut.estado === 'espera');
      if (e && e.pausa && esp.length) return `contados · detenido desde el ${esp[0].x.aut.desde} por el rin ${esp.map((o) => o.i + 1).join(', ')}`;
      const re = window.reinicioPlazo ? window.reinicioPlazo(ticket.id) : null;
      if (re) return `contados desde la autorización del ${re.fecha}`;
    } catch (x) {}
    return 'desde la recogida';
  })();
  return (
    <div style={{ background: TOKENS.bg, display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
      <AppHeader title="Resumen" onBack={onBack} />
      <div style={{ padding: '14px 16px 24px' }}>
        <Card style={{ padding: '14px 14px', background: TOKENS.surface }}>
          <CabeceraPlaca ticket={ticket} grande />
        </Card>
        <TriDatos aseguradora={ticket.aseguradora} taller={ticket.taller} sede={ticket.sede} />
        {ticket.cliente && <FichaSeccion titulo="Cliente"><FichaTabla filas={[['Nombre', ticket.cliente.nombre], ['Teléfono', ticket.cliente.telefono], ['Dirección', ticket.cliente.direccion]]} /></FichaSeccion>}
        <FichaSeccion titulo="Cumplimiento">
          <FichaTabla filas={[
          !anulado && filaPrioridad(ticket),
          ['Estado', anulado ? fichaChip('Anulado', TOKENS.anuladoBg, TOKENS.anuladoText) : e ? e.pausa ? (window.PcChipPausa ? <window.PcChipPausa /> : fichaChip('En pausa', '#fdf0d5', '#8a5a00')) : fichaChip(e.label, e.bg, e.fg) : null],
          !anulado && e && ['Días hábiles', <>{e.dias} {fichaSub(diasTxt)}</>]]} />
        </FichaSeccion>

        {/* 23/11/2026: suministros y novedades del registro, como en el PC. */}
        {!anulado && sumsF.length > 0 && <FichaSeccion titulo="Suministros">
          <FichaTabla filas={[['Recogido', window.pcItemsTxt ? window.pcItemsTxt(ticket.items) : ''], ['Se entrega', <>{window.pcItemsTxt ? window.pcItemsTxt(ticket.items) : ''} <span style={{ color: '#0e7490' }}>+ {window.sumLista(sumsF)}</span></>]]} />
        </FichaSeccion>}
        {!anulado && window.NovedadesFichaCel && <window.NovedadesFichaCel r={{ ...ticket, _estado: 'pend' }} onFoto={setVerFoto} />}

        {/* Admin: decide la solicitud aquí */}
        {admin && !anulado && <div style={{ marginTop: 12 }}><SolicitudAnulacionAdminBox ticket={ticket} /></div>}

        {/* Solicitud de anulación (13/11/2026) */}
        {enEspera && !admin &&
        <div style={cajaAnu}>
            <b style={{ display: 'block', fontSize: 13.5, marginBottom: 2 }}>⏳ Anulación solicitada</b>
            Motivo: {sol.motivo}{sol.nota ? ` · "${sol.nota}"` : ''}<br />
            Esperando respuesta del administrador. Mientras tanto no se puede entregar.
            {puedeSolicitarAnulacion &&
          <div><button type="button" onClick={() => setRetirar(true)} style={{ marginTop: 8, padding: 0, border: 0, background: 'none', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 800, color: TOKENS.anuladoText, textDecoration: 'underline', cursor: 'pointer' }}>Retirar solicitud</button></div>
          }
          </div>
        }
        {sol && sol.estado === 'rechazada' && !admin &&
        <div style={{ ...cajaAnu, background: TOKENS.surfaceLow, color: TOKENS.textMuted, border: `1px solid ${TOKENS.border}` }}>
            <b style={{ display: 'block', fontSize: 13.5, marginBottom: 2, color: TOKENS.text }}>Solicitud de anulación rechazada</b>
            {sol.respondidoPorNombre || 'El administrador'}: "{sol.respuesta}"
          </div>
        }
        {anulado && !admin &&
        <div style={cajaAnu}>
            <b style={{ display: 'block', fontSize: 13.5, marginBottom: 2 }}>Registro anulado</b>
            Motivo: {anulado.motivo || '—'}{anulado.nota ? ` · "${anulado.nota}"` : ''}{anulado.por ? <><br />Anuló: {anulado.por}{anulado.fecha ? ` · ${String(anulado.fecha).replace(/\s/g, '')}` : ''}</> : null}
          </div>
        }

        {admin && anulado && <HistorialRegistro ticket={ticket} />}

        <RecogidaSeccion fecha={ticket.fecha} hora={ticket.horaRecogida} por={ticket.recogidoPorNombre} items={items} fotos={fotos} onFoto={setVerFoto} />

        {admin && !anulado && <HistorialRegistro ticket={ticket} />}

        {/* Acciones al final */}
        <div style={{ display: 'grid', gap: 8, marginTop: 16 }}>
          {anulado ? null : enEspera || daBloqueo ?
          <div>
              <Button variant="primary" full icon={I.truck(18, '#fff')} disabled style={{ padding: '14px', fontSize: 15 }}>Entregar esta placa</Button>
              <MotivoBloqueo>{enEspera ? 'Hay una solicitud de anulación en espera.' : 'Daño adicional por aprobar: se podrá entregar cuando el cliente o la aseguradora lo apruebe o se descarte en Recepción.'}</MotivoBloqueo>
            </div> :
          <Button variant="primary" full icon={I.truck(18, '#fff')} onClick={onEntregar} style={{ padding: '14px', fontSize: 15 }}>Entregar esta placa</Button>
          }
          {!anulado && nRinesF > 0 && window.SinRepararDlg && <Button variant="outline" full onClick={() => setSrDlg(true)} style={{ padding: '13px', fontSize: 15, color: TOKENS.primary }}>⊘ Rin que no se repara</Button>}
          <Button variant="outline" full icon={I.print(16, TOKENS.primary)} onClick={onImprimir} style={{ padding: '13px', fontSize: 15, color: TOKENS.primary }}>Imprimir resumen</Button>
          {puedeSolicitarAnulacion && !anulado && !enEspera &&
          <Button variant="outline" full icon={I.ban(16, TOKENS.danger)} onClick={() => setPedir(true)} style={{ padding: '13px', fontSize: 15, color: TOKENS.danger, borderColor: TOKENS.borderInput, borderWidth: 1.5 }}>Solicitar anulación</Button>
          }
        </div>
        {admin && <AccionesAdmin onEditar={onEditar} onAnular={onAnular} onReactivar={onReactivar} />}
      </div>
      {srDlg && <window.SinRepararDlg r={ticket} onCancel={() => setSrDlg(false)} onOk={(L) => { window.servFijarSinReparar(ticket, L); setSrDlg(false); bumpSv(); }} />}
      {verFoto && <FotoGrande src={verFoto} onClose={() => setVerFoto(null)} />}
      {pedir && <SolicitarAnulacionModal ticket={ticket} onDismiss={() => setPedir(false)} onEnviar={({ motivo, nota }) => { solicitarAnulacion(ticket, { motivo, nota }); setPedir(false); setAviso(true); refrescar((n) => n + 1); }} />}
      {retirar &&
      <ConfirmActionModal
        icon={I.x(24, TOKENS.danger)}
        tone="danger"
        title="¿Retirar la solicitud?"
        message={`La placa ${ticket.placa} vuelve a quedar pendiente por entregar, sin anulación.`}
        confirmLabel="Retirar"
        onConfirm={() => { retirarSolicitudAnulacion(sol.id); setRetirar(false); refrescar((n) => n + 1); }}
        onDismiss={() => setRetirar(false)} />
      }
      {aviso && ReactDOM.createPortal(
        <div onClick={() => setAviso(false)} style={{ position: 'fixed', left: 16, right: 16, bottom: 24, zIndex: 1200, background: TOKENS.navyDark, color: '#fff', borderRadius: 12, padding: '11px 13px', fontSize: 12.5, lineHeight: 1.4, boxShadow: '0 10px 24px rgba(11,28,48,.3)', maxWidth: 420, margin: '0 auto' }}>
          <b style={{ display: 'block', fontSize: 13 }}>Solicitud enviada</b>Le llegó al administrador. Te avisamos en la campana cuando responda.
        </div>, document.body)}
    </div>);

}

// ─── Resumen de un registro entregado (13/11/2026) ──────────────────────
// Placa 24 px, datos, bloque "Entrega" (fecha, cómo, comprobante, recibe, quién
// entregó y hojas), ítems y fotos de la recogida. Botón al final.
function ResumenEntregadoScreen({ entrega, onBack, onImprimir, admin, onEditar }) {
  const e = entrega || {};
  const desp = !!e.despachado;
  const hojas = desp ? ((e.guiaFotos && e.guiaFotos.length) ? e.guiaFotos : (e.guiaFoto ? [e.guiaFoto] : [])) :
  ((e.fotos && e.fotos.length) ? e.fotos : (e.foto ? [e.foto] : []));
  const items = e.items || [];
  const total = items.reduce((s, it) => s + (Number(it.cantidad) || 0), 0);
  const fotos = (e.fotosPlaca || []).filter(Boolean);
  const [verFoto, setVerFoto] = React.useState(null);
  const [pedirCor, setPedirCor] = React.useState(false);
  const [, refrescarCor] = React.useState(0);
  React.useEffect(() => { const r = () => refrescarCor((n) => n + 1); window.addEventListener('rodando-servicios', r); return () => window.removeEventListener('rodando-servicios', r); }, []);
  const f12 = (h) => h ? (window.formatHora12 ? window.formatHora12(h) : h) : '';
  const limpia = (x) => String(x || '').replace(/\s/g, '');
  const kv = (k, v, mono) => <>
      <span style={{ color: TOKENS.textMuted, fontWeight: 600 }}>{k}</span>
      <b style={{ fontWeight: 700, color: TOKENS.text, minWidth: 0, overflowWrap: 'anywhere', fontFamily: mono ? "'JetBrains Mono', monospace" : undefined }}>{v || '—'}</b>
    </>;
  const grid = { display: 'grid', gridTemplateColumns: 'auto 1fr', gap: '5px 12px', fontSize: 13 };
  const docNombre = desp ? 'guía' : (e.comprobanteTipo || 'Factura').toLowerCase();
  const pe = plazoEntrega(e);
  const gars = (window.garantiasDe ? window.garantiasDe(e.ticketId) : []).slice().sort((a, b) => (a.estado === 'abierta' ? 0 : 1) - (b.estado === 'abierta' ? 0 : 1));
  return (
    <div style={{ background: TOKENS.bg, display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
      <AppHeader title="Resumen" onBack={onBack} />
      <div style={{ padding: '14px 16px 24px' }}>
        <Card style={{ padding: '14px 14px', background: TOKENS.surface }}>
          <CabeceraPlaca ticket={{ ...e, id: e.ticketId }} grande />
        </Card>
        <TriDatos aseguradora={e.aseguradora} taller={e.taller} sede={e.sede} />
        {e.cliente && <FichaSeccion titulo="Cliente"><FichaTabla filas={[['Nombre', e.cliente.nombre], ['Teléfono', e.cliente.telefono], ['Dirección', e.cliente.direccion]]} /></FichaSeccion>}
        <FichaSeccion titulo="Cumplimiento">
          <FichaTabla filas={[
          filaPrioridad(e),
          // 20/11/2026: igual que el PC — solo el estado (sin "a tiempo / tarde").
          ['Estado', gars.some((g) => g.estado === 'abierta') ? fichaChip('Garantía', '#e6f7fa', '#0e7490') : <ChipEntregado />],
          ['Días hábiles', <>{pe.dias} {fichaSub(pe.re ? `desde la autorización del ${pe.re.fecha} a la entrega` : 'de la recogida a la entrega')}</>]]} />
        </FichaSeccion>

        {gars.map((g) => <GarantiaFichaCard key={g.id} ticket={e} g={g} onFoto={setVerFoto} />)}

        <FichaSeccion titulo={gars.length ? 'Primera entrega' : 'Entrega'} derecha={<ChipEntregado />}>
          <FichaTabla filas={[
          ['Fecha', <>{limpia(e.fechaEntrega)}{e.horaEntrega ? ' · ' + f12(e.horaEntrega) : ''} {e.entregadoPorNombre && fichaSub(e.entregadoPorNombre)}</>],
          ['Cómo', desp ? 'Transportadora' : 'Directo'],
          desp ? ['Transportadora', <>{e.transportadora || '—'}{e.guia && <> · <span style={{ fontFamily: "'JetBrains Mono', monospace" }}>{e.guia}</span></>}</>] :
          [/remisi/i.test(e.comprobanteTipo || '') ? 'Remisión' : 'Factura', <>{e.factura ? <span style={{ fontFamily: "'JetBrains Mono', monospace" }}>{fmtComprobante(e)}</span> : '—'} {e.recibePor && fichaSub('recibe ' + e.recibePor)}</>],
          ...((e.sinReparar || []).length ? [['Novedad', <span style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>{e.sinReparar.map((x) => { const na = /autoriz/i.test(x.motivo || ''); return <span key={x.i}>Rin {x.i + 1} <span style={{ fontSize: 11.5, fontWeight: 500, borderRadius: 99, padding: '2px 8px', background: na ? '#efe9f7' : '#fbe3e1', color: na ? '#6c4aa6' : '#9c443c', marginLeft: 4 }}>{na ? 'No autorizado' : 'No reparable'}</span> {fichaSub('no se cobra')}</span>; })}</span>]] : []),
          ...((e.suministros || []).length ? [['Se entregó además', <span style={{ color: '#0e7490' }}>{window.sumLista ? window.sumLista(e.suministros) : ''}</span>]] : [])]} />
          {(e.sinReparar || []).some((x) => x.foto) && <>{fichaSubt('Carta · rin sin reparar')}{fichaFotosGrid([...new Set(e.sinReparar.map((x) => x.foto).filter(Boolean))], setVerFoto, true)}</>}
          {fichaSubt(`Fotos de la ${docNombre} · ${hojas.length} ${hojas.length === 1 ? 'hoja' : 'hojas'}`)}
          {fichaFotosGrid(hojas, setVerFoto, true)}
        </FichaSeccion>

        {window.NovedadesFichaCel && <window.NovedadesFichaCel r={{ ...e, id: e.ticketId, _estado: 'ent', _ent: e }} onFoto={setVerFoto} />}
        <RecogidaSeccion fecha={e.fechaRecogido} hora={e.horaRecogida} por={e.recogidoPorNombre} items={items} fotos={fotos} onFoto={setVerFoto} />

        <CorreccionBox ticketId={e.ticketId} admin={admin} />
        {admin && <HistorialRegistro entrega={e} />}

        <div style={{ display: 'grid', gap: 8, marginTop: 16 }}>
          <Button variant="outline" full icon={I.print(16, TOKENS.primary)} onClick={onImprimir} style={{ padding: '13px', fontSize: 15, color: TOKENS.primary }}>Imprimir constancia</Button>
          {!admin && !correccionEnEspera(e.ticketId) &&
          <Button variant="outline" full icon={I.pencil(16, TOKENS.primary)} onClick={() => setPedirCor(true)} style={{ padding: '13px', fontSize: 15, color: TOKENS.primary }}>Pedir corrección</Button>}
        </div>
        {admin && <AccionesAdmin onEditar={onEditar} notaEditar="Solo se corrigen datos de identificación (placa, taller, sede, aseguradora). Los ítems y el comprobante firmado no cambian." />}
      </div>
      {verFoto && <FotoGrande src={verFoto} onClose={() => setVerFoto(null)} />}
      {pedirCor && <PedirCorreccionModal entrega={e} onDismiss={() => setPedirCor(false)} onEnviar={(v) => { pedirCorreccion(e, v); setPedirCor(false); refrescarCor((n) => n + 1); }} />}
    </div>);
}

// ─── Pedir corrección de una entrega (18/11/2026) ────────────────────────
// El mensajero pide corregir algo de una placa ya entregada: qué (motivo) + nota
// obligatoria y, si es placa o taller/sede, el valor correcto. El administrador
// aprueba (se aplica el cambio) o rechaza explicando por qué. Nada cambia sin aprobar.
const LS_CORRECCIONES = 'rodando.correcciones';
const MOTIVOS_CORRECCION = ['Placa', 'Rines entregados', 'Taller / sede', 'Firma o foto', 'Otro'];
function loadCorrecciones() { try { return JSON.parse(localStorage.getItem(LS_CORRECCIONES) || '[]'); } catch (e) { return []; } }
function saveCorrecciones(l) { window.safeSetItem(LS_CORRECCIONES, JSON.stringify(l)); window.dispatchEvent(new Event('rodando-anulaciones')); }
function correccionesDe(ticketId) { return loadCorrecciones().filter((x) => x.ticketId === ticketId); }
function correccionEnEspera(ticketId) { return loadCorrecciones().find((x) => x.ticketId === ticketId && x.estado === 'espera') || null; }
function pedirCorreccion(e, { campo, nuevo, nota }) {
  const yo = quien(); const now = _nowFechaHora();
  const c = {
    id: 'co-' + now.ts, ticketId: e.ticketId, codigo: e.codigo, placa: e.placa, taller: e.taller, sede: e.sede,
    campo, nuevo: nuevo || null, antes: campo === 'Placa' ? { placa: e.placa } : campo === 'Taller / sede' ? { taller: e.taller, sede: e.sede } : null,
    nota: (nota || '').trim(), por: yo.usuario, porNombre: yo.nombre, fecha: now.fecha, hora: now.hora, createdAt: now.ts, estado: 'espera'
  };
  saveCorrecciones([c, ...loadCorrecciones().filter((x) => !(x.ticketId === e.ticketId && x.estado === 'espera'))]);
  if (window.addNotif) window.addNotif({
    id: 'n-co-' + now.ts, tipo: 'correccion', para: 'admin', estado: 'pendiente',
    taller: e.taller, sede: e.sede, accion: 'otro', referencia: `${e.codigo} · ${e.placa}`,
    motivo: `${campo}: ${c.nota}`, titulo: `Corrección solicitada · ${e.placa}`,
    mensaje: `${yo.nombre || 'El mensajero'} pidió corregir una entrega · ${campo}`,
    correccionId: c.id, actor: yo.usuario, createdAt: now.ts, resolucion: null
  });
  return c;
}
function retirarCorreccion(id) {
  saveCorrecciones(loadCorrecciones().map((x) => x.id === id ? { ...x, estado: 'retirada', retiradaEn: Date.now() } : x));
  if (window.loadNotifs && window.updateNotif) window.loadNotifs().filter((n) => n.correccionId === id && n.estado === 'pendiente').forEach((n) => window.updateNotif(n.id, { estado: 'resuelta', resolucion: 'vista', resolvedAt: Date.now() }));
}
function responderCorreccion(id, { aprobar, respuesta }) {
  const yo = quien(); const l = loadCorrecciones(); const c = l.find((x) => x.id === id);
  if (!c || c.estado !== 'espera') return;
  const upd = { ...c, estado: aprobar ? 'aprobada' : 'rechazada', respuesta: (respuesta || '').trim(), respondidoPor: yo.usuario, respondidoPorNombre: yo.nombre, respondidoEn: Date.now() };
  saveCorrecciones(l.map((x) => x.id === id ? upd : x));
  // Se aplica solo lo que el mensajero propuso (placa o taller/sede); lo demás lo corrige el admin a mano.
  if (aprobar && c.nuevo) {
    updateEntregaTicket(c.ticketId, c.nuevo);
    const ps = loadPendientesSaved(); const i = ps.findIndex((t) => t.id === c.ticketId);
    if (i >= 0) { ps[i] = { ...ps[i], ...c.nuevo }; window.safeSetItem(LS_PENDIENTES_KEY, JSON.stringify(ps)); }
  }
  if (window.loadNotifs && window.updateNotif) window.loadNotifs().filter((n) => n.correccionId === id && n.estado === 'pendiente').forEach((n) => window.updateNotif(n.id, { estado: 'resuelta', resolucion: aprobar ? 'aceptada' : 'rechazada', resolvedAt: Date.now() }));
  if (window.addNotif) window.addNotif({
    id: 'n-cor-' + Date.now(), tipo: 'correccion', para: 'mensajero', paraUsuario: c.por || null, estado: 'pendiente',
    taller: c.taller, sede: c.sede, accion: 'otro', referencia: `${c.codigo} · ${c.placa}`, motivo: upd.respuesta,
    titulo: aprobar ? `Corrección aprobada · ${c.placa}` : `Corrección rechazada · ${c.placa}`,
    mensaje: aprobar ? `${yo.nombre || 'El administrador'} aprobó la corrección (${c.campo})` : `${yo.nombre || 'El administrador'} no aprobó la corrección (${c.campo})`,
    correccionId: c.id, actor: 'admin', createdAt: Date.now(), resolucion: null
  });
}
// Chip ámbar mientras la corrección espera respuesta.
function ChipCorreccion() {
  const P = window.PAUSA_COLOR || { bg: '#fdf0d5', fg: '#8a5a00', bd: '#f1d49b' };
  return <span style={{ display: 'inline-block', fontSize: 11.5, fontWeight: 500, borderRadius: 999, padding: '3px 9px', whiteSpace: 'nowrap', background: P.bg, color: P.fg, border: `1px solid ${P.bd}` }}>Corrección en espera</span>;
}
// Antes → después de lo que se pide cambiar.
function CorreccionDiff({ c }) {
  if (!c.nuevo) return null;
  const filas = c.campo === 'Placa' ? [['Placa', c.antes && c.antes.placa, c.nuevo.placa]] :
  [['Taller', c.antes && c.antes.taller, c.nuevo.taller], ['Sede', c.antes && c.antes.sede, c.nuevo.sede]].filter((f) => f[1] !== f[2]);
  return <div style={{ display: 'grid', gridTemplateColumns: 'auto 1fr 1fr', gap: '5px 10px', fontSize: 12.5, margin: '9px 0 2px', alignItems: 'baseline' }}>
    {filas.map(([k, a, b]) => <React.Fragment key={k}>
      <span style={{ color: TOKENS.textMuted, fontWeight: 500 }}>{k}</span>
      <span style={{ color: TOKENS.textSubtle, textDecoration: 'line-through' }}>{a || '—'}</span>
      <span style={{ color: TOKENS.text, fontWeight: 600 }}>{b || '—'}</span>
    </React.Fragment>)}
  </div>;
}
// Modal del mensajero: qué corregir + nota obligatoria (+ valor correcto si aplica).
function PedirCorreccionModal({ entrega, onEnviar, onDismiss }) {
  const [campo, setCampo] = React.useState(null);
  const [nota, setNota] = React.useState('');
  const [placa, setPlaca] = React.useState('');
  const [taller, setTaller] = React.useState(entrega.taller || '');
  const [sede, setSede] = React.useState(entrega.sede || '');
  const [tallerNuevo, setTallerNuevo] = React.useState(false); // taller que no está en el catálogo → por revisar
  const nuevo = campo === 'Placa' ? { placa: placa.trim().toUpperCase() } : campo === 'Taller / sede' ? { taller: taller.trim(), sede: sede.trim() } : null;
  const valOk = campo === 'Placa' ? nuevo.placa.length > 0 && nuevo.placa !== String(entrega.placa || '').toUpperCase() :
  campo === 'Taller / sede' ? nuevo.taller.length > 0 && (tallerNuevo || nuevo.sede || !(window.catSedesDe && window.catSedesDe(nuevo.taller).length)) && (nuevo.taller !== entrega.taller || nuevo.sede !== (entrega.sede || '')) : true;
  const MIN_NOTA = 15;
  const ok = !!campo && nota.trim().length >= MIN_NOTA && valOk;
  const [salirConf, setSalirConf] = React.useState(false);
  const sucio = !!campo || nota.trim().length > 0;
  const cerrar = () => sucio ? setSalirConf(true) : onDismiss();
  const lab = (t) => <div style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: '0.06em', color: TOKENS.textMuted, textTransform: 'uppercase', margin: '14px 0 6px' }}>{t}</div>;
  const inp = { width: '100%', boxSizing: 'border-box', border: `1px solid ${TOKENS.borderInput}`, background: TOKENS.surfaceLow, borderRadius: 10, padding: '9px 10px', fontFamily: 'inherit', fontSize: 14, color: TOKENS.text, outline: 'none' };
  const req = <span style={{ color: TOKENS.danger }}>*</span>;
  return ReactDOM.createPortal(
    <div onClick={cerrar} style={{ position: 'fixed', inset: 0, background: 'rgba(11,28,48,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: 16 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: TOKENS.surface, borderRadius: 16, padding: '20px 18px', width: '100%', maxWidth: 360, maxHeight: '90vh', overflow: 'auto', boxShadow: '0 20px 60px rgba(11,28,48,0.3)' }}>
        <div style={{ fontSize: 17, fontWeight: 700 }}>Pedir corrección</div>
        <div style={{ marginTop: 10 }}><CabeceraPlaca ticket={{ ...entrega, id: entrega.ticketId }} /></div>
        {lab(<>¿Qué hay que corregir? {req}</>)}
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          {MOTIVOS_CORRECCION.map((m) =>
          <button key={m} type="button" onClick={() => setCampo(m)} style={{
            border: `1px solid ${campo === m ? TOKENS.primary : TOKENS.borderInput}`, background: campo === m ? TOKENS.primary : TOKENS.surface,
            color: campo === m ? '#fff' : TOKENS.text, borderRadius: 999, padding: '6px 11px', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 600, cursor: 'pointer'
          }}>{m}</button>)}
        </div>
        {campo === 'Placa' && <>{lab(<>Placa correcta {req}</>)}<input value={placa} onChange={(e) => setPlaca(e.target.value.toUpperCase())} placeholder={entrega.placa} style={{ ...inp, fontFamily: "'JetBrains Mono', monospace", letterSpacing: '0.06em' }} /></>}
        {campo === 'Taller / sede' && <>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 14 }}>
            <div>
              <FieldLabel>Taller</FieldLabel>
              {tallerNuevo ?
              <TextInput value={taller} onChange={setTaller} placeholder="Como aparece en la orden" /> :
              <Select value={taller} options={window.catTallerOpciones ? window.catTallerOpciones() : []} placeholder="Seleccionar" searchable popWidth="calc(200% + 10px)"
              onChange={(v) => { const ss = window.catSedesDe ? window.catSedesDe(v) : []; setTaller(v); setSede(v === taller ? sede : ss.length === 1 ? ss[0] : ''); }}
              footer={(qq, cerrar) => <button type="button" onClick={() => { cerrar(); setTallerNuevo(true); setTaller(qq.trim().toUpperCase()); setSede(''); }} style={{ border: 0, borderTop: `1px solid ${TOKENS.border}`, background: 'none', marginTop: 4, padding: '10px 12px', width: '100%', textAlign: 'left', fontFamily: 'inherit', fontSize: 13, fontWeight: 700, color: TOKENS.primary, cursor: 'pointer' }}>¿No está? Solicitar taller nuevo</button>} />}
            </div>
            <div>
              <FieldLabel>Sede</FieldLabel>
              {tallerNuevo ?
              <TextInput value={sede} onChange={setSede} placeholder="Opcional" /> :
              <DisabledSelect value={sede} options={taller && window.catSedesDe ? window.catSedesDe(taller) : []} placeholder="Seleccionar" disabled={!taller} onChange={setSede} />}
            </div>
          </div>
          {tallerNuevo ?
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8, fontSize: 11.5, color: TOKENS.textMuted }}>
              <span style={{ fontSize: 10.5, fontWeight: 600, borderRadius: 999, padding: '2px 8px', background: '#fff2cc', color: '#7f6000', border: '1px solid #ecd98f', whiteSpace: 'nowrap' }}>Nuevo · por revisar</span>
              <span style={{ flex: 1 }}>Le llega al admin en Catálogos.</span>
              <button type="button" onClick={() => { setTallerNuevo(false); setTaller(entrega.taller || ''); setSede(entrega.sede || ''); }} style={{ border: 0, background: 'none', padding: 0, fontFamily: 'inherit', fontSize: 12, fontWeight: 700, color: TOKENS.primary, cursor: 'pointer' }}>Usar la lista</button>
            </div> :
          (taller !== entrega.taller || sede !== (entrega.sede || '')) && taller && <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 6 }}>Antes: {entrega.taller}{entrega.sede ? ' · ' + entrega.sede : ''} → {taller}{sede ? ' · ' + sede : ''}</div>}
        </>}
        {lab(<>Explica el cambio {req}</>)}
        <textarea value={nota} onChange={(e) => setNota(e.target.value)} placeholder="Cuéntale al administrador qué pasó" style={{ ...inp, minHeight: 70, resize: 'none', fontSize: 13.5 }} />
        <div style={{ fontSize: 11.5, textAlign: 'right', marginTop: 4, color: nota.trim().length >= MIN_NOTA ? TOKENS.successText : TOKENS.textSubtle }}>{nota.trim().length >= MIN_NOTA ? '✓' : `Mínimo ${MIN_NOTA} caracteres · ${nota.trim().length}/${MIN_NOTA}`}</div>
        <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 6 }}>El administrador la revisa y la aprueba o la rechaza. Nada cambia hasta que la apruebe.</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 16 }}>
          <Button variant="outline" full onClick={cerrar}>Cancelar</Button>
          <Button variant="primary" full disabled={!ok} onClick={() => {
            if (!ok) return;
            if (campo === 'Taller / sede' && tallerNuevo && window.catAgregarRevision) {
              const u = window.usuarioActual ? window.usuarioActual() : null;
              window.catAgregarRevision({ llega: nuevo.taller + (nuevo.sede ? ' · ' + nuevo.sede : ''), taller: nuevo.taller, sede: nuevo.sede, motivo: 'mens', por: u && u.usuario, porNombre: u && (u.nombre || u.usuario), placa: entrega.placa });
            }
            onEnviar({ campo, nuevo, nota });
          }}>Enviar solicitud</Button>
        </div>
      </div>
      {salirConf && <div onClick={(e) => e.stopPropagation()}><ConfirmActionModal tone="danger" icon={I.x(22, TOKENS.danger)} title="¿Descartar la solicitud?" message="Se pierde lo que escribiste. La entrega queda como está." confirmLabel="Descartar" cancelLabel="Seguir editando" onConfirm={onDismiss} onDismiss={() => setSalirConf(false)} /></div>}
    </div>, document.body);
}
// Rechazo con motivo obligatorio / aprobación (verde).
function DecisionCorreccionModal({ c, tipo, onDone, onDismiss }) {
  const [txt, setTxt] = React.useState('');
  const quienP = c.porNombre || 'el mensajero';
  if (tipo === 'aprobar') {
    return <ConfirmActionModal icon={I.check(24, TOKENS.primary)} tone="primary"
      title={c.nuevo ? '¿Aprobar y aplicar la corrección?' : '¿Aprobar la corrección?'}
      message={c.nuevo ? `Se cambia ${c.campo === 'Placa' ? `la placa a ${c.nuevo.placa}` : `el taller a ${c.nuevo.taller}${c.nuevo.sede ? ' · ' + c.nuevo.sede : ''}`}. Le avisamos a ${quienP}.` : `${c.campo}: haz el ajuste con "Editar registro". Le avisamos a ${quienP}.`}
      confirmLabel={c.nuevo ? 'Aprobar y aplicar' : 'Aprobar'} onConfirm={() => { responderCorreccion(c.id, { aprobar: true }); onDone && onDone(); }} onDismiss={onDismiss} />;
  }
  const ok = txt.trim().length > 0;
  return ReactDOM.createPortal(
    <div onClick={onDismiss} style={{ position: 'fixed', inset: 0, background: 'rgba(11,28,48,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1300, padding: 16 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: TOKENS.surface, borderRadius: 16, padding: '20px 18px', width: '100%', maxWidth: 360, textAlign: 'center' }}>
        <div style={{ width: 50, height: 50, borderRadius: 999, background: TOKENS.dangerBg, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 12px' }}>{I.x(22, TOKENS.danger)}</div>
        <div style={{ fontSize: 17, fontWeight: 700 }}>¿Rechazar la corrección?</div>
        <div style={{ fontSize: 13, color: TOKENS.textMuted, lineHeight: 1.45, marginTop: 6 }}>La entrega queda como está. Cuéntale a {quienP} por qué.</div>
        <textarea value={txt} onChange={(e) => setTxt(e.target.value)} autoFocus placeholder="Por qué no se corrige (obligatorio)" style={{
          width: '100%', boxSizing: 'border-box', minHeight: 70, resize: 'none', marginTop: 12, border: `1px solid ${TOKENS.borderInput}`, background: TOKENS.surfaceLow,
          borderRadius: 10, padding: '9px 10px', fontFamily: 'inherit', fontSize: 13.5, color: TOKENS.text, outline: 'none', textAlign: 'left'
        }} />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 14 }}>
          <Button variant="outline" full onClick={onDismiss}>Cancelar</Button>
          <Button variant="primary" full disabled={!ok} onClick={() => { if (!ok) return; responderCorreccion(c.id, { aprobar: false, respuesta: txt.trim() }); onDone && onDone(); }} style={ok ? { background: TOKENS.danger, borderColor: TOKENS.danger } : {}}>Rechazar</Button>
        </div>
      </div>
    </div>, document.body);
}
// Caja en la ficha de la entrega. Admin: decide. Mensajero: ve el estado y puede retirarla.
function CorreccionBox({ ticketId, admin }) {
  const [, refrescar] = React.useState(0);
  const [tipo, setTipo] = React.useState(null);
  React.useEffect(() => { const r = () => refrescar((n) => n + 1); window.addEventListener('rodando-anulaciones', r); return () => window.removeEventListener('rodando-anulaciones', r); }, []);
  const l = correccionesDe(ticketId).filter((x) => x.estado !== 'retirada');
  const c = l[0];
  if (!c) return null;
  const P = window.PAUSA_COLOR || { bg: '#fdf0d5', fg: '#8a5a00', bd: '#f1d49b' };
  const caja = { marginTop: 12, borderRadius: 12, padding: 12, fontSize: 12.5, lineHeight: 1.5 };
  if (c.estado !== 'espera') {
    if (admin) return null; // el admin lo ve en el historial
    return <div style={{ ...caja, background: TOKENS.surfaceLow, color: TOKENS.textMuted, border: `1px solid ${TOKENS.border}` }}>
      <b style={{ display: 'block', fontSize: 13.5, color: TOKENS.text, marginBottom: 2 }}>Corrección {c.estado === 'aprobada' ? 'aprobada' : 'rechazada'} · {c.campo}</b>
      {c.respuesta ? `${c.respondidoPorNombre || 'Admin'}: "${c.respuesta}"` : `${c.respondidoPorNombre || 'Admin'} la aprobó.`}
    </div>;
  }
  return (
    <div style={{ ...caja, background: TOKENS.surface, border: `1px solid ${P.bd}` }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}><ChipCorreccion /><span style={{ fontSize: 11.5, color: TOKENS.textMuted }}>{c.porNombre || 'Mensajero'} · {String(c.fecha || '').replace(/\s/g, '')} {window.formatHora12 ? window.formatHora12(c.hora) : c.hora}</span></div>
      <b style={{ display: 'block', fontSize: 13.5, color: TOKENS.text, marginTop: 8 }}>{c.campo}</b>
      <div style={{ color: TOKENS.textMuted }}>"{c.nota}"</div>
      <CorreccionDiff c={c} />
      {admin ?
      <div style={{ display: 'flex', gap: 8, marginTop: 11 }}>
          <Button variant="outline" full onClick={() => setTipo('rechazar')} style={{ color: TOKENS.danger, borderColor: TOKENS.borderInput, borderWidth: 1.5, padding: 10 }}>Rechazar</Button>
          <Button variant="primary" full onClick={() => setTipo('aprobar')} style={{ background: TOKENS.success, borderColor: TOKENS.success, padding: 10 }}>{c.nuevo ? 'Aprobar y aplicar' : 'Aprobar'}</Button>
        </div> :
      <button type="button" onClick={() => retirarCorreccion(c.id)} style={{ marginTop: 8, background: 'none', border: 0, padding: 0, color: TOKENS.textMuted, fontFamily: 'inherit', fontSize: 12.5, fontWeight: 600, textDecoration: 'underline', cursor: 'pointer' }}>Retirar solicitud</button>}
      {tipo && <DecisionCorreccionModal c={c} tipo={tipo} onDone={() => { setTipo(null); refrescar((n) => n + 1); }} onDismiss={() => setTipo(null)} />}
    </div>);
}

// ─── Admin: decidir una solicitud de anulación (13/11/2026) ─────────────
// Rechazar pide el porqué (obligatorio, le llega al mensajero). Anular pide confirmar (rojo).
function DecisionAnulacionModal({ solicitudId, tipo, onDone, onDismiss }) {
  const sol = loadSolicitudesAnulacion().find((x) => x.id === solicitudId);
  const [txt, setTxt] = React.useState('');
  if (!sol) return null;
  const quien = sol.porNombre || 'el mensajero';
  if (tipo === 'anular') {
    return <ConfirmActionModal icon={I.ban(24, TOKENS.danger)} tone="danger"
      title={`¿Anular el registro ${sol.codigo}?`}
      message={`${sol.placa} sale de pendientes y pasa a Anulados. Le avisamos a ${quien}. Para devolverla habría que reactivarla.`}
      confirmLabel="Anular" onConfirm={() => {responderSolicitudAnulacion(sol.id, { aceptar: true, respuesta: '' });onDone && onDone();}} onDismiss={onDismiss} />;
  }
  const ok = txt.trim().length > 0;
  return ReactDOM.createPortal(
    <div onClick={onDismiss} style={{ position: 'fixed', inset: 0, background: 'rgba(11,28,48,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1300, padding: 16 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: TOKENS.surface, borderRadius: 16, padding: '20px 18px', width: '100%', maxWidth: 360, textAlign: 'center' }}>
        <div style={{ width: 50, height: 50, borderRadius: 999, background: TOKENS.surfaceLow, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 12px' }}>{I.x(22, TOKENS.textMuted)}</div>
        <div style={{ fontSize: 17, fontWeight: 700 }}>¿Rechazar la anulación?</div>
        <div style={{ fontSize: 13, color: TOKENS.textMuted, lineHeight: 1.45, marginTop: 6 }}>{sol.placa} sigue pendiente por entregar. Cuéntale a {quien} por qué.</div>
        <textarea value={txt} onChange={(e) => setTxt(e.target.value)} autoFocus placeholder="Por qué no se anula (obligatorio)" style={{
          width: '100%', boxSizing: 'border-box', minHeight: 70, resize: 'none', marginTop: 12, border: `1px solid ${TOKENS.borderInput}`, background: TOKENS.surfaceLow,
          borderRadius: 10, padding: '9px 10px', fontFamily: 'inherit', fontSize: 13.5, color: TOKENS.text, outline: 'none', textAlign: 'left'
        }} />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 14 }}>
          <button type="button" onClick={onDismiss} style={{ padding: 12, borderRadius: 10, fontSize: 14, fontWeight: 700, background: TOKENS.surface, color: TOKENS.text, border: `1px solid ${TOKENS.border}`, cursor: 'pointer', fontFamily: 'inherit' }}>Cancelar</button>
          <button type="button" disabled={!ok} onClick={() => {if (!ok) return;responderSolicitudAnulacion(sol.id, { aceptar: false, respuesta: txt.trim() });onDone && onDone();}} style={{ padding: 12, borderRadius: 10, fontSize: 14, fontWeight: 700, background: TOKENS.primary, color: '#fff', border: 'none', cursor: ok ? 'pointer' : 'not-allowed', opacity: ok ? 1 : 0.45, fontFamily: 'inherit' }}>Rechazar</button>
        </div>
      </div>
    </div>, document.body);
}
// Cuadro de la solicitud en el resumen del admin, con las dos decisiones.
function SolicitudAnulacionAdminBox({ ticket }) {
  const [, refrescar] = React.useState(0);
  const [tipo, setTipo] = React.useState(null);
  React.useEffect(() => {const r = () => refrescar((n) => n + 1);window.addEventListener('rodando-anulaciones', r);return () => window.removeEventListener('rodando-anulaciones', r);}, []);
  const sol = solicitudAnulacionFor(ticket.id);
  if (!sol || sol.estado === 'aceptada') return null;
  const caja = { marginBottom: 14, borderRadius: 12, padding: 12, fontSize: 12.5, lineHeight: 1.5 };
  if (sol.estado === 'rechazada') {
    return <div style={{ ...caja, background: TOKENS.surfaceLow, color: TOKENS.textMuted, border: `1px solid ${TOKENS.border}` }}>
        <b style={{ display: 'block', fontSize: 13.5, color: TOKENS.text, marginBottom: 2 }}>Anulación rechazada</b>
        {sol.respondidoPorNombre || 'Admin'}: "{sol.respuesta}"
      </div>;
  }
  return (
    <div style={{ ...caja, background: TOKENS.anuladoBg, color: TOKENS.anuladoText, border: '1px solid ' + TOKENS.anuladoBorder }}>
      <b style={{ display: 'block', fontSize: 13.5, marginBottom: 3 }}>⏳ {sol.porNombre || 'El mensajero'} pidió anular este registro</b>
      Motivo: {sol.motivo}{sol.nota ? ` · "${sol.nota}"` : ''}
      <div style={{ display: 'flex', gap: 8, marginTop: 11 }}>
        <button type="button" onClick={() => setTipo('rechazar')} style={{ flex: 1, padding: 10, borderRadius: 10, fontFamily: 'inherit', fontSize: 13.5, fontWeight: 800, cursor: 'pointer', background: '#fff', border: `1px solid ${TOKENS.borderInput}`, color: TOKENS.text }}>Rechazar</button>
        <button type="button" onClick={() => setTipo('anular')} style={{ flex: 1, padding: 10, borderRadius: 10, fontFamily: 'inherit', fontSize: 13.5, fontWeight: 800, cursor: 'pointer', background: TOKENS.danger, border: 'none', color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 5 }}>{I.ban(15, '#fff')} Anular registro</button>
      </div>
      {tipo && <DecisionAnulacionModal solicitudId={sol.id} tipo={tipo} onDone={() => {setTipo(null);refrescar((n) => n + 1);}} onDismiss={() => setTipo(null)} />}
    </div>);
}

// Historial del registro (13/11/2026, Resumen del admin): recogido → entregado / anulado → reactivado.
function HistorialRegistro({ ticket, entrega }) {
  const f12 = (h) => h ? (window.formatHora12 ? window.formatHora12(h) : h) : '';
  const fx = (f) => String(f || '').replace(/\s/g, '');
  const ev = [];
  const rec = entrega || ticket || {};
  ev.push({ ic: I.recoger, t: 'Recogido', w: [rec.recogidoPorNombre, [fx(rec.fechaRecogido || rec.fecha), f12(rec.horaRecogida)].filter(Boolean).join(' · ')].filter(Boolean).join(' · ') });
  const id = (ticket && ticket.id) || (entrega && entrega.ticketId);
  const anu = id ? anulacionFor(id) : null;
  const sols = id ? loadSolicitudesAnulacion().filter((x) => x.ticketId === id) : [];
  (anu && anu.historial || []).forEach((e) => {
    const sol = e.tipo === 'anulado' ? sols.find((x) => x.estado === 'aceptada') : null;
    ev.push({ ic: e.tipo === 'anulado' ? I.ban : I.reactivar, anu: e.tipo === 'anulado', t: e.tipo === 'anulado' ? 'Anulado' : 'Reactivado',
      w: [e.por, [fx(e.fecha), f12(e.hora)].filter(Boolean).join(' · ')].filter(Boolean).join(' · '),
      extra: e.tipo === 'anulado' ? [e.motivo, e.nota ? `"${e.nota}"` : '', sol && sol.porNombre ? 'pidió ' + sol.porNombre : ''].filter(Boolean).join(' · ') : '' });
  });
  sols.filter((x) => x.estado === 'rechazada').forEach((x) => ev.push({ ic: I.x, t: 'Anulación rechazada', w: [x.respondidoPorNombre, 'pidió ' + (x.porNombre || 'el mensajero')].filter(Boolean).join(' · '), extra: x.respuesta ? `"${x.respuesta}"` : '' }));
  if (entrega) ev.push({ ic: I.check, t: 'Entregado', w: [entrega.entregadoPorNombre, [fx(entrega.fechaEntrega), f12(entrega.horaEntrega)].filter(Boolean).join(' · ')].filter(Boolean).join(' · '),
    extra: entrega.despachado ? `Transportadora ${entrega.transportadora || ''}`.trim() : entrega.factura ? `${entrega.comprobanteTipo || 'Factura'} ${entrega.factura}` : '' });
  // Garantías (18/11/2026): registrada y entregada, con el ↺ en cian.
  (window.garantiasDe && id ? window.garantiasDe(id) : []).forEach((g) => {
    ev.push({ ic: I.reactivar, gar: true, t: `Garantía · ${(g.rines || []).map((i) => 'rin ' + (i + 1)).join(', ')}`, w: [g.porNombre, [fx(g.fecha), f12(g.hora)].filter(Boolean).join(' · ')].filter(Boolean).join(' · '), extra: [g.motivo, g.desc && `"${g.desc}"`].filter(Boolean).join(' · ') });
    if (g.estado === 'entregada' && g.entrega) ev.push({ ic: I.check, gar: true, t: 'Garantía entregada', w: [g.entrega.porNombre, [fx(g.entrega.fecha), f12(g.entrega.hora)].filter(Boolean).join(' · ')].filter(Boolean).join(' · ') });
  });
  correccionesDe(id).filter((x) => x.estado !== 'retirada').forEach((x) => ev.push({ ic: I.pencil, t: x.estado === 'espera' ? `Corrección pedida · ${x.campo}` : `Corrección ${x.estado} · ${x.campo}`,
    w: [x.porNombre, [x.fecha, f12(x.hora)].filter(Boolean).join(' · '), x.respondidoPorNombre && 'respondió ' + x.respondidoPorNombre].filter(Boolean).join(' · '),
    extra: [x.nota && `"${x.nota}"`, x.nuevo && (x.nuevo.placa ? `${x.antes && x.antes.placa} → ${x.nuevo.placa}` : `${x.antes && x.antes.taller} → ${x.nuevo.taller}`), x.respuesta && `Respuesta: "${x.respuesta}"`].filter(Boolean).join(' · ') }));
  return (
    <Card style={{ marginTop: 12, padding: '14px 14px', background: TOKENS.surface }}>
      <div style={{ fontSize: 15, fontWeight: 700, color: TOKENS.text, marginBottom: 8 }}>Historial</div>
      {ev.map((e, i) =>
      <div key={i} style={{ display: 'flex', gap: 10, position: 'relative', paddingBottom: i < ev.length - 1 ? 12 : 0 }}>
          {i < ev.length - 1 && <span style={{ position: 'absolute', left: 11, top: 24, bottom: 0, width: 2, background: TOKENS.border }} />}
          <span style={{ width: 24, height: 24, flexShrink: 0, borderRadius: 999, display: 'flex', alignItems: 'center', justifyContent: 'center',
          background: e.anu ? TOKENS.anuladoBg : e.gar ? '#e6f7fa' : TOKENS.surfaceLow, border: `1px solid ${e.anu ? TOKENS.anuladoBorder : e.gar ? '#b3e3ec' : TOKENS.border}` }}>{e.ic ? e.ic(12, e.anu ? TOKENS.anulado : e.gar ? '#0e7490' : TOKENS.textMuted) : null}</span>
          <div style={{ fontSize: 12.5, lineHeight: 1.4, minWidth: 0 }}>
            <b style={{ display: 'block', fontSize: 13 }}>{e.t}</b>
            <span style={{ color: TOKENS.textMuted }}>{e.w}</span>
            {e.extra && <div style={{ fontWeight: 600, color: e.anu ? TOKENS.anuladoText : TOKENS.textMuted }}>{e.extra}</div>}
          </div>
        </div>
      )}
    </Card>);
}
// Botones del administrador al final del resumen (regla de color: azul acción · amarillo modificar · rojo eliminar).
function AccionesAdmin({ onEditar, onAnular, onReactivar, notaEditar }) {
  if (!onEditar && !onAnular && !onReactivar) return null;
  const b = (label, icon, color, border, fn, solid) =>
  <Button variant={solid ? 'primary' : 'outline'} full icon={icon} onClick={fn} style={solid ? { padding: '13px', fontSize: 15 } : { padding: '13px', fontSize: 15, color, borderColor: border, borderWidth: border === TOKENS.borderInput ? 1.5 : 1, background: TOKENS.surface }}>{label}</Button>;
  return (
    <div style={{ display: 'grid', gap: 8, marginTop: 16 }}>
      <div style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: '0.06em', color: TOKENS.textMuted, textTransform: 'uppercase', margin: '0 2px' }}>Administrador</div>
      {notaEditar && onEditar && <div style={{ fontSize: 11.5, color: TOKENS.textMuted, lineHeight: 1.4, margin: '0 2px' }}>{notaEditar}</div>}
      {onReactivar && b('Reactivar registro', I.reactivar(16, '#fff'), null, null, onReactivar, true)}
      {onEditar && <Button variant="outline" full icon={I.pencil(16, TOKENS.primary)} onClick={onEditar} style={{ padding: '13px', fontSize: 15, color: TOKENS.primary }}>Editar registro</Button>}
      {onAnular && b('Anular registro', I.ban(16, TOKENS.danger), TOKENS.danger, TOKENS.borderInput, onAnular)}
    </div>);
}

const cajaAnu = { marginTop: 12, borderRadius: 12, padding: '11px 12px', fontSize: 12.5, lineHeight: 1.5, background: TOKENS.anuladoBg, color: TOKENS.anuladoText, border: '1px solid ' + TOKENS.anuladoBorder };

// Pedir la anulación de un registro: motivo obligatorio, nota obligatoria si el motivo es "Otro".
function SolicitarAnulacionModal({ ticket, onEnviar, onDismiss }) {
  const [motivo, setMotivo] = React.useState(null);
  const [nota, setNota] = React.useState('');
  const ok = !!motivo && (motivo !== 'Otro' || nota.trim().length > 0);
  const lab = (t) => <div style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: '0.06em', color: TOKENS.textMuted, textTransform: 'uppercase', margin: '14px 0 6px' }}>{t}</div>;
  return ReactDOM.createPortal(
    <div onClick={onDismiss} style={{ position: 'fixed', inset: 0, background: 'rgba(11,28,48,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: 16 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: TOKENS.surface, borderRadius: 16, padding: '20px 18px', width: '100%', maxWidth: 360, boxShadow: '0 20px 60px rgba(11,28,48,0.3)' }}>
        <div style={{ width: 50, height: 50, borderRadius: 999, background: TOKENS.dangerBg, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 12px' }}>{I.ban(24, TOKENS.danger)}</div>
        <div style={{ fontSize: 17, fontWeight: 700, textAlign: 'center' }}>Solicitar anulación de {ticket.placa}</div>
        <div style={{ fontSize: 13, color: TOKENS.textMuted, textAlign: 'center', lineHeight: 1.45, marginTop: 6 }}>La solicitud le llega al administrador. Él la acepta o la rechaza y te explica por qué.</div>
        {lab(<>Motivo <span style={{ color: TOKENS.danger }}>*</span></>)}
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          {MOTIVOS_ANULACION.map((m) =>
          <button key={m} type="button" onClick={() => setMotivo(m)} style={{
            border: `1px solid ${motivo === m ? TOKENS.primary : TOKENS.borderInput}`, background: motivo === m ? TOKENS.primary : TOKENS.surface,
            color: motivo === m ? '#fff' : TOKENS.text, borderRadius: 999, padding: '6px 11px', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 700, cursor: 'pointer'
          }}>{m}</button>
          )}
        </div>
        {lab(<>Nota {motivo === 'Otro' ? <span style={{ color: TOKENS.danger }}>*</span> : <span style={{ textTransform: 'none', letterSpacing: 0, fontWeight: 600, color: TOKENS.textSubtle }}>(opcional)</span>}</>)}
        <textarea value={nota} onChange={(e) => setNota(e.target.value)} placeholder="Cuéntale al administrador qué pasó" style={{
          width: '100%', boxSizing: 'border-box', minHeight: 64, resize: 'none', border: `1px solid ${TOKENS.borderInput}`, background: TOKENS.surfaceLow,
          borderRadius: 10, padding: '9px 10px', fontFamily: 'inherit', fontSize: 13.5, color: TOKENS.text, outline: 'none'
        }} />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 16 }}>
          <button type="button" onClick={onDismiss} style={{ padding: 12, borderRadius: 10, fontSize: 14, fontWeight: 700, background: TOKENS.surface, color: TOKENS.text, border: `1px solid ${TOKENS.border}`, cursor: 'pointer', fontFamily: 'inherit' }}>Cancelar</button>
          <button type="button" disabled={!ok} onClick={() => ok && onEnviar({ motivo, nota })} style={{ padding: 12, borderRadius: 10, fontSize: 14, fontWeight: 700, background: ok ? TOKENS.danger : '#d9b3ad', color: '#fff', border: 'none', cursor: ok ? 'pointer' : 'not-allowed', fontFamily: 'inherit' }}>Enviar solicitud</button>
        </div>
      </div>
    </div>, document.body);
}

// Visor de fotos (18/11/2026): anterior / siguiente con flechas, deslizando o con el teclado.
// `src` puede ser una foto suelta o { src, list } para navegar dentro de un grupo.
function FotoGrande({ src, fotos, onClose }) {
  const lista = (src && src.list) || fotos || [src && src.src ? src.src : src];
  const [i, setI] = React.useState(() => Math.max(0, lista.indexOf(src && src.src ? src.src : src)));
  const n = lista.length;
  const ir = (d) => setI((x) => (x + d + n) % n);
  const x0 = React.useRef(null);
  React.useEffect(() => {
    const k = (e) => { if (e.key === 'Escape') onClose(); else if (e.key === 'ArrowRight' && n > 1) ir(1); else if (e.key === 'ArrowLeft' && n > 1) ir(-1); };
    window.addEventListener('keydown', k); return () => window.removeEventListener('keydown', k);
  }, [n]);
  const flecha = (d) => <button type="button" aria-label={d < 0 ? 'Foto anterior' : 'Foto siguiente'} onClick={(e) => { e.stopPropagation(); ir(d); }} style={{ position: 'absolute', top: '50%', [d < 0 ? 'left' : 'right']: 10, transform: 'translateY(-50%)', width: 42, height: 42, borderRadius: 999, border: 'none', background: 'rgba(255,255,255,.9)', fontSize: 22, fontWeight: 700, color: '#16233f', cursor: 'pointer' }}>{d < 0 ? '‹' : '›'}</button>;
  return ReactDOM.createPortal(
    <div onClick={onClose} onTouchStart={(e) => { x0.current = e.touches[0].clientX; }} onTouchEnd={(e) => { if (x0.current == null || n < 2) return; const dx = e.changedTouches[0].clientX - x0.current; x0.current = null; if (Math.abs(dx) > 40) { e.stopPropagation(); ir(dx < 0 ? 1 : -1); } }}
    style={{ position: 'fixed', inset: 0, zIndex: 1000, background: 'rgba(11,28,48,0.92)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }}>
      <img src={lista[i]} alt={`Foto ${i + 1}`} onClick={(e) => e.stopPropagation()} style={{ maxWidth: '100%', maxHeight: '100%', borderRadius: 12 }} />
      <button aria-label="Cerrar" onClick={onClose} style={{ position: 'absolute', top: 16, right: 16, width: 36, height: 36, borderRadius: 999, border: 'none', background: 'rgba(255,255,255,.9)', fontSize: 18, cursor: 'pointer' }}>×</button>
      {n > 1 && <>{flecha(-1)}{flecha(1)}<div style={{ position: 'absolute', bottom: 18, left: 0, right: 0, textAlign: 'center', color: '#fff', fontSize: 13, fontWeight: 600 }}>{i + 1} / {n}</div></>}
    </div>, document.body);
}

// ─── Cámara en modo documento (13/11/2026) ──────────────────────────────
// Vista en vivo con un marco para encuadrar el papel completo. Si el navegador no
// deja abrir la cámara aquí, se usa la cámara del celular (selector de archivo).
function DocCamera({ titulo, onCapture, onClose }) {
  const videoRef = React.useRef(null);
  const [estado, setEstado] = React.useState('cargando'); // 'cargando' | 'vivo' | 'sin'
  React.useEffect(() => {
    let stream = null;let activo = true;
    const md = navigator.mediaDevices;
    if (!md || !md.getUserMedia) {setEstado('sin');return;}
    md.getUserMedia({ video: { facingMode: { ideal: 'environment' }, width: { ideal: 1920 }, height: { ideal: 1440 } }, audio: false }).
    then((s) => {
      if (!activo) {s.getTracks().forEach((t) => t.stop());return;}
      stream = s;
      const v = videoRef.current;
      if (v) {v.srcObject = s;v.play().catch(() => {});}
      setEstado('vivo');
    }).
    catch(() => setEstado('sin'));
    return () => {activo = false;if (stream) stream.getTracks().forEach((t) => t.stop());};
  }, []);
  const disparar = () => {
    const v = videoRef.current;
    if (!v || !v.videoWidth) return;
    const c = document.createElement('canvas');
    c.width = v.videoWidth;c.height = v.videoHeight;
    c.getContext('2d').drawImage(v, 0, 0);
    onCapture(c.toDataURL('image/jpeg', 0.92));
  };
  const desdeArchivo = (f) => {
    if (!f) return;
    const r = new FileReader();
    r.onload = () => onCapture(r.result);
    r.readAsDataURL(f);
  };
  const esquina = (pos) => ({ position: 'absolute', width: 22, height: 22, borderColor: '#7fd1a0', borderStyle: 'solid', ...pos });
  const archivo = (contenido, estilo) =>
  <label style={{ cursor: 'pointer', display: 'block', ...estilo }}>
      <input type="file" accept="image/*" capture="environment" style={{ display: 'none' }}
    onChange={(e) => {const f = e.target.files && e.target.files[0];e.target.value = '';desdeArchivo(f);}} />
      {contenido}
    </label>;
  return ReactDOM.createPortal(
    <div style={{ position: 'fixed', inset: 0, zIndex: 1100, background: '#0d121c', display: 'flex', flexDirection: 'column', fontFamily: 'inherit' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', color: '#fff', padding: '14px 16px', fontSize: 13.5, fontWeight: 700 }}>
        <span>{titulo}</span>
        <button type="button" onClick={onClose} style={{ border: 0, background: 'rgba(255,255,255,.14)', color: '#fff', borderRadius: 999, padding: '7px 13px', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 700, cursor: 'pointer' }}>Cerrar</button>
      </div>
      <div style={{ flex: 1, position: 'relative', overflow: 'hidden', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <video ref={videoRef} playsInline muted style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', display: estado === 'vivo' ? 'block' : 'none' }} />
        {estado !== 'sin' ?
        <div style={{ position: 'relative', width: '74%', maxWidth: 420, aspectRatio: '3 / 4', border: '2px dashed rgba(255,255,255,.85)', borderRadius: 8, boxShadow: '0 0 0 2000px rgba(0,0,0,.35)' }}>
            <span style={esquina({ top: -3, left: -3, borderWidth: '4px 0 0 4px' })} />
            <span style={esquina({ top: -3, right: -3, borderWidth: '4px 4px 0 0' })} />
            <span style={esquina({ bottom: -3, left: -3, borderWidth: '0 0 4px 4px' })} />
            <span style={esquina({ bottom: -3, right: -3, borderWidth: '0 4px 4px 0' })} />
          </div> :
        <div style={{ color: '#dfe7f4', textAlign: 'center', padding: 24, fontSize: 14, lineHeight: 1.5 }}>
            <div>No se pudo abrir la cámara aquí.<br />Usa la cámara del celular.</div>
            <div />{archivo(<span style={{ display: 'inline-block', marginTop: 16, background: '#fff', color: TOKENS.primary, borderRadius: 12, padding: '12px 18px', fontWeight: 800 }}>Abrir cámara</span>)}
          </div>
        }
      </div>
      <div style={{ color: '#dfe7f4', textAlign: 'center', fontSize: 13, padding: '10px 24px 6px', lineHeight: 1.4 }}>
        Pon el papel sobre una superficie plana y encuádralo completo dentro del marco. Sin flash.
      </div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 26px 26px' }}>
        <span style={{ width: 80 }} />
        <button type="button" aria-label="Tomar foto" onClick={disparar} disabled={estado !== 'vivo'} style={{
          width: 70, height: 70, borderRadius: 999, border: '4px solid #fff', background: 'rgba(255,255,255,.25)',
          cursor: estado === 'vivo' ? 'pointer' : 'not-allowed', opacity: estado === 'vivo' ? 1 : 0.35
        }} />
        {archivo(<span style={{ display: 'block', width: 80, color: '#c9d6ee', fontSize: 11.5, fontWeight: 700, textAlign: 'right', lineHeight: 1.3 }}>Usar cámara del celular</span>)}
      </div>
    </div>, document.body);
}

// Hojas de un comprobante: vista previa vertical, número de hoja, ✕ para quitar y "Otra hoja".
function HojasComprobante({ fotos, max, onAgregar, onVer, onQuitar }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
      {fotos.map((src, i) =>
      <div key={i} style={{ position: 'relative', aspectRatio: '3 / 4' }}>
          <img src={src} alt={`Hoja ${i + 1}`} onClick={() => onVer(i)} style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: 9, border: `1px solid ${TOKENS.border}`, display: 'block', cursor: 'zoom-in' }} />
          <span style={{ position: 'absolute', left: 5, bottom: 5, background: 'rgba(22,35,63,.82)', color: '#fff', fontSize: 10, fontWeight: 800, borderRadius: 6, padding: '2px 6px' }}>Hoja {i + 1}</span>
          <button type="button" aria-label={`Quitar hoja ${i + 1}`} onClick={() => onQuitar(i)} style={{
          position: 'absolute', top: -6, right: -6, width: 22, height: 22, borderRadius: 999, border: 'none',
          background: '#1b2333', color: '#fff', fontSize: 12, cursor: 'pointer', display: 'grid', placeItems: 'center', padding: 0
        }}>×</button>
        </div>
      )}
      {fotos.length < max &&
      <button type="button" onClick={onAgregar} style={{
        aspectRatio: '3 / 4', border: `1.5px dashed ${TOKENS.borderInput}`, background: TOKENS.surface, borderRadius: 9,
        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 2,
        color: TOKENS.primary, fontFamily: 'inherit', fontWeight: 800, fontSize: 12, cursor: 'pointer'
      }}>
          <span style={{ fontSize: 22, lineHeight: 1 }}>＋</span>Otra hoja
        </button>
      }
    </div>);
}

// ─── Registrar entrega (rediseño 13/11/2026) ────────────────────────────
// En mano (Factura o Remisión + número + quién recibe + foto) o por transportadora
// (nombre + guía + foto de la guía). Fotos en modo documento, varias hojas, 1100 px al 70 %.
const MAX_HOJAS = 5,MAX_HOJAS_GUIA = 3;
function EntregaConfirmScreen({ ticket, onBack, onSaved }) {
  // 25/11/2026: sede en una ciudad donde el mensajero no recoge → por transportadora (César la lleva).
  const [modo, setModo] = React.useState(() => ticket && window.catMensajeroRecoge && !window.catMensajeroRecoge(ticket.taller, ticket.sede) ? 'transportadora' : 'mano'); // 'mano' | 'transportadora'
  const [doc, setDoc] = React.useState('Factura'); // 'Factura' | 'Remisión'
  const [numero, setNumero] = React.useState('');
  const [recibePor, setRecibePor] = React.useState(() => (ticket.cliente && ticket.cliente.nombre) || '');
  const [hojas, setHojas] = React.useState([]);
  const [transportadora, setTransportadora] = React.useState('');
  const [guia, setGuia] = React.useState('');
  const [guiaFotos, setGuiaFotos] = React.useState([]);
  const [camara, setCamara] = React.useState(null); // 'hojas' | 'guia'
  const [verFoto, setVerFoto] = React.useState(null);
  const [quitar, setQuitar] = React.useState(null); // { k, i }
  const [confirmar, setConfirmar] = React.useState(false);
  // Garantía al entregar (16/11/2026): el taller devuelve rines en el momento.
  const [garOn, setGarOn] = React.useState(false);
  const [srV, setSrV] = React.useState(() => window.srDesdeServicios ? window.srDesdeServicios(ticket) : window.srVacio ? window.srVacio() : { on: false, rines: [] });
  const nRinesSr = window.servRinesDeItems ? window.servRinesDeItems(ticket.items).length : 0;
  const sumsE = window.suministrosDe ? window.suministrosDe(ticket.id) : [];
  const [garV, setGarV] = React.useState(() => window.garVacio ? window.garVacio() : { rines: [], motivo: '', desc: '', fotos: [] });
  const [garToc, setGarToc] = React.useState(false);
  const [garTk, setGarTk] = React.useState(null);
  const [descartar, setDescartar] = React.useState(false);
  const [ahora] = React.useState(() => new Date());
  const rootRef = React.useRef(null);

  // Al abrir esta pantalla, empezar arriba (no heredar el scroll anterior).
  React.useEffect(() => {
    let el = rootRef.current;
    while (el) {if (el.scrollTop > 0) el.scrollTop = 0;el = el.parentElement;}
    if (window.scrollTo) window.scrollTo(0, 0);
  }, []);

  const docMin = doc.toLowerCase();
  const enMano = modo === 'mano';
  const faltas = [...(enMano ?
  [numero.trim().length < 3 && `número de ${docMin}`, hojas.length === 0 && `foto de la ${docMin}`].filter(Boolean) :
  [transportadora.trim().length < 2 && 'transportadora', guiaFotos.length === 0 && 'foto de la guía'].filter(Boolean)),
  ...(garOn && enMano && window.garFaltas ? window.garFaltas(garV).map((x) => x + ' de la garantía') : []),
  ...(window.srFaltas ? window.srFaltas(srV) : [])];
  const dirty = !!(numero.trim() || recibePor.trim() || hojas.length || transportadora.trim() || guia.trim() || guiaFotos.length || garOn || srV.on || modo !== 'mano');

  const agregarFoto = async (dataUrl) => {
    const k = camara;
    setCamara(null);
    const small = window.downscaleDataURL ? await window.downscaleDataURL(dataUrl, 1100, 0.7) : dataUrl;
    if (k === 'guia') setGuiaFotos((l) => l.length < MAX_HOJAS_GUIA ? [...l, small] : l);else
    setHojas((l) => l.length < MAX_HOJAS ? [...l, small] : l);
  };

  const guardar = () => {
    const entry = markTicketDelivered(ticket, enMano ?
    { factura: docGuardar(doc, numero), comprobanteTipo: doc, fotos: hojas, recibePor: recibePor.trim(), despacho: null, sinReparar: window.srLista ? window.srLista(srV) : [] } :
    { factura: '', comprobanteTipo: '', fotos: [], recibePor: '', despacho: { despachado: true, transportadora: transportadora.trim(), guia: guia.trim(), guiaFotos }, sinReparar: window.srLista ? window.srLista(srV) : [] });
    if (garOn && enMano && window.crearGarantia) { const g = window.crearGarantia(ticket.id, garV); setGarTk({ g, entry }); return; }
    onSaved && onSaved(entry);
  };
  const salir = () => dirty ? setDescartar(true) : onBack && onBack();

  const fechaTxt = fechaDDMMYYYY(ahora).replace(/\s/g, '');
  const horaTxt = window.formatHora12 ? window.formatHora12(`${String(ahora.getHours()).padStart(2, '0')}:${String(ahora.getMinutes()).padStart(2, '0')}`) : '';
  const titulo = (txt, extra) =>
  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', margin: '16px 2px 8px' }}>
      <span style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: '0.06em', color: TOKENS.textMuted, textTransform: 'uppercase' }}>{txt}</span>
      {extra && <span style={{ fontSize: 11.5, fontWeight: 700, color: TOKENS.textSubtle }}>{extra}</span>}
    </div>;
  const campo = (label, req, input) =>
  <div style={{ marginTop: 10 }}>
      <div style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: '0.06em', color: TOKENS.textMuted, textTransform: 'uppercase', marginBottom: 5 }}>
        {label} {req ? <span style={{ color: TOKENS.danger }}>*</span> : <span style={{ textTransform: 'none', letterSpacing: 0, fontWeight: 600, color: TOKENS.textSubtle }}>(opcional)</span>}
      </div>
      {input}
    </div>;
  const inp = (value, onChange, placeholder, mono) =>
  <input value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} style={{
    width: '100%', boxSizing: 'border-box', border: `1px solid ${TOKENS.borderInput}`, background: TOKENS.surfaceLow,
    borderRadius: 10, padding: '10px 11px', fontFamily: mono ? "'JetBrains Mono', monospace" : 'inherit',
    fontSize: 14.5, fontWeight: 600, color: TOKENS.text, outline: 'none'
  }} />;
  const modoBtn = (id, icon, label) => <ModoEntregaTile on={modo === id} icon={id === 'mano' ? I.check : icon} titulo={label} sub={id === 'mano' ? 'Factura o remisión' : 'Guía del envío'} onClick={() => setModo(id)} />;

  const capturaGrande = (label, sub) =>
  <button type="button" onClick={() => setCamara(enMano ? 'hojas' : 'guia')} style={{
    width: '100%', height: 150, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 5,
    border: `1.5px dashed ${TOKENS.primary}`, background: TOKENS.primaryBg, color: TOKENS.primary, borderRadius: 14,
    fontFamily: 'inherit', cursor: 'pointer'
  }}>
      {I.doc(30, TOKENS.primary)}
      <span style={{ fontSize: 15, fontWeight: 800 }}>{label}</span>
      <span style={{ fontSize: 12, fontWeight: 600, color: TOKENS.textMuted }}>{sub}</span>
    </button>;
  const fotosActuales = enMano ? hojas : guiaFotos;

  return (
    <div ref={rootRef} style={{ background: TOKENS.bg, display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
      <AppHeader title="Registrar entrega" onBack={salir} hideRuta />
      <div style={{ padding: '14px 16px 24px', flex: 1 }}>

        {/* Placa que se entrega + fecha y hora en una línea pequeña */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10, background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 12, padding: '10px 12px' }}>
          <div style={{ minWidth: 0 }}>
            <CabeceraPlaca ticket={ticket} />
            <div style={{ fontSize: 12, color: TOKENS.textMuted, fontWeight: 600, marginTop: 8 }}>{ticket.taller}{ticket.sede ? ' · ' + ticket.sede : ''}</div>
            {ticket.cliente && <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 3 }}>{ticket.cliente.nombre} · {ticket.cliente.telefono}<br />{ticket.cliente.direccion}</div>}
          </div>
          <div style={{ fontSize: 12, color: TOKENS.textMuted, fontWeight: 600, textAlign: 'right', flex: 'none' }}>Hoy {fechaTxt}<br />{horaTxt}</div>
        </div>

        {/* 23/11/2026: qué se entrega cuando hay suministros (lo recogido + lo que pone la empresa). */}
        {sumsE.length > 0 && <div style={{ marginTop: 10, background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 12, padding: '10px 12px' }}>
          <div style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: '.06em', color: TOKENS.textMuted }}>SE ENTREGA</div>
          <div style={{ fontSize: 13, marginTop: 6 }}>{window.pcItemsTxt ? window.pcItemsTxt(ticket.items) : ''} <span style={{ color: TOKENS.textMuted }}>(lo recogido)</span></div>
          {sumsE.map((x) => <div key={x.id} style={{ fontSize: 13, marginTop: 4, color: '#0e7490', fontWeight: 600 }}>＋ {window.sumTxt(x)}</div>)}
          <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 6 }}>La factura o remisión debe incluir el suministro.</div>
        </div>}

        {titulo('Cómo se entrega')}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
          {modoBtn('mano', I.users, 'Directo')}
          {modoBtn('transportadora', I.truck, 'Transportadora')}
        </div>

        {enMano ?
        <>
            {titulo('Comprobante')}
            {/* Selector secundario (menos peso visual que En mano / Transportadora) */}
            <div style={{ display: 'inline-flex', background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 999, padding: 3, gap: 2 }}>
              {['Factura', 'Remisión'].map((d) =>
            <button key={d} type="button" onClick={() => setDoc(d)} style={{
              border: 0, borderRadius: 999, padding: '6px 16px', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 700, cursor: 'pointer',
              background: doc === d ? '#fff' : 'transparent', color: doc === d ? TOKENS.primary : TOKENS.textMuted,
              boxShadow: doc === d ? '0 1px 3px rgba(22,35,63,.15)' : 'none'
            }}>{d}</button>
            )}
            </div>
            {campo(`Número de ${docMin}`, true, <DocNumInput doc={doc} value={numero} onChange={setNumero} />)}
            {campo('Recibe', false, inp(recibePor, setRecibePor, 'Nombre de quien recibe'))}
            {titulo(`Foto de la ${docMin}`, `${hojas.length}/${MAX_HOJAS}`)}
            {hojas.length === 0 ?
          capturaGrande(`Tomar foto de la ${docMin}`, 'Firmada y sellada · puedes agregar varias hojas') :
          <>
                <HojasComprobante fotos={hojas} max={MAX_HOJAS} onAgregar={() => setCamara('hojas')} onVer={(i) => setVerFoto({ src: hojas[i], list: hojas })} onQuitar={(i) => setQuitar({ k: 'hojas', i })} />
                <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 6 }}>Toca una hoja para verla. Firmada y sellada por el taller.</div>
              </>
          }
          </> :

        <>
            {campo('Transportadora', true, inp(transportadora, setTransportadora, 'Ej. Servientrega'))}
            {campo('Número de guía', false, inp(guia, (v) => setGuia(v.toUpperCase()), 'Escríbelo como aparece en la guía', true))}
            {titulo('Foto de la guía', `${guiaFotos.length}/${MAX_HOJAS_GUIA}`)}
            {guiaFotos.length === 0 ?
          capturaGrande('Tomar foto de la guía', 'La guía completa, que se lean los datos') :
          <HojasComprobante fotos={guiaFotos} max={MAX_HOJAS_GUIA} onAgregar={() => setCamara('guia')} onVer={(i) => setVerFoto({ src: guiaFotos[i], list: guiaFotos })} onQuitar={(i) => setQuitar({ k: 'guia', i })} />
          }
          </>
        }

        {/* Garantía: el taller devolvió rines al recibir (16/11/2026) */}
        {window.GarantiaCampos && enMano &&
        <>
          <button type="button" onClick={() => { setGarOn(!garOn); setGarToc(false); }} style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%', textAlign: 'left', border: `1.5px solid ${garOn ? '#0e7490' : TOKENS.border}`, background: garOn ? '#eef8f6' : TOKENS.surface, borderRadius: 12, padding: '11px 12px', marginTop: 16, marginBottom: 10, cursor: 'pointer', fontFamily: 'inherit' }}>
            <span style={{ fontSize: 18, color: '#0e7490' }}>↺</span>
            <span style={{ flex: 1 }}><b style={{ display: 'block', fontSize: 14, color: TOKENS.text }}>El taller devolvió rines por garantía</b><span style={{ fontSize: 12, color: TOKENS.textMuted }}>Se entrega la placa y lo devuelto abre una garantía</span></span>
            <span style={{ width: 40, height: 22, borderRadius: 99, background: garOn ? '#0e7490' : TOKENS.borderInput, position: 'relative', flexShrink: 0 }}><span style={{ position: 'absolute', top: 2, left: garOn ? 20 : 2, width: 18, height: 18, borderRadius: 99, background: '#fff', transition: 'left .15s' }} /></span>
          </button>
          {garOn && <window.GarantiaCampos ticket={ticket} v={garV} setV={setGarV} toc={garToc} />}
        </>}
        {/* Rin que sale sin reparar (21/11/2026) */}
        {window.SinRepararCampos && nRinesSr > 0 && <window.SinRepararCampos nRines={nRinesSr} v={srV} setV={setSrV} toc={garToc} />}

        {/* Acciones al final (sin barra fija) */}
        <div style={{ marginTop: 18, paddingTop: 14, borderTop: `1px solid ${TOKENS.border}` }}>
          <div style={{ display: 'flex', gap: 8 }}>
            {/* Cancelar (19/11/2026): el mismo de Recoger — blanco, borde gris y ⊗ rojo */}
            <IconAction title="Cancelar" onClick={salir}>{I.x(20, TOKENS.danger)}</IconAction>
            <Button variant="primary" full icon={I.check(17, '#fff')} disabled={faltas.length > 0} onClick={() => { setGarToc(true); if (!faltas.length) setConfirmar(true); }}
            style={{ padding: '14px', fontSize: 15, background: faltas.length ? undefined : TOKENS.success, borderColor: faltas.length ? undefined : TOKENS.success }}>
              Finalizar entrega
            </Button>
          </div>
          {faltas.length > 0 && <MotivoBloqueo>Para finalizar falta: {faltas.join(', ')}.</MotivoBloqueo>}
        </div>
      </div>

      {camara &&
      <DocCamera
        titulo={`Modo documento · Hoja ${(camara === 'guia' ? guiaFotos : hojas).length + 1}`}
        onCapture={agregarFoto}
        onClose={() => setCamara(null)} />
      }
      {verFoto && <FotoGrande src={verFoto} onClose={() => setVerFoto(null)} />}
      {garTk && window.GarantiaTicket && <window.GarantiaTicket ticket={ticket} g={garTk.g} onCerrar={() => { const en = garTk.entry; setGarTk(null); onSaved && onSaved(en); }} />}

      {quitar &&
      <ConfirmActionModal
        icon={I.trash(24, TOKENS.danger)}
        tone="danger"
        title={`¿Quitar la hoja ${quitar.i + 1}?`}
        message="La foto se quitará de esta entrega. Puedes volver a tomarla."
        confirmLabel="Quitar"
        onConfirm={() => {
          const set = quitar.k === 'guia' ? setGuiaFotos : setHojas;
          set((l) => l.filter((_, j) => j !== quitar.i));
          setQuitar(null);
        }}
        onDismiss={() => setQuitar(null)} />
      }

      {descartar &&
      <ConfirmActionModal
        icon={I.x(24, TOKENS.danger)}
        tone="danger"
        title="¿Descartar la entrega?"
        message={`Se perderán los datos y las fotos que registraste para ${ticket.placa}. La placa sigue pendiente por entregar.`}
        cancelLabel="Seguir"
        confirmLabel="Descartar"
        onConfirm={() => {setDescartar(false);onBack && onBack();}}
        onDismiss={() => setDescartar(false)} />
      }

      {confirmar &&
      <ConfirmActionModal
        icon={I.checkCircle(24, TOKENS.success)}
        tone="primary"
        title={`¿Registrar la entrega de ${ticket.placa}?`}
        message={<>
            Revisa los datos. Después de registrarla, cualquier cambio debe pedírselo a un administrador.
            <div style={{ textAlign: 'left', marginTop: 10, background: TOKENS.surfaceLow, borderRadius: 10, padding: '10px 12px', fontSize: 13, color: TOKENS.text, lineHeight: 1.6 }}>
              {(enMano ?
            [['Entrega', 'Directo'], [doc, fmtComprobante({ factura: docGuardar(doc, numero), comprobanteTipo: doc })], ['Recibe', recibePor.trim() || '—'], ['Fotos', `${hojas.length} ${hojas.length === 1 ? 'hoja' : 'hojas'}`]] :
            [['Entrega', 'Transportadora'], ['Transportadora', transportadora.trim()], ['Guía', guia.trim() || '—'], ['Fotos', `${guiaFotos.length} ${guiaFotos.length === 1 ? 'hoja' : 'hojas'}`]]).
            map(([k, v]) => <div key={k}><span style={{ color: TOKENS.textMuted }}>{k}:</span> <b>{v}</b></div>)}
            </div>
          </>}
        cancelLabel="Revisar"
        confirmLabel="Registrar"
        onConfirm={() => {setConfirmar(false);guardar();}}
        onDismiss={() => setConfirmar(false)} />
      }
    </div>);

}

// ─── Entrega registrada (rediseño 13/11/2026) ───────────────────────────
// Resumen corto, recordatorio de finalizar la parada y la siguiente placa del mismo taller.
function EntregaSuccessScreen({ entrega, onMenu, onSiguiente, siguiente, quedan = 0, enParada, onSiguientePlaca, volverLabel = 'Volver a la lista' }) {
  const [showPrint, setShowPrint] = React.useState(false);
  if (showPrint) {
    return <ImprimirEntregaScreen
      entrega={entrega}
      onBack={() => setShowPrint(false)}
      onPrint={() => alert('Enviado a impresora Bluetooth.')} />;

  }
  const desp = !!entrega.despachado;
  const nFotos = desp ?
  (entrega.guiaFotos || []).length || (entrega.guiaFoto ? 1 : 0) :
  (entrega.fotos || []).length || (entrega.foto ? 1 : 0);
  const filas = [
  ['Fecha', `${String(entrega.fechaEntrega || '').replace(/\s/g, '')} · ${window.formatHora12 ? window.formatHora12(entrega.horaEntrega) : entrega.horaEntrega}`],
  ['Entrega', desp ? 'Transportadora' : 'Directo'],
  ...(desp ?
  [['Transportadora', entrega.transportadora || '—'], ['Guía', entrega.guia || '—']] :
  [[entrega.comprobanteTipo || 'Factura / remisión', fmtComprobante(entrega) || '—'], ['Recibe', entrega.recibePor || '—']]),
  ['Fotos', `${nFotos} ${nFotos === 1 ? 'hoja' : 'hojas'}`]];

  return (
    <div style={{ background: TOKENS.bg, display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
      <AppHeader title="Entrega registrada" hideRuta />
      <div style={{ padding: '14px 16px 24px', flex: 1 }}>
        <div style={{ textAlign: 'center', padding: '10px 0 4px' }}>
          <div style={{ width: 62, height: 62, borderRadius: 999, background: TOKENS.successBg, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 10px' }}>
            {I.check(30, TOKENS.success)}
          </div>
          <div style={{ fontSize: 20, fontWeight: 700, color: TOKENS.text }}>Entrega registrada</div>
          <div style={{ fontSize: 13, color: TOKENS.textMuted, marginTop: 4 }}>
            <b style={{ fontFamily: "'JetBrains Mono', monospace", color: TOKENS.text }}>{entrega.placa}</b> · {entrega.taller}
          </div>
        </div>

        <Card style={{ marginTop: 12, padding: '4px 14px', background: TOKENS.surface }}>
          {filas.map(([k, v], i) =>
          <div key={k} style={{ display: 'flex', justifyContent: 'space-between', gap: 10, fontSize: 13, padding: '8px 0', borderTop: i ? `1px dashed ${TOKENS.border}` : 'none' }}>
              <span style={{ color: TOKENS.textMuted, fontWeight: 600 }}>{k}</span>
              <b style={{ textAlign: 'right', overflowWrap: 'anywhere' }}>{v}</b>
            </div>
          )}
        </Card>

        {enParada &&
        <div style={{ marginTop: 12, background: TOKENS.cautionBg, border: `1px solid ${TOKENS.cautionBorder}`, borderRadius: 12, padding: '10px 12px', fontSize: 12.5, color: TOKENS.cautionText, lineHeight: 1.45 }}>
            {quedan > 0 ?
          <>Quedan <b style={{ color: TOKENS.primary }}>{quedan} {quedan === 1 ? 'placa' : 'placas'}</b> por entregar en este taller.</> :
          'Ya no quedan placas por entregar en este taller.'}
            {' '}Cuando termines aquí, <b style={{ color: TOKENS.primary }}>finaliza la parada</b> desde Inicio.
          </div>
        }

        <div style={{ display: 'grid', gap: 8, marginTop: 18, paddingTop: 14, borderTop: `1px solid ${TOKENS.border}` }}>
          {siguiente && onSiguientePlaca &&
          <Button variant="primary" full icon={I.truck(18, '#fff')} onClick={() => onSiguientePlaca(siguiente)} style={{ padding: '14px', fontSize: 15 }}>
              Entregar {siguiente.placa}
            </Button>
          }
          <Button variant="outline" full icon={I.print(16, TOKENS.primary)} onClick={() => setShowPrint(true)} style={{ padding: '13px', fontSize: 15, color: TOKENS.primary }}>Imprimir constancia</Button>
          <Button variant="outline" full onClick={onSiguiente || onMenu} style={{ padding: '13px', fontSize: 15, color: TOKENS.primary }}>{volverLabel}</Button>
        </div>
      </div>
    </div>);

}

function SuccessRow({ k, v, mono }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 13 }}>
      <span style={{ color: TOKENS.textMuted }}>{k}</span>
      <span style={{ fontWeight: 700, color: TOKENS.text, fontFamily: mono ? 'monospace' : 'inherit', letterSpacing: mono ? '0.04em' : '0' }}>{v}</span>
    </div>
  );
}

function Divider() {
  return <div style={{ borderTop: `1px dashed ${TOKENS.border}`, margin: '10px 0' }} />;
}

Object.assign(window, { ChipEncargo, PlacaOrdenChica, fmtComprobante, DocNumInput, docGuardar, DOC_PREFIJO, TriDatos, FichaSeccion, RecogidaSeccion, FotoGrande, ENTREGADO_COLOR, ChipEntregado, GarantiaInsignia, InsigniasPlaca, CabeceraPlaca, FichaTabla, GarantiaFichaCard, loadCorrecciones, correccionesDe, correccionEnEspera, pedirCorreccion, responderCorreccion, retirarCorreccion, ChipCorreccion, CorreccionBox, PedirCorreccionModal, PLACA_BOX, TarjetaPlaca, HistorialRegistro, AccionesAdmin, DecisionAnulacionModal, SolicitudAnulacionAdminBox, ResumenEntregaScreen, ResumenEntregadoScreen, SolicitarAnulacionModal, ChipSolicitud, DocCamera, EntregaConfirmScreen, EntregaSuccessScreen, FichaTecnicaScreen, FichaCell, SectionTitle, FechasBlock, parseFechaDDMMYYYY, daysBetween, PhotoLightbox, PhotoReal });


// ─── Imprimir Entrega: ticket tipo supermercado (sin foto) ─────────────
function ImprimirEntregaScreen({ entrega, onBack, onPrint }) {
  const items = entrega.items || [];
  const total = items.reduce((s, it) => s + Number(it.cantidad || 0), 0);
  return (
    <div style={{ background: TOKENS.bg, display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
      <AppHeader title="Imprimir comprobante" onBack={onBack} bell={false} />
      <div style={{ padding: '16px' }}>
        <div style={{ fontSize: 12, color: TOKENS.textMuted, marginBottom: 10, textAlign: 'center' }}>
          Vista previa · 58 mm · Impresora térmica Bluetooth
        </div>

        {/* Ticket */}
        <div style={{
          background: '#fff', padding: '20px 18px', borderRadius: 8,
          boxShadow: '0 2px 8px rgba(0,0,0,0.08)',
          fontFamily: '"SF Mono", "Consolas", "Menlo", monospace',
          fontSize: 12, color: '#000', lineHeight: 1.55,
          backgroundImage: 'repeating-linear-gradient(135deg, transparent 0, transparent 2px, rgba(0,0,0,0.012) 2px, rgba(0,0,0,0.012) 4px)',
          position: 'relative',
        }}>
          {/* Torn top */}
          <div style={{
            position: 'absolute', top: -6, left: 0, right: 0, height: 6,
            backgroundImage: 'linear-gradient(135deg, #fff 33%, transparent 33%), linear-gradient(45deg, #fff 33%, transparent 33%)',
            backgroundSize: '8px 8px',
          }} />

          {/* Header */}
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontWeight: 700, fontSize: 14, letterSpacing: '0.1em' }}>RODANDO · SALVALLANTAS S.A.S.</div>
            <div style={{ fontSize: 10 }}>NIT 900.123.456-7</div>
            <div style={{ fontSize: 10 }}>Comprobante de Entrega</div>
          </div>
          <div style={{ borderTop: '1px dashed #000', margin: '10px 0' }} />

          {/* Estado destacado */}
          <div style={{
            textAlign: 'center', padding: '6px 8px',
            border: '2px solid #000', fontWeight: 700,
            letterSpacing: '0.12em', fontSize: 13, marginBottom: 12,
          }}>
            ★ ENTREGADO ★
          </div>

          {/* Datos inline (label izq · valor der) */}
          {[
            ['Entregado:', `${entrega.fechaEntrega} · ${window.formatHora12(entrega.horaEntrega)}`],
            ['Orden:', '' + entrega.codigo],
            [entrega.idType === 'vin' ? 'VIN:' : 'Placa:', entrega.placa],
            ['Aseguradora:', entrega.aseguradora],
            ['Taller:', entrega.taller],
            ['Sede:', entrega.sede],
          ].map(([k, v]) => (
            <div key={k} style={{
              display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
              gap: 10, marginBottom: 4,
            }}>
              <span>{k}</span>
              <span style={{ fontWeight: 700, textAlign: 'right', wordBreak: 'break-all' }}>{v || '—'}</span>
            </div>
          ))}

          <div style={{ borderTop: '1px dashed #000', margin: '10px 0' }} />

          {/* Comprobante (section + factura + mensajero) */}
          <div style={{ fontWeight: 700, textTransform: 'uppercase', fontSize: 11, marginBottom: 6 }}>Comprobante</div>
          <div style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
            gap: 10, marginBottom: 4,
          }}>
            <span>Factura/Rem:</span>
            <span style={{ fontWeight: 700, textAlign: 'right', wordBreak: 'break-all' }}>{fmtComprobante(entrega) || '—'}</span>
          </div>
          <div style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
            gap: 10, marginBottom: 4,
          }}>
            <span>Mensajero:</span>
            <span style={{ fontWeight: 700, textAlign: 'right' }}>{entrega.entregadoPorNombre || (window.userName ? window.userName() : '')}</span>
          </div>
          {entrega.recibePor && (
            <div style={{
              display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
              gap: 10, marginBottom: 4,
            }}>
              <span>Recibe:</span>
              <span style={{ fontWeight: 700, textAlign: 'right', wordBreak: 'break-all' }}>{entrega.recibePor}</span>
            </div>
          )}

          <div style={{ borderTop: '1px dashed #000', margin: '10px 0' }} />

          {/* Firma placeholder */}
          <div style={{ marginTop: 10, marginBottom: 4 }}>
            <div style={{ borderBottom: '1px solid #000', height: 28 }} />
            <div style={{ fontSize: 10, textAlign: 'center', marginTop: 4 }}>
              Firma de quien recibe
            </div>
          </div>

          <div style={{ borderTop: '1px dashed #000', margin: '10px 0' }} />
          <div style={{ textAlign: 'center', fontSize: 10 }}>
            ¡Gracias!
          </div>

          {/* Torn bottom */}
          <div style={{
            marginTop: 12, height: 6,
            backgroundImage: 'linear-gradient(225deg, #fff 33%, transparent 33%), linear-gradient(315deg, #fff 33%, transparent 33%)',
            backgroundSize: '8px 8px',
          }} />
        </div>

        <div style={{
          marginTop: 14, padding: 12, background: TOKENS.surfaceContainer,
          borderRadius: 10, fontSize: 12, color: TOKENS.textMuted,
          display: 'flex', gap: 10, alignItems: 'flex-start',
        }}>
          <div style={{ marginTop: 2 }}>{I.print(18, TOKENS.primary)}</div>
          <div>
            Al pulsar <b>Imprimir</b> se enviará a la impresora Bluetooth emparejada con este dispositivo.
            La foto de la factura no se incluye en el ticket impreso.
          </div>
        </div>
      </div>
      <div style={{ padding: '12px 16px 16px', borderTop: `1px solid ${TOKENS.border}`, display: 'flex', gap: 10, background: TOKENS.bg, position: 'sticky', bottom: 0, zIndex: 10 }}>
        <Button variant="outline" onClick={onBack} style={{ flex: 1 }}>Volver</Button>
        <Button variant="dark" icon={I.print(16, '#fff')} onClick={onPrint} style={{ flex: 2 }}>Imprimir</Button>
      </div>
    </div>
  );
}

Object.assign(window, { ImprimirEntregaScreen });
