// Panel del PC (13/11/2026): la misma app en pantalla grande para el administrador.
// Menú lateral blanco · Inicio (ruta en vivo, por entregar, por recoger, por taller) ·
// Registros (tabla + detalle que se desliza por encima + registrar recogida/entrega) ·
// Rutas · Informes (un solo Excel) · Catálogos · Usuarios. Notas y notificaciones en la barra.
// Rutas y Catálogos van a dos columnas. Notificaciones, Mi perfil y la edición de un
// registro usan las pantallas del celular en una columna dentro del panel.

const PC_ANCHO_MIN = 1024;
// 27/11/2026: en la vista celular (también en el PC con vista celular) las capas fijas se quedan dentro de la columna del celular.
const PC_CEL_FIJO = { left: 0, right: 0, marginLeft: 'auto', marginRight: 'auto', width: '100%', maxWidth: 440 };
function usePantallaAncha() {
  const [w, setW] = React.useState(() => window.innerWidth);
  React.useEffect(() => { const f = () => setW(window.innerWidth); window.addEventListener('resize', f); return () => window.removeEventListener('resize', f); }, []);
  return w >= PC_ANCHO_MIN;
}

// ─── Datos ───────────────────────────────────────────────────────────────
const pcMono = "'JetBrains Mono', monospace";
const pcAseg = (a) => window.catAseguradoraCorta ? window.catAseguradoraCorta(a) : a;
const pcFechaDate = (f, h) => window.parseFechaHora ? window.parseFechaHora(f, h) : null;
const pcIso = (f) => { const d = pcFechaDate(f); return d ? `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}` : ''; };
const pcFechaCorta = (f) => { const d = pcFechaDate(f); return d ? `${String(d.getDate()).padStart(2, '0')}/${String(d.getMonth() + 1).padStart(2, '0')}/${d.getFullYear()}` : (f || '—'); };
const pcDeIso = (iso) => { const [y, m, d] = String(iso).split('-'); return `${d} / ${m} / ${y}`; };
const pcHoyIso = () => { const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; };
const PC_EST = [['Vencido', TOKENS.dangerBg, TOKENS.dangerText, TOKENS.danger], ['Retrasado', TOKENS.warningBg, TOKENS.warningText, TOKENS.warning], ['Vence hoy', '#fff2cc', '#7f6000', '#f2c037'], ['En plazo', TOKENS.successBg, TOKENS.successText, TOKENS.success]];
function pcDiasEntrega(rec, ent) {
  try {
    // Si hubo rines esperando autorización, el plazo se cuenta desde que se resolvió la última.
    const re = window.reinicioPlazo ? window.reinicioPlazo(rec.id || ent.ticketId) : null;
    const start = re ? window.effectiveStart(re.fecha, re.hora) : window.effectiveStart(rec.fecha, rec.horaRecogida);
    const fin = pcFechaDate(ent.fechaEntrega, ent.horaEntrega);
    return window.businessDaysElapsed(start, fin);
  } catch (e) { return 0; }
}
const pcSlaDe = (express) => express ? (window.loadCatServicios ? window.loadCatServicios().slaExpress : 2) : (window.loadSlaConfig ? window.loadSlaConfig().slaHabiles : 3);
const pcPlazoDe = (d, express) => { const S = pcSlaDe(express); return d < S ? 3 : d === S ? 2 : d === S + 1 ? 1 : 0; };
function pcComoLlego(t) {
  if (t.comoLlego === 'otra-ciudad') return 'Llegó de otra ciudad' + (t.transportadoraLlegada ? ' · ' + t.transportadoraLlegada : '');
  if (t.comoLlego === 'taller') return 'Lo trajo el taller';
  if (t.encargo || t.comoLlego === 'encargo') return 'Encargo asignado' + (t.digitadoPorNombre ? ' por ' + t.digitadoPorNombre : '');
  return t.recogidoPorNombre || (window.nombreDeUsuario && window.nombreDeUsuario(t.recogidoPor)) || '—';
}
function pcItemsTxt(items) {
  const n = (tipo) => (items || []).filter((i) => i && i.tipo === tipo).reduce((a, i) => a + (Number(i.cantidad) || 0), 0);
  const r = n('rin'), l = n('llanta'), v = n('valvula');
  return [r && `${r} ${r === 1 ? 'rin' : 'rines'}`, l && `${l} ${l === 1 ? 'llanta' : 'llantas'}`, v && `${v} ${v === 1 ? 'válvula' : 'válvulas'}`].filter(Boolean).join(' · ') || 'Sin ítems';
}
function pcItemDetalle(it) {
  if (it.tipo === 'rin') return [`${it.cantidad} ${Number(it.cantidad) === 1 ? 'rin' : 'rines'}`, it.tamano && it.tamano + '"', it.material, it.huecos, it.tapa && 'tapa ' + it.tapa.toLowerCase(), it.tapaValvula && 'tapa válvula ' + it.tapaValvula.toLowerCase()].filter(Boolean).join(' · ');
  if (it.tipo === 'llanta') return [`${it.cantidad} ${Number(it.cantidad) === 1 ? 'llanta' : 'llantas'}`, it.marca, it.referencia, it.dot && 'DOT ' + it.dot, it.calidad].filter(Boolean).join(' · ');
  if (it.tipo === 'valvula') return [`${it.cantidad} ${Number(it.cantidad) === 1 ? 'válvula' : 'válvulas'}`, it.valvulaSensor && 'sensor ' + it.valvulaSensor.toLowerCase()].filter(Boolean).join(' · ');
  return `${it.cantidad || ''} ${it.tipo || ''}`;
}
// Todos los registros normalizados: por entregar, entregados y anulados.
function pcRegistros() {
  const saved = window.loadPendientesSaved ? window.loadPendientesSaved() : [];
  const demo = (window.PENDIENTES_DEMO || []).map(window.catCanonObj || ((x) => x));
  const entregados = window.loadEntregados ? window.loadEntregados() : [];
  const anuMap = window.loadAnulacionMap ? window.loadAnulacionMap() : new Map();
  const entIds = new Set(entregados.map((e) => e.ticketId));
  const out = [];
  const codSaved = new Set(saved.map((t) => String(t.codigo)));
  [...saved.map((t) => ({ t, src: 'pendiente-saved' })), ...demo.filter((t) => !codSaved.has(String(t.codigo))).map((t) => ({ t, src: 'pendiente-demo' }))].forEach(({ t, src }) => {
    if (entIds.has(t.id)) return;
    const a = anuMap.get(t.id);
    const tt = window.withAnulacion ? window.withAnulacion(t, anuMap) : t;
    const anulado = a && a.estadoActual === 'anulado';
    const est = !anulado && window.estadoProcesos ? window.estadoProcesos(tt) : null;
    out.push({ ...tt, aseguradora: pcAseg(t.aseguradora), _t: tt, _source: src, _estado: anulado ? 'anu' : 'pend', _est: est, _anu: a || null, _iso: pcIso(t.fecha) });
  });
  entregados.forEach((e) => {
    const rec = { ...e, id: e.ticketId, fecha: e.fechaRecogido, horaRecogida: e.horaRecogida };
    const d = pcDiasEntrega(rec, e);
    // Garantía abierta (16/11/2026): vuelve a Por entregar con su propio plazo; la primera entrega se conserva.
    const g = window.garantiaAbierta ? window.garantiaAbierta(e.ticketId) : null;
    if (g) { const ge = window.garEstado(g); out.push({ ...rec, aseguradora: pcAseg(e.aseguradora), _t: { ...rec, _status: 'entregado', _entrega: e }, _source: 'entregado', _estado: 'pend', _gar: g, _ent: e, _diasPrimera: d, _plazoPrimera: pcPlazoDe(d, e.express), _est: { ...ge, bg: PC_EST[ge.orden][1], fg: PC_EST[ge.orden][2] }, _iso: pcIso(e.fechaRecogido), _isoEnt: pcIso(e.fechaEntrega) }); return; }
    out.push({ ...rec, aseguradora: pcAseg(e.aseguradora), _t: { ...rec, _status: 'entregado', _entrega: e }, _source: 'entregado', _estado: 'ent', _ent: e, _dias: d, _plazo: pcPlazoDe(d, e.express), _iso: pcIso(e.fechaRecogido), _isoEnt: pcIso(e.fechaEntrega) });
  });
  return out;
}
function useRefrescoPC() {
  const [, r] = React.useState(0);
  React.useEffect(() => {
    const h = () => r((n) => n + 1);
    const ev = ['storage', 'focus', 'rodando-anulaciones', 'rodando-paradas', 'rodando-notifs', 'rodando-notas', 'rodando-catalogo', 'rodando-usuarios', 'rodando-pc', 'rodando-servicios'];
    ev.forEach((x) => window.addEventListener(x, h));
    const t = setInterval(h, 20000);
    return () => { ev.forEach((x) => window.removeEventListener(x, h)); clearInterval(t); };
  }, []);
}
const pcAvisar = () => { try { window.dispatchEvent(new Event('rodando-pc')); } catch (e) {} };

// ─── Excel (.xlsx) sin librerías: ZIP sin compresión + hojas con texto en línea ──
const pcCrcT = (() => { const t = []; for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xEDB88320 ^ (c >>> 1) : c >>> 1; t[n] = c >>> 0; } return t; })();
function pcCrc(b) { let c = 0xFFFFFFFF; for (let i = 0; i < b.length; i++) c = pcCrcT[(c ^ b[i]) & 0xFF] ^ (c >>> 8); return (c ^ 0xFFFFFFFF) >>> 0; }
function pcZip(files) {
  const enc = new TextEncoder(); const parts = []; const central = []; let off = 0;
  const u16 = (v) => [v & 255, (v >> 8) & 255], u32 = (v) => [v & 255, (v >> 8) & 255, (v >> 16) & 255, (v >>> 24) & 255];
  files.forEach(([name, txt]) => {
    const nb = enc.encode(name), db = enc.encode(txt), crc = pcCrc(db);
    const head = new Uint8Array([...u32(0x04034b50), ...u16(20), ...u16(0x0800), ...u16(0), ...u16(0), ...u16(0), ...u32(crc), ...u32(db.length), ...u32(db.length), ...u16(nb.length), ...u16(0)]);
    parts.push(head, nb, db);
    central.push(new Uint8Array([...u32(0x02014b50), ...u16(20), ...u16(20), ...u16(0x0800), ...u16(0), ...u16(0), ...u16(0), ...u32(crc), ...u32(db.length), ...u32(db.length), ...u16(nb.length), ...u16(0), ...u16(0), ...u16(0), ...u16(0), ...u32(0), ...u32(off)]), nb);
    off += head.length + nb.length + db.length;
  });
  const cSize = central.reduce((a, b) => a + b.length, 0);
  const end = new Uint8Array([...u32(0x06054b50), ...u16(0), ...u16(0), ...u16(files.length), ...u16(files.length), ...u32(cSize), ...u32(off), ...u16(0)]);
  return new Blob([...parts, ...central, end], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
}
const pcX = (s) => String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
function pcCol(i) { let s = ''; i++; while (i) { const m = (i - 1) % 26; s = String.fromCharCode(65 + m) + s; i = Math.floor((i - 1) / 26); } return s; }
function pcHoja(rows, anchos) {
  const xr = rows.map((r, ri) => r ? `<row r="${ri + 1}">${r.cells.map((v, ci) => {
    const ref = pcCol(ci) + (ri + 1); const st = r.bold ? ' s="1"' : '';
    if (typeof v === 'number' && isFinite(v)) return `<c r="${ref}"${st}><v>${v}</v></c>`;
    if (v === '' || v == null) return '';
    return `<c r="${ref}" t="inlineStr"${st}><is><t xml:space="preserve">${pcX(v)}</t></is></c>`;
  }).join('')}</row>` : '').join('');
  const cols = anchos ? `<cols>${anchos.map((w, i) => `<col min="${i + 1}" max="${i + 1}" width="${w}" customWidth="1"/>`).join('')}</cols>` : '';
  return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetViews><sheetView workbookViewId="0"><pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/></sheetView></sheetViews>${cols}<sheetData>${xr}</sheetData></worksheet>`;
}
function pcLibro(hojas) { // [{nombre, rows, anchos}]
  const files = [
    ['[Content_Types].xml', `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>${hojas.map((h, i) => `<Override PartName="/xl/worksheets/sheet${i + 1}.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>`).join('')}</Types>`],
    ['_rels/.rels', `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>`],
    ['xl/workbook.xml', `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets>${hojas.map((h, i) => `<sheet name="${pcX(h.nombre)}" sheetId="${i + 1}" r:id="rId${i + 1}"/>`).join('')}</sheets></workbook>`],
    ['xl/_rels/workbook.xml.rels', `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${hojas.map((h, i) => `<Relationship Id="rId${i + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet${i + 1}.xml"/>`).join('')}<Relationship Id="rId${hojas.length + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>`],
    ['xl/styles.xml', `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><fonts count="2"><font><sz val="11"/><name val="Calibri"/></font><font><b/><sz val="11"/><name val="Calibri"/></font></fonts><fills count="3"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill><fill><patternFill patternType="solid"><fgColor rgb="FFE8EFFB"/></patternFill></fill></fills><borders count="1"><border/></borders><cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs><cellXfs count="2"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/><xf numFmtId="0" fontId="1" fillId="2" borderId="0" xfId="0" applyFont="1" applyFill="1"/></cellXfs><cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles></styleSheet>`],
    ...hojas.map((h, i) => [`xl/worksheets/sheet${i + 1}.xml`, pcHoja(h.rows, h.anchos)]),
  ];
  return pcZip(files);
}
// Lee un .xlsx (25/11/2026): primera hoja → filas de texto. Sin librerías: zip + DecompressionStream.
async function pcLeerXlsx(file) {
  const buf = new Uint8Array(await file.arrayBuffer()); const dv = new DataView(buf.buffer);
  let e = buf.length - 22; while (e >= 0 && dv.getUint32(e, true) !== 0x06054b50) e--;
  if (e < 0) throw new Error('No es un archivo de Excel (.xlsx).');
  const n = dv.getUint16(e + 10, true); let p = dv.getUint32(e + 16, true); const files = {}; const td = new TextDecoder();
  for (let i = 0; i < n; i++) {
    const nl = dv.getUint16(p + 28, true), el = dv.getUint16(p + 30, true), cl = dv.getUint16(p + 32, true);
    files[td.decode(buf.slice(p + 46, p + 46 + nl))] = { m: dv.getUint16(p + 10, true), cs: dv.getUint32(p + 20, true), lo: dv.getUint32(p + 42, true) };
    p += 46 + nl + el + cl;
  }
  const leer = async (name) => { const f = files[name]; if (!f) return null; const l = f.lo; const d = buf.slice(l + 30 + dv.getUint16(l + 26, true) + dv.getUint16(l + 28, true)); const data = d.slice(0, f.cs);
    if (f.m === 0) return td.decode(data);
    return td.decode(await new Response(new Blob([data]).stream().pipeThrough(new DecompressionStream('deflate-raw'))).arrayBuffer()); };
  const xml = (t) => new DOMParser().parseFromString(t, 'application/xml');
  const ssT = await leer('xl/sharedStrings.xml'); const ss = ssT ? [...xml(ssT).getElementsByTagName('si')].map((si) => [...si.getElementsByTagName('t')].map((t) => t.textContent).join('')) : [];
  const hoja = await leer('xl/worksheets/sheet1.xml') || await leer(Object.keys(files).find((k) => /^xl\/worksheets\/sheet\d+\.xml$/.test(k)) || '');
  if (!hoja) throw new Error('El archivo no tiene hojas.');
  const colN = (ref) => { const m = String(ref).match(/^[A-Z]+/); let c = 0; (m ? m[0] : 'A').split('').forEach((ch) => { c = c * 26 + ch.charCodeAt(0) - 64; }); return c - 1; };
  return [...xml(hoja).getElementsByTagName('row')].map((row) => { const out = []; [...row.getElementsByTagName('c')].forEach((c) => {
    const t = c.getAttribute('t'); const v = c.getElementsByTagName('v')[0]; let val = '';
    if (t === 's') val = ss[+(v ? v.textContent : 0)] || ''; else if (t === 'inlineStr') val = [...c.getElementsByTagName('t')].map((x) => x.textContent).join(''); else val = v ? v.textContent : '';
    out[colN(c.getAttribute('r'))] = val; }); return out; });
}
// 25/11/2026: dentro de claude.ai las descargas pasan por la capacidad "downloads" (el usuario confirma). Fuera, enlace normal.
async function pcDescargar(blob, nombre) {
  let d = null; try { d = window.claude && window.claude.use ? await window.claude.use('downloads') : null; } catch (e) { d = null; }
  if (d) {
    try { await d.save({ filename: nombre, data: blob }); return true; }
    catch (e) {
      const c = e && e.code;
      if (c === 'declined') return false;
      if (c === 'host_unavailable') { alert('Esta app no puede guardar archivos aquí. Abre la app en un navegador o en el computador para descargarlo.'); return false; }
      if (c === 'rate_limited') { alert('Ya hay una descarga esperando confirmación.'); return false; }
    }
  }
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a'); a.href = url; a.download = nombre; document.body.appendChild(a); a.click();
  setTimeout(() => { URL.revokeObjectURL(url); a.remove(); }, 1500);
  return true;
}

// ─── Piezas de UI ────────────────────────────────────────────────────────
const pcCard = { background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 14 };
const pcLbl = { fontSize: 10.5, fontWeight: 800, letterSpacing: '0.06em', color: TOKENS.textMuted, textTransform: 'uppercase' };
const pcInp = { border: `1px solid ${TOKENS.borderInput}`, background: TOKENS.surface, borderRadius: 10, padding: '9px 11px', fontSize: 13.5, color: TOKENS.text, fontFamily: 'inherit', outline: 'none', boxSizing: 'border-box' };
function PcBtn({ tone = 'o', children, onClick, disabled, style }) {
  const t = { p: { background: TOKENS.primary, color: '#fff', border: 'none' }, o: { background: TOKENS.surface, color: TOKENS.primary, border: `1px solid ${TOKENS.borderInput}` },
    g: { background: TOKENS.success, color: '#fff', border: 'none' }, y: { background: '#fff2cc', color: '#7f6000', border: '1px solid #ecd98f' },
    r: { background: TOKENS.surface, color: TOKENS.danger, border: `1.5px solid ${TOKENS.borderInput}` } }[tone]; // rojo de contorno: el de Recoger (19/11/2026)
  return <button type="button" onClick={disabled ? undefined : onClick} disabled={disabled} style={{ ...t, borderRadius: 10, padding: '9px 14px', fontFamily: 'inherit', fontSize: 13, fontWeight: 800, cursor: disabled ? 'not-allowed' : 'pointer', whiteSpace: 'nowrap', opacity: disabled ? 0.45 : 1, ...style }}>{children}</button>;
}
function PcChipEst({ k, extra }) {
  const e = PC_EST[k];
  return <span style={{ display: 'inline-block', fontSize: 11.5, fontWeight: 500, borderRadius: 999, padding: '3px 9px', whiteSpace: 'nowrap', background: e[1], color: e[2] }}>{e[0]}{extra ? ' · ' + extra : ''}</span>;
}
function PcChip({ bg, fg, children }) { return <span style={{ display: 'inline-block', fontSize: 11.5, fontWeight: 500, borderRadius: 999, padding: '3px 9px', whiteSpace: 'nowrap', background: bg, color: fg }}>{children}</span>; }
const PcPlaca = ({ p, big }) => <span style={{ fontFamily: pcMono, fontWeight: 700, fontSize: big ? 24 : 13, ...(big ? {} : { background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 6, padding: '2px 6px' }) }}>{p}</span>;
function PcSeg({ value, options, onChange }) {
  return (
    <div style={{ display: 'inline-flex', background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 10, padding: 3, gap: 2 }}>
      {options.map(([v, l]) => <button key={v} type="button" onClick={() => onChange(v)} style={{ border: 0, borderRadius: 8, padding: '6px 11px', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 700, cursor: 'pointer', background: value === v ? TOKENS.primary : 'transparent', color: value === v ? '#fff' : TOKENS.textMuted }}>{l}</button>)}
    </div>);
}
function PcPills({ value, options, onChange, small }) {
  return <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>{options.map((o) => { const [v, l] = Array.isArray(o) ? o : [o, o]; const on = value === v; return <button key={v} type="button" onClick={() => onChange(v)} style={{ border: `1px solid ${on ? TOKENS.primary : TOKENS.borderInput}`, background: on ? TOKENS.primary : TOKENS.surface, color: on ? '#fff' : TOKENS.text, borderRadius: 9, padding: small ? '6px 10px' : '8px 12px', fontFamily: 'inherit', fontSize: small ? 12 : 13, fontWeight: 700, cursor: 'pointer' }}>{l}</button>; })}</div>;
}
function PcCampo({ label, children, nota, full }) {
  return <div style={{ gridColumn: full ? '1 / -1' : 'auto', minWidth: 0 }}><div style={{ ...pcLbl, marginBottom: 5 }}>{label}</div>{children}{nota && <div style={{ fontSize: 11.5, color: TOKENS.textMuted, marginTop: 5, lineHeight: 1.4 }}>{nota}</div>}</div>;
}
// Panel que se desliza por encima del contenido (no lo empuja). Cierra con ✕, Esc o clic afuera.
function PcDrawer({ titulo, ancho = 420, onClose, children, pie, fondo, onEsc, onAtras, atrasTxt }) {
  // Esc cierra el panel; si hay algo abierto encima (p. ej. una foto en grande), onEsc decide qué cerrar.
  const escRef = React.useRef(); escRef.current = onEsc || onClose;
  React.useEffect(() => { const f = (e) => { if (e.key === 'Escape') escRef.current(); }; window.addEventListener('keydown', f); return () => window.removeEventListener('keydown', f); }, []);
  const cel = usePcCel(); // 27/11/2026: en el celular el panel ocupa toda la pantalla
  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', top: 0, bottom: 0, left: cel ? 0 : window.rdAnchoMenu || 232, right: 0, background: 'rgba(17,35,74,.18)', zIndex: 900, animation: 'pcFade .15s' }} />
      <div style={{ position: 'fixed', top: 0, right: 0, bottom: 0, width: ancho, maxWidth: 'calc(100vw - 240px)', ...(cel ? PC_CEL_FIJO : {}), background: TOKENS.surface, borderLeft: `1px solid ${TOKENS.border}`, boxShadow: '-18px 0 40px rgba(11,28,48,.16)', zIndex: 901, display: 'flex', flexDirection: 'column', animation: 'pcSlide .2s ease-out' }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8, padding: '14px 18px', borderBottom: `1px solid ${TOKENS.border}` }}>
          {onAtras && <button type="button" onClick={onAtras} title={atrasTxt || 'Volver'} aria-label={atrasTxt || 'Volver'} style={{ border: `1px solid ${TOKENS.border}`, background: TOKENS.surface, borderRadius: 9, width: 32, height: 32, display: 'grid', placeItems: 'center', cursor: 'pointer', flexShrink: 0 }}>{I.chevLeft(18, TOKENS.primary)}</button>}
          <div style={{ flex: 1, minWidth: 0, alignSelf: 'center' }}>{titulo}</div>
          <button type="button" onClick={onClose} aria-label="Cerrar" style={{ border: `1px solid ${TOKENS.border}`, background: TOKENS.surface, borderRadius: 9, width: 32, height: 32, display: 'grid', placeItems: 'center', cursor: 'pointer' }}>{I.x(16, TOKENS.textMuted)}</button>
        </div>
        <div style={{ flex: 1, overflow: 'auto', padding: '16px 18px', background: typeof fondo === 'string' ? fondo : fondo ? TOKENS.bg : 'transparent' }}>{children}</div>
        {pie && <div style={{ display: 'flex', gap: 8, padding: '12px 18px', borderTop: `1px solid ${TOKENS.border}`, background: fondo ? TOKENS.surface : TOKENS.bg }}>{pie}</div>}
      </div>
    </>);
}
// Columna con una pantalla del celular dentro del panel.
function PcColumna({ children }) {
  return <div style={{ maxWidth: 460, margin: '0 auto', border: `1px solid ${TOKENS.border}`, borderRadius: 16, overflow: 'hidden', background: TOKENS.bg, boxShadow: '0 10px 30px rgba(11,28,48,.08)', position: 'relative' }}>{children}</div>;
}
function pcLeerFotos(files, cb) {
  [...(files || [])].slice(0, 10).forEach((f) => { const rd = new FileReader(); rd.onload = async () => { const s = window.downscaleDataURL ? await window.downscaleDataURL(rd.result, 1100, 0.7) : rd.result; cb(s); }; rd.readAsDataURL(f); });
}
function PcSubirFotos({ fotos, setFotos, texto, max = 10 }) {
  return (
    <>
      <label style={{ display: 'block', border: `1.5px dashed ${TOKENS.borderInput}`, borderRadius: 12, padding: 16, textAlign: 'center', color: TOKENS.textMuted, fontSize: 13, cursor: 'pointer', background: TOKENS.surface }}>
        ⇪ {texto}
        <input type="file" accept="image/*" multiple style={{ display: 'none' }} onChange={(e) => { pcLeerFotos(e.target.files, (s) => setFotos((arr) => arr.length >= max ? arr : [...arr, s])); e.target.value = ''; }} />
      </label>
      {fotos.length > 0 &&
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 8 }}>
          {fotos.map((u, i) => <div key={i} style={{ position: 'relative' }}><img src={u} style={{ width: 70, height: 70, objectFit: 'cover', borderRadius: 8, border: `1px solid ${TOKENS.border}` }} /><button type="button" onClick={() => setFotos((arr) => arr.filter((_, j) => j !== i))} aria-label="Quitar foto" style={{ position: 'absolute', top: -6, right: -6, width: 20, height: 20, borderRadius: 99, border: 'none', background: TOKENS.danger, color: '#fff', fontSize: 11, cursor: 'pointer' }}>✕</button></div>)}
        </div>}
    </>);
}

// ─── Inicio ──────────────────────────────────────────────────────────────
function PcRutaMensajero({ m, abierta, onToggle, onIrRutas }) {
  const hoy = fechaDDMMYYYY();
  const paradas = (window.loadParadas ? window.loadParadas() : []).filter((p) => p.fecha === hoy && p.asignadoA === m.usuario && ['pendiente', 'en_curso', 'completada'].includes(p.estado));
  const dest = (window.groupByDestino ? window.groupByDestino(paradas) : []).sort((a, b) => (a.estado === 'completada' ? 0 : 1) - (b.estado === 'completada' ? 0 : 1) || a.orden - b.orden);
  const hechas = dest.filter((d) => d.estado === 'completada').length;
  const cur = dest.find((d) => d.estado === 'en_curso');
  const prox = dest.find((d) => d.estado === 'pendiente');
  const pct = dest.length ? Math.round(hechas / dest.length * 100) : 0;
  const tareaTxt = (d) => d.tareas.map((t) => t.tipo === 'recoger' ? `Recoger${(t.placas || []).length ? ' ' + t.placas.join(', ') : ''}` : t.tipo === 'entregar' ? `Entregar ${(t.consecutivos || []).join(', ')}` : (t.referencia || 'Otro')).join(' · ');
  const markers = dest.filter((d) => d.lat != null && d.lng != null).map((d, i) => ({ lat: d.lat, lng: d.lng, label: d.estado === 'completada' ? '✓' : String(dest.indexOf(d) + 1), color: d.estado === 'completada' ? TOKENS.primary : d.estado === 'en_curso' ? TOKENS.caution : '#8c97ad', popup: `<b>${d.taller}</b> · ${d.sede || ''}` }));
  const Map = typeof MapView !== 'undefined' ? MapView : null;
  return (
    <div style={{ ...pcCard, padding: '12px 16px', marginBottom: 14 }}>
      <div onClick={onToggle} style={{ display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer', userSelect: 'none' }}>
        <div style={{ minWidth: 0 }}>
          <div style={pcLbl}>Ruta de {m.nombre} · en vivo</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 6, fontSize: 13 }}>
            {dest.length ? <><b style={{ whiteSpace: 'nowrap' }}>{hechas} de {dest.length} {dest.length === 1 ? 'parada' : 'paradas'}</b>
              <span style={{ width: 140, height: 6, borderRadius: 99, background: TOKENS.surfaceLow, overflow: 'hidden' }}><span style={{ display: 'block', width: pct + '%', height: '100%', background: TOKENS.primary }} /></span></> :
            <span style={{ color: TOKENS.textMuted }}>Sin ruta para hoy</span>}
          </div>
        </div>
        <span style={{ flex: 1 }} />
        {cur &&
        <span style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 12.5, fontWeight: 500, color: TOKENS.cautionText, background: TOKENS.cautionBg, border: `1px solid ${TOKENS.cautionBorder}`, borderRadius: 999, padding: '5px 11px', whiteSpace: 'nowrap' }}>
            <span style={{ width: 8, height: 8, borderRadius: 99, background: TOKENS.cautionText, animation: 'rdBlink 1.4s infinite' }} />
            En curso: {cur.taller}{cur.sede ? ' · ' + cur.sede : ''}{cur.iniciadaEn && window.LiveTimer ? <> · <window.LiveTimer since={cur.iniciadaEn} /></> : null}
          </span>}
        {prox && <span style={{ fontSize: 12, color: TOKENS.textMuted, whiteSpace: 'nowrap' }}>Próxima: {prox.taller}{prox.sede ? ' · ' + prox.sede : ''}</span>}
        <span style={{ width: 28, height: 28, borderRadius: 8, display: 'grid', placeItems: 'center', border: `1px solid ${TOKENS.border}`, transform: abierta ? 'rotate(180deg)' : 'none', transition: 'transform .15s' }}>{I.chev(15, TOKENS.primary)}</span>
      </div>
      {abierta &&
      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 16, marginTop: 12 }}>
          <div>
            {!dest.length && <div style={{ fontSize: 13, color: TOKENS.textMuted, padding: '10px 0' }}>{m.nombre} aún no tiene paradas para hoy.</div>}
            {dest.map((d, i) => {
            const done = d.estado === 'completada', en = d.estado === 'en_curso';
            return (
              <div key={d.key} style={{ display: 'flex', gap: 10, alignItems: 'flex-start', padding: en ? '10px 12px' : '10px 0', margin: en ? '0 -12px' : 0, borderTop: en ? 'none' : `1px solid ${TOKENS.border}`, background: en ? TOKENS.cautionBg : 'transparent', border: en ? `1px solid ${TOKENS.caution}` : undefined, borderRadius: en ? 10 : 0 }}>
                  <span style={{ width: 24, height: 24, borderRadius: 99, display: 'grid', placeItems: 'center', fontSize: 11.5, fontWeight: 800, flexShrink: 0, background: done ? TOKENS.primary : en ? '#fff' : TOKENS.surfaceLow, color: done ? '#fff' : en ? TOKENS.cautionText : TOKENS.textMuted, border: `1px solid ${done ? TOKENS.primary : en ? TOKENS.caution : TOKENS.border}` }}>{done ? '✓' : i + 1}</span>
                  <div style={{ flex: 1, minWidth: 0 }}><b style={{ fontSize: 13.5 }}>{d.taller}{d.sede ? ' · ' + d.sede : ''}</b><span style={{ display: 'block', fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>{tareaTxt(d)}</span></div>
                  <span style={{ fontSize: 12, whiteSpace: 'nowrap', color: en ? TOKENS.cautionText : TOKENS.textSubtle, fontWeight: en ? 800 : 500 }}>{en ? 'En curso' : done ? (d.completadaEn ? new Date(d.completadaEn).toLocaleTimeString('es-CO', { hour: 'numeric', minute: '2-digit' }) : 'Hecha') : 'Pendiente'}</span>
                </div>);
          })}
          </div>
          <div style={{ position: 'relative', minHeight: 230 }}>
            {Map && markers.length ? <Map markers={markers} height={260} fitBounds /> : <div style={{ height: 230, borderRadius: 12, background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, display: 'grid', placeItems: 'center', color: TOKENS.textMuted, fontSize: 12.5 }}>Sin ubicaciones para mostrar</div>}
            <div style={{ position: 'absolute', right: 8, top: 8, zIndex: 500 }}><PcBtn style={{ padding: '5px 10px', fontSize: 12 }} onClick={onIrRutas}>Ver en Rutas ›</PcBtn></div>
          </div>
        </div>}
    </div>);
}
// Por decidir (20/11/2026): tarjetas en fila con lo que espera una decisión del admin.
// Solo aparecen las que tienen algo; si no hay nada, el bloque no se muestra.
function PcPorDecidir({ regs, ir }) {
  const sols = (window.loadSolicitudesAnulacion ? window.loadSolicitudesAnulacion() : []).filter((x) => x.estado === 'espera');
  const cors = (window.loadCorrecciones ? window.loadCorrecciones() : []).filter((x) => x.estado === 'espera');
  const rines = typeof servPendientes === 'function' ? servPendientes(regs) : [];
  const alerta = (window.loadCatServicios ? window.loadCatServicios().alerta : 5) || 5;
  const rojos = rines.filter((x) => x.dias >= alerta).length;
  const sinSv = regs.filter((r) => r._estado === 'ent' && typeof servResumen === 'function' && (() => { const s = servResumen(r); return s.n > 0 && !s.con; })());
  // Mismo conteo que el menú lateral (Catálogos › Por revisar).
  const tns = (window.loadCatalogo ? window.loadCatalogo().revisar : null) || (window.catPendientesMensajero ? window.catPendientesMensajero() : []);
  const placaDe = (x) => x.placa || ((regs.find((r) => r.id === x.ticketId) || {}).placa);
  const aPlaca = (L) => L.length === 1 && placaDe(L[0]) ? ir('registros', { q: placaDe(L[0]) }) : ir('registros');
  const tiles = [
  sols.length && { k: 'anu', n: sols.length, ico: I.ban(16, TOKENS.anulado), bg: TOKENS.anuladoBg, t: sols.length === 1 ? 'Solicitud de anulación' : 'Solicitudes de anulación', go: () => aPlaca(sols) },
  cors.length && { k: 'cor', n: cors.length, ico: I.pencil(15, '#8a5a00'), bg: '#fdf0d5', t: cors.length === 1 ? 'Corrección de entrega' : 'Correcciones de entrega', go: () => aPlaca(cors) },
  rines.length && { k: 'aut', n: rines.length, ico: <span style={{ color: PAUSA_COLOR.fg, display: 'inline-flex' }}><PcPausaIco s={9} /></span>, bg: PAUSA_COLOR.bg, t: <>{rines.length === 1 ? 'Rin esperando autorización' : 'Rines esperando autorización'}{rojos > 0 && <span style={{ color: TOKENS.danger, fontWeight: 700 }}> · {rojos} en rojo</span>}</>, ver: 'Novedades', go: () => ir('seguimiento') },
  sinSv.length && { k: 'sv', n: sinSv.length, ico: <b style={{ color: '#7f6000', fontSize: 15 }}>$</b>, bg: '#fff2cc', t: sinSv.length === 1 ? 'Entregada sin servicios' : 'Entregadas sin servicios', go: () => ir('registros', { tab: 'ent', sinsv: true }) },
  tns.length && { k: 'tal', n: tns.length, ico: I.building ? I.building(16, TOKENS.primary) : '⌂', bg: TOKENS.primaryBg, t: tns.length === 1 ? 'Taller nuevo por revisar' : 'Talleres nuevos por revisar', ver: 'Catálogos', go: () => ir('catalogos-revisar') }].
  filter(Boolean);
  if (!tiles.length) return null;
  return <div style={{ marginBottom: 14 }}>
    <div style={{ ...pcLbl, margin: '2px 2px 8px' }}>Por decidir</div>
    <div style={{ display: 'grid', gridTemplateColumns: `repeat(${Math.max(tiles.length, 4)}, 1fr)`, gap: 10 }}>
      {tiles.map((x) =>
      <button key={x.k} type="button" onClick={x.go} className="pc-fila" style={{ ...pcCard, textAlign: 'left', padding: '13px 14px', cursor: 'pointer', fontFamily: 'inherit', color: TOKENS.text, display: 'flex', flexDirection: 'column' }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}><span style={{ width: 30, height: 30, borderRadius: 9, background: x.bg, display: 'grid', placeItems: 'center' }}>{x.ico}</span><b style={{ fontSize: 24, fontWeight: 800 }}>{x.n}</b></span>
          <span style={{ fontSize: 12.5, color: TOKENS.textMuted, marginTop: 6, lineHeight: 1.35, flex: 1 }}>{x.t}</span>
          <span style={{ fontSize: 12.5, fontWeight: 700, color: TOKENS.primary, marginTop: 8 }}>{x.ver || 'Ver'} ›</span>
        </button>)}
    </div>
  </div>;
}
function PcInicio({ regs, ir }) {
  const [abierta, setAbierta] = React.useState(() => { try { return localStorage.getItem('rodando.pc.rutaAbierta') === '1'; } catch (e) { return false; } });
  const toggle = () => setAbierta((v) => { try { localStorage.setItem('rodando.pc.rutaAbierta', v ? '0' : '1'); } catch (e) {} return !v; });
  const ms = window.mensajerosApp ? window.mensajerosApp() : [];
  const pend = regs.filter((r) => r._estado === 'pend');
  // 21/11/2026: igual que Registros — las placas en pausa van aparte, no dentro de "En plazo".
  const c = [0, 1, 2, 3].map((k) => pend.filter((r) => r._est && !r._est.pausa && r._est.orden === k).length);
  const nPausa = pend.filter((r) => r._est && r._est.pausa).length;
  const hoy = fechaDDMMYYYY();
  const paradas = window.loadParadas ? window.loadParadas() : [];
  const sinPlanear = paradas.filter((p) => p.tipo === 'recoger' && p.estado === 'solicitud');
  const enRuta = paradas.filter((p) => p.tipo === 'recoger' && p.fecha === hoy && ['pendiente', 'en_curso'].includes(p.estado));
  const hace = (ts) => window.relTime ? window.relTime(ts) : '';
  const tal = {};
  pend.forEach((r) => { const k = r.taller + (r.sede ? ' · ' + r.sede : ''); const o = tal[k] = tal[k] || { n: 0, c: [0, 0, 0, 0, 0], taller: r.taller }; o.n++; if (r._est) o.c[r._est.pausa ? 4 : r._est.orden]++; });
  const tt = Object.entries(tal).sort((a, b) => b[1].c[0] - a[1].c[0] || b[1].c[1] - a[1].c[1] || b[1].c[2] - a[1].c[2] || b[1].n - a[1].n);
  const th = { ...pcLbl, textAlign: 'center', padding: '9px 10px', background: TOKENS.surfaceLow, borderBottom: `1px solid ${TOKENS.border}` };
  return (
    <>
      {(ms.length ? ms : [{ usuario: 'cesar', nombre: 'César' }]).map((m) => <PcRutaMensajero key={m.usuario} m={m} abierta={abierta} onToggle={toggle} onIrRutas={() => ir('rutas')} />)}
      <PcPorDecidir regs={regs} ir={ir} />
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <div style={{ ...pcCard, padding: 16 }}>
          <div style={{ display: 'flex', alignItems: 'baseline' }}><div style={{ ...pcLbl, flex: 1 }}>Por entregar</div><b style={{ fontSize: 22 }}>{pend.length}</b><span style={{ fontSize: 12, color: TOKENS.textMuted, marginLeft: 6 }}>placas</span></div>
          <div style={{ display: 'flex', height: 10, borderRadius: 99, overflow: 'hidden', background: TOKENS.surfaceLow, margin: '10px 0 12px' }}>{c.map((n, k) => <span key={k} style={{ width: (pend.length ? n / pend.length * 100 : 0) + '%', background: PC_EST[k][3] }} />)}<span style={{ width: (pend.length ? nPausa / pend.length * 100 : 0) + '%', background: PAUSA_COLOR.solid }} /></div>
          {PC_EST.map((e, k) =>
          <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0', borderTop: `1px solid ${TOKENS.border}`, fontSize: 13 }}>
              <span style={{ width: 9, height: 9, borderRadius: 99, background: e[3] }} />{e[0]}<b style={{ marginLeft: 'auto' }}>{c[k]}</b>
              <PcBtn style={{ padding: '5px 10px', fontSize: 12 }} onClick={() => ir('registros', { tab: 'pend', est: k })}>Ver ›</PcBtn>
            </div>)}
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0', borderTop: `1px solid ${TOKENS.border}`, fontSize: 13 }}>
            <span style={{ width: 9, height: 9, borderRadius: 99, background: PAUSA_COLOR.solid }} />En pausa<b style={{ marginLeft: 'auto' }}>{nPausa}</b>
            <PcBtn style={{ padding: '5px 10px', fontSize: 12 }} onClick={() => ir('registros', { tab: 'pend', est: 'p' })}>Ver ›</PcBtn>
          </div>
        </div>
        <div style={{ ...pcCard, padding: 16 }}>
          <div style={{ display: 'flex', alignItems: 'baseline' }}><div style={{ ...pcLbl, flex: 1 }}>Por recoger</div><b style={{ fontSize: 22 }}>{sinPlanear.length + enRuta.length}</b><span style={{ fontSize: 12, color: TOKENS.textMuted, marginLeft: 6 }}>solicitudes</span></div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, margin: '10px 0 4px' }}>
            <div style={{ background: TOKENS.surfaceLow, borderRadius: 10, padding: '9px 11px' }}><b style={{ fontSize: 18 }}>{sinPlanear.length}</b><span style={{ display: 'block', fontSize: 12, color: TOKENS.textMuted }}>sin planear (en la bandeja)</span></div>
            <div style={{ background: TOKENS.surfaceLow, borderRadius: 10, padding: '9px 11px' }}><b style={{ fontSize: 18 }}>{enRuta.length}</b><span style={{ display: 'block', fontSize: 12, color: TOKENS.textMuted }}>en la ruta de hoy</span></div>
          </div>
          {[...sinPlanear.map((p) => ({ p, ruta: false })), ...enRuta.map((p) => ({ p, ruta: true }))].slice(0, 6).map(({ p, ruta }) =>
          <div key={p.id} style={{ display: 'flex', gap: 10, alignItems: 'center', padding: '9px 0', borderTop: `1px solid ${TOKENS.border}`, fontSize: 13 }}>
              <div style={{ flex: 1, minWidth: 0 }}><b>{p.taller}{p.sede ? ' · ' + p.sede : ''}</b><span style={{ display: 'block', fontSize: 11.5, color: TOKENS.textMuted, marginTop: 2 }}>{(p.placas || []).length ? `${p.placas.length} ${p.placas.length === 1 ? 'placa' : 'placas'} · ${p.placas.join(', ')}` : p.referencia || ''}</span></div>
              <span style={{ fontSize: 11.5, color: TOKENS.textMuted, whiteSpace: 'nowrap' }}>{ruta ? 'En la ruta · ' : ''}{hace(p.createdAt)}</span>
            </div>)}
          {!sinPlanear.length && !enRuta.length && <div style={{ fontSize: 13, color: TOKENS.textMuted, padding: '10px 0' }}>No hay recogidas pendientes.</div>}
          <PcBtn style={{ width: '100%', marginTop: 8, padding: 7, fontSize: 12.5 }} onClick={() => ir('rutas')}>Planear en Rutas ›</PcBtn>
        </div>
      </div>
      <div style={{ ...pcCard, padding: 16, marginTop: 14 }}>
        <div style={pcLbl}>Por entregar, por taller <span style={{ textTransform: 'none', letterSpacing: 0, fontWeight: 600, color: TOKENS.textSubtle }}>· los más urgentes primero</span></div>
        {!tt.length ? <div style={{ fontSize: 13, color: TOKENS.textMuted, paddingTop: 10 }}>No hay placas por entregar.</div> :
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, marginTop: 8 }}>
            <thead><tr><th style={{ ...th, textAlign: 'left' }}>Taller · sede</th>{PC_EST.map((e) => <th key={e[0]} style={th}>{e[0] === 'Vencido' ? 'Vencidas' : e[0] === 'Retrasado' ? 'Retrasadas' : e[0]}</th>)}<th style={th}>En pausa</th><th style={th}>Total</th><th style={th}></th></tr></thead>
            <tbody>{tt.map(([k, o]) =>
            <tr key={k} onClick={() => ir('registros', { tab: 'pend', taller: o.taller })} style={{ cursor: 'pointer' }} className="pc-fila">
                  <td style={{ padding: '9px 10px', borderBottom: `1px solid ${TOKENS.border}` }}><b>{k}</b></td>
                  {o.c.map((n, i) => <td key={i} style={{ textAlign: 'center', padding: '9px 10px', borderBottom: `1px solid ${TOKENS.border}` }}>{n ? <span style={{ display: 'inline-block', minWidth: 26, fontSize: 11.5, fontWeight: 500, borderRadius: 999, padding: '3px 8px', background: i === 4 ? PAUSA_COLOR.bg : PC_EST[i][1], color: i === 4 ? PAUSA_COLOR.fg : PC_EST[i][2] }}>{n}</span> : <span style={{ color: TOKENS.textSubtle }}>–</span>}</td>)}
                  <td style={{ textAlign: 'center', fontWeight: 800, borderBottom: `1px solid ${TOKENS.border}` }}>{o.n}</td>
                  <td style={{ textAlign: 'right', color: TOKENS.primary, fontWeight: 800, padding: '9px 10px', borderBottom: `1px solid ${TOKENS.border}` }}>Ver ›</td>
                </tr>)}</tbody>
          </table>}
      </div>
    </>);
}

// ─── Registros ───────────────────────────────────────────────────────────
// Detalle de una placa (14/11/2026): encabezado con placa y consecutivo en recuadros (como la
// Business Suite), recorrido Recogida → En Salvallantas → Entregada, ítems que se expanden,
// fotos, entrega e historial. Colores de Rodando.
const PC_ITEM_META = { rin: ['Rin', 'Rines', '⚙'], llanta: ['Llanta', 'Llantas', '◯'], valvula: ['Válvula', 'Válvulas', '⬡'] };
function pcItemAttrs(it) {
  if (it.tipo === 'rin') return [['Tamaño', it.tamano ? it.tamano + '"' : ''], ['Material', it.material], ['Huecos', it.huecos], ['Tapa', it.tapa], ['Tapa válvula', it.tapaValvula]];
  if (it.tipo === 'llanta') return [['Marca', it.marca], ['Referencia', it.referencia], ['DOT', it.dot], ['Calidad', it.calidad]];
  if (it.tipo === 'valvula') return [['Sensor', it.valvulaSensor]];
  return [];
}
// Ítem al estilo de la app (14/11/2026): etiqueta ITEM 01, datos en dos columnas y tablitas
// de DOT y Calidad. Siempre abierto, sin íconos ni botones (la ficha es de consulta).
function pcRepartos(it, campo, excKey, excCampo) {
  const exc = (it[excKey] || []).filter((x) => x && x[excCampo]);
  const total = Number(it.cantidad) || 0;
  const resto = total - exc.reduce((a, x) => a + (Number(x.count) || 0), 0);
  const out = [];
  if (it[campo]) out.push([it[campo], resto > 0 ? resto : total]);
  exc.forEach((x) => out.push([x[excCampo], Number(x.count) || 0]));
  return out;
}
function PcItemCard({ it, n }) {
  const m = PC_ITEM_META[it.tipo] || [it.tipo, it.tipo, '•'];
  const attrs = [['Cantidad', it.cantidad], ...(it.tipo === 'rin' ? [['Tamaño', it.tamano ? it.tamano + '"' : ''], ['Material', it.material], ['Huecos', it.huecos], ['Tapa', it.tapa], ['T. válvula', it.tapaValvula]] :
    it.tipo === 'llanta' ? [['Marca', it.marca], ['Referencia', it.referencia]] : it.tipo === 'valvula' ? [['Sensor', it.valvulaSensor]] : [])].filter(([, v]) => v !== '' && v != null);
  const dots = it.tipo === 'llanta' ? pcRepartos(it, 'dot', 'dotExceptions', 'dot') : [];
  const cals = it.tipo === 'llanta' ? pcRepartos(it, 'calidad', 'calidadExceptions', 'calidad') : [];
  const unidad = (k) => `${k} ${k === 1 ? m[0].toLowerCase() : m[1].toLowerCase()}`;
  const tablita = (titulo, filas, mono) =>
  <div style={{ marginTop: 10, background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 10, overflow: 'hidden' }}>
      <div style={{ ...pcLbl, fontSize: 10, background: TOKENS.surfaceContainer, padding: '6px 12px' }}>{titulo}</div>
      {filas.map(([v, k], i) => <div key={i} style={{ display: 'flex', justifyContent: 'space-between', gap: 10, padding: '7px 12px', borderTop: i ? `1px dashed ${TOKENS.border}` : 'none', fontSize: 13 }}><b style={{ fontFamily: mono ? pcMono : 'inherit' }}>{v}</b><span style={{ color: TOKENS.textMuted, fontWeight: 600 }}>{unidad(k)}</span></div>)}
    </div>;
  return (
    <div style={{ background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 14, padding: '12px 14px', marginBottom: 10 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
        <span style={{ background: TOKENS.primary, color: '#fff', fontSize: 10.5, fontWeight: 800, letterSpacing: '0.05em', padding: '3px 9px', borderRadius: 999 }}>ITEM {String(n).padStart(2, '0')}</span>
        <b style={{ fontSize: 14.5 }}>{m[0]}</b>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', columnGap: 22 }}>
        {attrs.map(([k, v]) => <div key={k} style={{ padding: '5px 0', borderBottom: `1px dashed ${TOKENS.border}`, fontSize: 13, color: TOKENS.textMuted }}>{k}: <b style={{ color: TOKENS.text }}>{v}</b></div>)}
      </div>
      {dots.length > 0 && tablita('DOT', dots, true)}
      {cals.length > 0 && tablita('Calidad', cals)}
      {it.observaciones && <div style={{ marginTop: 8, fontSize: 12.5, color: TOKENS.textMuted }}>📝 {it.observaciones}</div>}
    </div>);
}
function pcHistorial(r) {
  const fx = (f) => pcFechaCorta(f);
  const f12 = (h) => h ? (window.formatHora12 ? window.formatHora12(h) : h) : '';
  const ev = [];
  const llego = r.comoLlego === 'otra-ciudad' ? `Llegó de otra ciudad${r.transportadoraLlegada ? ' · ' + r.transportadoraLlegada : ''}${r.guiaLlegada ? ' · guía ' + r.guiaLlegada : ''}` : r.comoLlego === 'taller' ? 'Lo trajo el taller' : (r.recogidoPorNombre || '');
  ev.push({ t: r.comoLlego && r.comoLlego !== 'mensajero' ? 'Recibido' : 'Recogido', w: [llego, [fx(r.fecha), f12(r.horaRecogida)].filter(Boolean).join(' · ')].filter(Boolean).join(' · '), extra: r.digitadoPorNombre ? `Digitó ${r.digitadoPorNombre} desde el PC` : '' });
  const id = r.id;
  const anu = window.anulacionFor ? window.anulacionFor(id) : null;
  const sols = window.loadSolicitudesAnulacion ? window.loadSolicitudesAnulacion().filter((x) => x.ticketId === id) : [];
  sols.filter((x) => x.estado === 'espera').forEach((x) => ev.push({ t: 'Pidió anular', nov: true, w: [x.porNombre || 'El mensajero', [fx(x.fecha), f12(x.hora)].filter(Boolean).join(' · ')].filter(Boolean).join(' · '), extra: [x.motivo, x.nota ? `"${x.nota}"` : ''].filter(Boolean).join(' · '), aten: true }));
  ((anu && anu.historial) || []).forEach((e) => ev.push({ t: e.tipo === 'anulado' ? 'Anulado' : 'Reactivado', nov: true, anu: e.tipo === 'anulado', 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}"` : ''].filter(Boolean).join(' · ') : '' }));
  sols.filter((x) => x.estado === 'rechazada').forEach((x) => ev.push({ t: 'Anulación rechazada', nov: true, w: [x.respondidoPorNombre, 'pidió ' + (x.porNombre || 'el mensajero')].filter(Boolean).join(' · '), extra: x.respuesta ? `"${x.respuesta}"` : '' }));
  const e = r._ent;
  if (e) ev.push({ t: 'Entregado', w: [e.entregadoPorNombre, [fx(e.fechaEntrega), f12(e.horaEntrega)].filter(Boolean).join(' · ')].filter(Boolean).join(' · '), extra: e.despachado ? `Transportadora ${e.transportadora || ''}${e.guia ? ' · guía ' + e.guia : ''}` : e.factura ? `${e.comprobanteTipo || 'Factura'} ${e.factura}` : '' });
  else if (r._estado === 'pend') ev.push({ t: 'Entrega', w: 'Pendiente', pend: true });
  return ev;
}
// Ficha de una placa (14/11/2026, playground "Ficha PC"): Placa | Orden; tablita de datos (con
// entrega y factura/remisión si ya se entregó); historial = recorrido con fecha, hora y quién,
// más un recuadro de novedades (anulaciones) solo si las hay; ítems; fotos.
// Botones: Entregar (verde) · Editar (blanco) · "Anular registro" en texto rojo.
function PcDetalle({ r, onClose, onEntregar, onEditar, onAnular, onReactivar, toast, soloVer }) {
  const [lb, setLb] = React.useState(null);
  const [decision, setDecision] = React.useState(null);
  const [editSv, setEditSv] = React.useState(false);
  const [dlg, setDlg] = React.useState(null); // 'deshacer' | 'garantia' | 'entGar' | {ticket}
  const [entTab, setEntTab] = React.useState(null); // 'ent' | 'gar'
  const svCtrl = React.useRef(null);
  const garantias = typeof garantiasDe === 'function' ? garantiasDe(r.id) : [];
  const deshechas = typeof deshechasDe === 'function' ? deshechasDe(r.id) : [];
  const fotos = [...(r.fotosPlaca || []), ...(r.items || []).flatMap((it) => (it.photos || []).filter((x) => typeof x === 'string' && x.startsWith('data:')))].filter(Boolean);
  const e = r._ent;
  const fotosEnt = e ? [...(e.fotos || []), ...(e.guiaFotos || []), ...(e.sinReparar || []).map((x) => x.foto)].filter((x, k, a) => x && a.indexOf(x) === k) : [];
  const f12 = (h) => h ? (window.formatHora12 ? window.formatHora12(h) : h) : '';
  // 25/11/2026: una por una, con la confirmación de descarga de claude.ai.
  const bajar = async (arr, pref) => { for (let i = 0; i < arr.length; i++) { try { const b = await (await fetch(arr[i])).blob(); if (!(await pcDescargar(b, `${r.placa}_${pref}_${i + 1}.jpg`))) break; } catch (e) { window.open(arr[i], '_blank', 'noopener'); } } };
  const Lb = window.PhotoLightbox, Dec = window.DecisionAnulacionModal;
  const sol = window.loadSolicitudesAnulacion ? window.loadSolicitudesAnulacion().find((x) => x.ticketId === r.id && x.estado === 'espera') : null;
  const h4 = (txt, der) => <div style={{ display: 'flex', alignItems: 'center', gap: 8, margin: '20px 0 10px' }}><span style={{ ...pcLbl, flex: 1 }}>{txt}</span>{der}</div>;
  const galeria = (arr) => <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6 }}>{arr.map((u, i) => <img key={i} src={u} onClick={() => setLb({ fotos: arr, i })} style={{ width: '100%', aspectRatio: '1', objectFit: 'cover', borderRadius: 9, cursor: 'zoom-in', border: `1px solid ${TOKENS.border}` }} />)}</div>;
  const bajarBtn = (arr, pref) => <PcBtn style={{ padding: '5px 10px', fontSize: 12 }} onClick={() => bajar(arr, pref)}>⇩ Descargar todas</PcBtn>;
  const dias = r._estado === 'ent' ? r._dias : r._est ? r._est.dias : null;
  const diasTxt = (d) => `${d} ${d === 1 ? 'día hábil' : 'días hábiles'}`;
  const sub = (t) => <span style={{ fontWeight: 500, color: TOKENS.textSubtle, fontSize: 12.5 }}>{t}</span>;
  const anuEv = r._estado === 'anu' ? ((r._anu && r._anu.historial) || []).filter((x) => x.tipo === 'anulado').pop() : null;
  // Servicios y pausas por rin (16/11/2026)
  const sv = typeof servDe === 'function' ? servDe(r) : { rines: [] };
  const enEspera = sv.rines.map((x, i) => ({ x, i })).filter((o) => o.x.aut && o.x.aut.estado === 'espera');
  const pz = r._estado === 'pend' && enEspera.length > 0;
  const reIni = r._estado !== 'anu' && typeof reinicioPlazo === 'function' ? reinicioPlazo(r.id) : null;
  const enProceso = sv.rines.map((x, i) => i).filter((i) => !(sv.rines[i].aut && sv.rines[i].aut.estado === 'espera'));
  const sums = window.suministrosDeReg ? window.suministrosDeReg(r) : [];
  // Tablita de datos
  const filas = [
    ['Aseguradora', r.aseguradora],
    ['Taller', r.taller],
    ['Sede', r.sede || '—'],
    ...(r._estado !== 'anu' ? [['Prioridad', r.encargo && !r._gar ? <>{window.ChipEncargo && <window.ChipEncargo />}{r.express && <PcChipExpress solo />}{sub(r.fechaLimite ? `para el ${r.fechaLimite}` : `plazo ${pcSlaDe(!!r.express)} días hábiles`)}</> : r._gar ? <><PcChipGarantia />{sub(`plazo ${(loadCatServicios().slaGarantia || 2)} días hábiles`)}{r.express && <PcChipExpress solo />}</> : r.express ? <><PcChipExpress />{sub(`plazo ${pcSlaDe(true)} días hábiles`)}</> : <span style={{ fontWeight: 500, color: TOKENS.textMuted }}>Normal · plazo {pcSlaDe(false)} días hábiles</span>]] : []),
    ...(r.nota ? [['Nota', <span style={{ fontWeight: 500 }}>{r.nota}</span>]] : []),
    ...(r.cliente ? [['Cliente', <span style={{ display: 'flex', flexDirection: 'column' }}><span>{r.cliente.nombre} {sub(r.cliente.telefono)}</span><span style={{ fontWeight: 500, color: TOKENS.textMuted, fontSize: 12.5 }}>{r.cliente.direccion}</span></span>]] : []),
    ...(sums.length ? [['Recogido', pcItemsTxt(r.items)], ['Se entrega', <>{pcItemsTxt(r.items)} <span style={{ color: '#0e7490' }}>+ {sumLista(sums)}</span></>]] : []),
    ['Estado', <>{r._est && r._est.pausa && window.pcVerSeguimiento ? <span role="button" title="Ver en Novedades" onClick={() => window.pcVerSeguimiento(r.placa, true)} style={{ cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6 }}>{pcEstadoCelda(r)}<span style={{ fontSize: 12, fontWeight: 600, color: TOKENS.primary }}>Ver ›</span></span> : pcEstadoCelda(r)}{r._gar && r._est && <PcChipEst k={r._est.orden} />}</>],
    ['Días hábiles', r._estado === 'anu' ? '—' : <><b>{dias != null ? dias : 0}</b> {sub((r._gar ? `desde que volvió por garantía (${r._gar.fecha})` : pz ? `contados · detenido desde el ${enEspera[0].x.aut.desde} por el rin ${enEspera.map((o) => o.i + 1).join(', ')}` : reIni ? `contados desde la autorización del ${reIni.fecha}` : r._estado === 'ent' ? 'de la recogida a la entrega' : 'en Salvallantas'))}</>]];
  // Entrega (19/11/2026): sale de la tablita y va a su propia sección, con interruptor si hubo garantía.
  const filasEnt = [];
  if (e) {
    const dE = r._gar ? r._diasPrimera : r._dias; const mE = pcSlaDe(!!e.express || !!r.express);
    filasEnt.push(['Entregada', <>{[pcFechaCorta(e.fechaEntrega), f12(e.horaEntrega)].filter(Boolean).join(' · ')} {e.entregadoPorNombre && sub(e.entregadoPorNombre)}</>]);
    filasEnt.push(['Cómo', e.despachado ? 'Transportadora' : 'Directo']);
    if (e.despachado) filasEnt.push(['Transportadora · guía', <>{e.transportadora || '—'}{e.guia && <> · <span style={{ fontFamily: pcMono, fontWeight: 800 }}>{e.guia}</span></>}</>]);
    else filasEnt.push([e.comprobanteTipo === 'Remisión' ? 'Remisión' : 'Factura', e.factura ? <><span style={{ fontFamily: pcMono, fontWeight: 800, fontSize: 14.5 }}>{pcComprobante(e)}</span>{e.recibePor && sub('recibió ' + e.recibePor)}</> : '—']);
    if ((e.sinReparar || []).length) filasEnt.push(['Novedad', <span style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>{e.sinReparar.map((x) => <span key={x.i} style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>Rin {x.i + 1} {window.PcChipNovedad ? <window.PcChipNovedad t={/autoriz/i.test(x.motivo || '') ? 'na' : 'nr'} /> : null} {sub(x.motivo + ' · no se cobra')}</span>)}</span>]);
    if ((e.suministros || []).length) filasEnt.push(['Se entregó además', <span style={{ color: '#0e7490' }}>{window.sumLista ? window.sumLista(e.suministros) : ''}</span>]);
    filasEnt.push(['Días hábiles', <><b>{dE || 0}</b> {sub('de la recogida a la entrega')}</>]);
  }
  // Recorrido
  const llego = pcComoLlego(r);
  const pasos = [
    { t: r.encargo ? 'Asignado' : r.comoLlego && r.comoLlego !== 'mensajero' ? 'Recibida' : 'Recogida', f: pcFechaCorta(r.fecha), h: f12(r.horaRecogida), q: [llego !== '—' ? llego : '', r.digitadoPorNombre && !r.encargo ? `Digitó ${r.digitadoPorNombre} (PC)` : ''].filter(Boolean), st: 'ok' },
    { t: 'En Salvallantas', f: pcFechaCorta(r.fecha), h: '', q: pz ? [`${enProceso.length ? `Rin ${enProceso.map((i) => i + 1).join(', ')} en proceso · ` : ''}rin ${enEspera.map((o) => o.i + 1).join(', ')} en pausa`] : dias != null && r._estado !== 'anu' ? [diasTxt(dias)] : [], st: pz ? 'pa' : r._estado === 'pend' ? 'now' : 'ok' },
    r._estado === 'anu' ?
    { t: 'Anulada', f: anuEv ? pcFechaCorta(anuEv.fecha) : '', h: anuEv ? f12(anuEv.hora) : '', q: anuEv && anuEv.por ? [anuEv.por] : [], st: 'anu' } :
    { t: 'Entregada', f: e ? pcFechaCorta(e.fechaEntrega) : 'Pendiente', h: e ? f12(e.horaEntrega) : '', q: e && e.entregadoPorNombre ? [e.entregadoPorNombre] : [], st: e ? 'ok' : 'no' }];
  if (garantias.length && r._estado !== 'anu') { const g = garantias[garantias.length - 1]; pasos.push({ t: 'Garantía', f: g.fecha, h: '', q: [g.estado === 'entregada' ? `Entregada ${g.entrega && g.entrega.fecha || ''}`.trim() : `Se espera ${garFechaEstimada(g)}`], st: 'gar' }); }
  const dot = (p, i) => <span style={{ width: 30, height: 30, borderRadius: 99, display: 'grid', placeItems: 'center', fontSize: 13, fontWeight: 800, margin: '0 auto 7px', position: 'relative', zIndex: 1, boxSizing: 'border-box',
    background: p.st === 'gar' ? '#0e7490' : p.st === 'ok' ? TOKENS.primary : p.st === 'anu' ? TOKENS.anulado : p.st === 'pa' ? PAUSA_COLOR.solid : '#fff', color: p.st === 'ok' || p.st === 'anu' || p.st === 'gar' ? '#fff' : p.st === 'pa' ? '#fff' : p.st === 'now' ? TOKENS.primary : TOKENS.textSubtle,
    border: p.st === 'ok' || p.st === 'anu' || p.st === 'pa' || p.st === 'gar' ? 'none' : p.st === 'now' ? `2px solid ${TOKENS.primaryBorder}` : `2px dashed ${TOKENS.borderInput}` }}>{p.st === 'gar' ? '↺' : p.st === 'ok' ? I.check(15, '#fff') : p.st === 'anu' ? '✕' : p.st === 'pa' ? <PcPausaIco s={10} /> : i + 1}</span>;
  // 21/11/2026: las pausas salen de aquí y van en su propio campo (PcPausasFicha).
  const novedades = [...pcHistorial(r).filter((x) => x.nov),
  ...deshechas.flatMap((d) => [{ t: 'Entregada (deshecha)', w: [pcFechaCorta(d.entrega.fechaEntrega), d.entrega.entregadoPorNombre, pcFacturaTxt(d.entrega)].filter(Boolean).join(' · '), tachado: true },
    { t: 'Entrega deshecha', w: [d.fecha, d.por, d.motivo, d.nota && `"${d.nota}"`].filter(Boolean).join(' · '), aten: true }]),
  ...garantias.flatMap((g) => [{ t: `↺ Garantía · rin ${g.rines.map((i) => i + 1).join(', ')}`, w: [g.fecha, g.porNombre, g.motivo, g.desc && `"${g.desc}"`, `${(g.fotos || []).length} fotos`].filter(Boolean).join(' · '), gar: true },
    g.estado === 'entregada' ? { t: 'Garantía entregada', w: [g.entrega.fecha, g.entrega.porNombre].filter(Boolean).join(' · '), ok: true } : { t: 'Entrega de la garantía', w: `Pendiente · se espera para el ${garFechaEstimada(g)}`, pend: true }])];
  const resumen = (() => { const n = (t) => (r.items || []).filter((i) => i.tipo === t).reduce((a, i) => a + (Number(i.cantidad) || 0), 0); return [['rin', n('rin')], ['llanta', n('llanta')], ['valvula', n('valvula')]].filter(([, v]) => v); })();
  const encabezado =
  <div style={{ display: 'flex', gap: 10 }}>
      {[['Placa', r.placa], ['Orden', r.codigo]].map(([k, v]) =>
    <div key={k} style={{ flex: '0 0 auto', minWidth: 130, border: `1px solid ${TOKENS.border}`, borderRadius: 12, padding: '9px 14px', background: TOKENS.surfaceLow }}>
          <span style={{ ...pcLbl, fontSize: 9.5 }}>{k}</span>
          <b style={{ display: 'block', fontFamily: pcMono, fontSize: 22, fontWeight: 800, letterSpacing: '0.04em', marginTop: 1 }}>{v}</b>
        </div>)}
      {window.InsigniasPlaca && (r.express || r._gar) && <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, flexShrink: 0, paddingRight: 14, paddingBottom: 8 }}><window.InsigniasPlaca ticket={{ ...r, id: r.id }} alto={30} /></div>}
    </div>;
  const tabla = (fs) => <div style={{ border: `1px solid ${TOKENS.border}`, borderRadius: 12, overflow: 'hidden' }}>
      {fs.map(([k, v], i) =>
    <div key={k} style={{ display: 'grid', gridTemplateColumns: '150px 1fr', borderTop: i ? `1px solid ${TOKENS.border}` : 'none' }}>
          <span style={{ background: TOKENS.surfaceLow, padding: '8px 12px', fontSize: 12, color: TOKENS.textMuted, fontWeight: 700 }}>{k}</span>
          <span style={{ padding: '8px 12px', fontWeight: 600, fontSize: 13.5, display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', minWidth: 0 }}>{v}</span>
        </div>)}
    </div>;
  const garsOrd = [...garantias].reverse();
  // Secciones en tarjetas (19/11/2026), como en el celular: fondo gris y cada sección en su tarjeta blanca.
  const card = (titulo, der, children, primera) => <div style={{ background: TOKENS.surface, border: '1px solid #dfe5ee', borderRadius: 14, padding: 14, marginTop: primera ? 0 : 12 }}>
      {titulo && <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}><b style={{ fontSize: 14, fontWeight: 700, flex: 1 }}>{titulo}</b>{der}</div>}
      {children}
    </div>;
  const tabEnt = garantias.length ? entTab || 'gar' : 'ent';
  const btnGrande = { padding: '11px 18px', fontSize: 14, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8 };
  const pie = soloVer && !editSv ? <><span style={{ flex: 1 }} /><PcBtn onClick={onClose}>Cerrar</PcBtn></> : editSv ? <><span style={{ flex: 1, fontSize: 12.5, color: TOKENS.textMuted, alignSelf: 'center' }}>Editando servicios</span><PcBtn style={btnGrande} onClick={() => svCtrl.current && svCtrl.current.cancelar()}>Cancelar</PcBtn><PcBtn tone="p" style={btnGrande} onClick={() => svCtrl.current && svCtrl.current.guardar()}>Guardar servicios</PcBtn></> :
  r._gar ? <><PcBtn tone="p" style={{ ...btnGrande, minWidth: 190 }} onClick={() => setDlg('entGar')}>{I.check(16, '#fff')} Entregar garantía</PcBtn><PcBtn style={btnGrande} onClick={onEditar}>{I.pencil(16, TOKENS.primary)} Editar</PcBtn><span style={{ flex: 1 }} /></> :
  r._estado === 'ent' ? <><PcBtn style={btnGrande} onClick={onEditar}>{I.pencil(16, TOKENS.primary)} Editar</PcBtn><PcBtn style={{ ...btnGrande, color: '#0e7490', border: '1px solid #b3e3ec' }} onClick={() => setDlg('garantia')}>↺ Registrar garantía</PcBtn><span style={{ flex: 1 }} /><button type="button" onClick={() => setDlg('deshacer')} style={{ background: TOKENS.surface, border: `1.5px solid ${TOKENS.borderInput}`, color: TOKENS.danger, borderRadius: 10, fontFamily: 'inherit', fontWeight: 700, fontSize: 13.5, cursor: 'pointer', padding: '9px 14px', display: 'inline-flex', alignItems: 'center', gap: 7 }}>{I.x(15, TOKENS.danger)} Deshacer entrega</button></> :
  r._estado === 'anu' ? <><span style={{ flex: 1, fontSize: 12.5, color: TOKENS.textMuted }}>Registro anulado</span><PcBtn tone="p" onClick={onReactivar}>Reactivar</PcBtn></> :
  <>
      {r._estado === 'pend' && <span title={pz ? 'Hay rines esperando autorización' : ''}><PcBtn tone="p" disabled={pz} style={{ minWidth: 180, padding: '11px 18px', fontSize: 14, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8 }} onClick={onEntregar}>{I.check(16, '#fff')} Entregar</PcBtn></span>}
      <PcBtn style={{ padding: '11px 18px', fontSize: 14, display: 'inline-flex', alignItems: 'center', gap: 8 }} onClick={onEditar}>{I.pencil(16, TOKENS.primary)} Editar</PcBtn>
      <span style={{ flex: 1 }} />
      {r._estado === 'pend' && <button type="button" onClick={onAnular} style={{ background: TOKENS.surface, border: `1.5px solid ${TOKENS.borderInput}`, color: TOKENS.danger, borderRadius: 10, fontFamily: 'inherit', fontWeight: 700, fontSize: 13.5, cursor: 'pointer', padding: '9px 14px', display: 'inline-flex', alignItems: 'center', gap: 7 }}>{I.ban(15, TOKENS.danger)} Anular registro</button>}
    </>;
  return (
    <PcDrawer ancho={520} fondo="#eef1f6" onClose={onClose} onEsc={() => lb ? setLb(null) : decision ? setDecision(null) : onClose()} titulo={encabezado} pie={pie}>
      {card('Datos', null, tabla(filas), true)}
      {card('Historial', null, <>
      <div style={{ display: 'grid', gridTemplateColumns: `repeat(${pasos.length}, 1fr)` }}>
        {pasos.map((p, i) =>
        <div key={i} style={{ position: 'relative', textAlign: 'center', padding: '0 4px' }}>
            {i < pasos.length - 1 && <span style={{ position: 'absolute', top: 14, left: 'calc(50% + 17px)', right: 'calc(-50% + 17px)', borderTop: pasos[i + 1].st === 'ok' || pasos[i + 1].st === 'anu' || pasos[i + 1].st === 'gar' || (i === 0) ? `2px solid ${TOKENS.primary}` : `2px dashed ${TOKENS.borderInput}` }} />}
            {dot(p, i)}
            <b style={{ display: 'block', fontSize: 13, color: p.st === 'anu' ? TOKENS.anuladoText : TOKENS.text }}>{p.t}</b>
            <div style={{ fontSize: 12.5, marginTop: 3, color: p.st === 'no' ? TOKENS.textSubtle : TOKENS.text }}>{p.f}</div>
            {p.h && <div style={{ fontSize: 12, color: TOKENS.textMuted }}>{p.h}</div>}
            {p.q.map((x, j) => <div key={j} style={{ fontSize: 11.5, color: TOKENS.textSubtle, marginTop: 2, lineHeight: 1.3 }}>{x}</div>)}
          </div>)}
      </div>
      {novedades.length > 0 &&
      <div style={{ marginTop: 14, border: `1px solid ${TOKENS.border}`, borderRadius: 12, overflow: 'hidden' }}>
          {novedades.map((x, i) =>
        <div key={i} style={{ display: 'flex', gap: 10, padding: '9px 12px', fontSize: 12.5, borderTop: i ? `1px solid ${TOKENS.border}` : 'none', background: x.pz ? PAUSA_COLOR.bg : x.aten ? '#fff8e1' : x.gar ? '#eef8f6' : TOKENS.surface, opacity: x.tachado ? 0.6 : 1 }}>
              <b style={{ minWidth: 130, fontWeight: 500, textDecoration: x.tachado ? 'line-through' : 'none', color: x.pz ? PAUSA_COLOR.fg : x.aten ? '#7f6000' : x.gar ? '#0e7490' : x.pend ? TOKENS.textSubtle : x.anu ? TOKENS.anuladoText : x.ok ? TOKENS.successText : x.no ? TOKENS.dangerText : TOKENS.text }}>{x.t}</b>
              <span style={{ color: TOKENS.textMuted, lineHeight: 1.45 }}>{[x.w, x.extra].filter(Boolean).join(' · ')}</span>
            </div>)}
        </div>}
      {window.PcPausasFicha && <window.PcPausasFicha r={r} onVer={(abierta) => window.pcVerSeguimiento(r.placa, abierta)} />}
      {r._estado === 'ent' && window.CorreccionBox && <window.CorreccionBox ticketId={r.id} admin />}
      {sol &&
      <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 8 }}>
          <PcBtn style={{ padding: '7px 14px' }} onClick={() => setDecision('rechazar')}>Rechazar</PcBtn>
          <PcBtn style={{ padding: '7px 14px', background: TOKENS.anulado, color: '#fff', border: 'none' }} onClick={() => setDecision('anular')}>Anular registro</PcBtn>
        </div>}
      </>)}
      {r._estado !== 'anu' && sv.rines.length > 0 && card('Servicios y cobro', <>{!sv.guardado && <PcChip bg="#fff2cc" fg="#7f6000">Sin servicios</PcChip>}</>,
        <PcServiciosFicha key={r.id} r={r} toast={toast} ctrl={svCtrl} onEditando={setEditSv} plano />)}
      {r._estado !== 'anu' && window.PcSuministrosFicha && <window.PcSuministrosFicha r={r} toast={toast} />}
      {e && card(null, null, <>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
          {garantias.length ?
          <div style={{ display: 'inline-flex', background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 10, padding: 3, gap: 3 }}>
              {[['ent', 'Primera entrega'], ['gar', `↺ Garantía${garantias.length > 1 ? ' · ' + garantias.length : ''}`]].map(([k, l]) => { const on = tabEnt === k; return <button key={k} type="button" onClick={() => setEntTab(k)} style={{ border: 0, borderRadius: 8, padding: '6px 14px', fontFamily: 'inherit', fontSize: 13, fontWeight: 700, cursor: 'pointer', background: on ? TOKENS.surface : 'transparent', color: on ? (k === 'gar' ? '#0e7490' : TOKENS.primary) : TOKENS.textMuted, boxShadow: on ? '0 1px 3px rgba(22,35,63,.12)' : 'none' }}>{l}</button>; })}
            </div> :
          <b style={{ fontSize: 14, fontWeight: 700 }}>Entrega</b>}
          <span style={{ flex: 1 }} />
          {tabEnt === 'ent' && fotosEnt.length > 0 && bajarBtn(fotosEnt, 'soporte')}
        </div>
        {tabEnt === 'ent' ? <>
          {tabla(filasEnt)}
          <div style={{ ...pcLbl, margin: '12px 0 6px' }}>Soporte · {fotosEnt.length}</div>
          {fotosEnt.length ? galeria(fotosEnt) : <div style={{ fontSize: 12.5, color: TOKENS.textMuted }}>Sin fotos.</div>}
        </> : garsOrd.map((g, gi) => <div key={g.id} style={{ marginTop: gi ? 16 : 0 }}>
          {tabla([
          ['Rines', `Rin ${g.rines.map((i) => i + 1).join(', ')}`],
          ['Motivo', g.motivo || '—'],
          ...(g.desc ? [['Qué reclaman', <span style={{ fontWeight: 500 }}>“{g.desc}”</span>]] : []),
          ['Registrada', <>{g.fecha} {g.porNombre && sub(g.porNombre)}</>],
          g.estado === 'entregada' ? ['Entregada', <>{(g.entrega && g.entrega.fecha) || '—'} {g.entrega && g.entrega.porNombre && sub(g.entrega.porNombre)}</>] : ['Se espera', garFechaEstimada(g)]])}
          {(g.fotos || []).length > 0 && <>
            <div style={{ display: 'flex', alignItems: 'center', margin: '12px 0 6px' }}><span style={{ ...pcLbl, flex: 1 }}>Fotos · {g.fotos.length}</span>{bajarBtn(g.fotos, 'garantia')}</div>
            {galeria(g.fotos)}
          </>}
        </div>)}
      </>)}
      {card(r.encargo ? 'Encargo' : 'Recogida', <span style={{ fontSize: 12.5, fontWeight: 600, color: TOKENS.textMuted }}>{[pcFechaCorta(r.fecha), f12(r.horaRecogida), llego !== '—' ? llego : ''].filter(Boolean).join(' · ')}</span>, <>
      <div style={{ fontSize: 12.5, color: TOKENS.textMuted, margin: '-4px 0 8px' }}>{resumen.map(([t, n]) => `${n} ${n === 1 ? PC_ITEM_META[t][0].toLowerCase() : PC_ITEM_META[t][1].toLowerCase()}`).join(' · ') || 'Sin ítems'}</div>
      {(r.items || []).map((it, i) => <PcItemCard key={it.id || i} it={it} n={i + 1} />)}
      <div style={{ display: 'flex', alignItems: 'center', margin: '12px 0 6px' }}><span style={{ ...pcLbl, flex: 1 }}>Fotos · {fotos.length}</span>{fotos.length > 0 && bajarBtn(fotos, 'recogida')}</div>
      {fotos.length ? galeria(fotos) : <div style={{ fontSize: 12.5, color: TOKENS.textMuted }}>Sin fotos.</div>}
      </>)}
      {lb && Lb && ReactDOM.createPortal(<Lb photos={lb.fotos} index={lb.i} onIndex={(i) => setLb({ ...lb, i })} onClose={() => setLb(null)} title={r.placa} />, document.body)}
      {decision && sol && Dec && <Dec solicitudId={sol.id} tipo={decision} onDone={() => { setDecision(null); pcAvisar(); }} onDismiss={() => setDecision(null)} />}
      {dlg === 'deshacer' && <PcDialogo tono="y" icono="↶" titulo="Deshacer entrega" ticket={r} msg={`Vuelve a Por entregar con su plazo original. La entrega queda tachada en el historial; no se borra.`} confirmar="Deshacer entrega"
      campos={[{ k: 'motivo', l: 'Motivo', ops: MOTIVOS_DESHACER }, { k: 'nota', l: 'Nota *', req: true, ph: 'Qué pasó' }]} onCancel={() => setDlg(null)}
      onOk={(v) => { setDlg(null); deshacerEntrega(r.id, { motivo: v.motivo, nota: v.nota.trim() }); pcAvisar(); toast && toast(`Entrega deshecha · ${r.placa} vuelve a Por entregar`, 'y'); onClose(); }} />}
      {dlg === 'garantia' && <PcGarantiaForm r={r} onCancel={() => setDlg(null)} onListo={(g) => { setDlg({ ticket: g }); pcAvisar(); toast && toast(`Garantía registrada · ${r.placa}`, 'g'); }} />}
      {dlg && dlg.ticket && <GarantiaTicket ticket={r} g={dlg.ticket} onCerrar={() => { setDlg(null); onClose(); }} />}
      {dlg === 'entGar' && window.ConfirmActionModal && <window.ConfirmActionModal tone="primary" icon={I.check(24, TOKENS.primary)} title="Entregar garantía" confirmLabel="Entregar"
      ticket={r} message={`${r._gar.rines.length} ${r._gar.rines.length === 1 ? 'rin' : 'rines'} de garantía. No se cobra ni genera factura.`}
      onDismiss={() => setDlg(null)} onConfirm={() => { entregarGarantia(r.id, r._gar.id); setDlg(null); pcAvisar(); toast && toast('Garantía entregada', 'g'); onClose(); }} />}
    </PcDrawer>);
}
// Registrar garantía desde el PC (misma información que en el celular).
function PcGarantiaForm({ r, onCancel, onListo }) {
  const [v, setV] = React.useState(() => garVacio());
  const [toc, setToc] = React.useState(false);
  const [conf, setConf] = React.useState(false);
  const f = garFaltas(v);
  return ReactDOM.createPortal(
    <div onClick={onCancel} style={{ position: 'fixed', inset: 0, background: 'rgba(11,28,48,.45)', zIndex: 1100, display: 'grid', placeItems: 'center' }}>
      <div onClick={(ev) => ev.stopPropagation()} style={{ background: TOKENS.bg, borderRadius: 18, width: 460, maxHeight: '90vh', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        <div style={{ padding: '16px 18px', borderBottom: `1px solid ${TOKENS.border}`, background: TOKENS.surface }}><b style={{ fontSize: 17, color: '#0e7490' }}>↺ Registrar garantía</b><div style={{ display: 'flex', alignItems: 'flex-end', gap: 12, marginTop: 10 }}>{window.CabeceraPlaca && <window.CabeceraPlaca ticket={r} />}<span style={{ fontSize: 12.5, color: TOKENS.textMuted, paddingBottom: 8 }}>{r.taller}{r.sede ? ' · ' + r.sede : ''}</span></div></div>
        <div style={{ flex: 1, overflow: 'auto', padding: 16 }}><GarantiaCampos ticket={r} v={v} setV={setV} toc={toc} /><div style={{ fontSize: 12, color: TOKENS.textMuted }}>La primera entrega y su cumplimiento se conservan. Lo devuelto vuelve a Por entregar con plazo de garantía.</div></div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center', padding: '12px 16px', borderTop: `1px solid ${TOKENS.border}`, background: TOKENS.surface }}>
          <span style={{ flex: 1, fontSize: 12, color: TOKENS.textMuted }}>{toc && f.length ? 'Falta: ' + f.join(', ') : ''}</span>
          <PcBtn onClick={onCancel}>Cancelar</PcBtn>
          <PcBtn style={{ background: '#0e7490', color: '#fff', border: 'none' }} onClick={() => { setToc(true); if (!f.length) setConf(true); }}>Registrar garantía</PcBtn>
        </div>
      </div>
      {conf && window.ConfirmActionModal && <window.ConfirmActionModal tone="primary" icon={<span style={{ fontSize: 22, color: '#0e7490' }}>↺</span>} title="Registrar garantía" confirmLabel="Registrar"
      ticket={r} message={`${v.rines.length} ${v.rines.length === 1 ? 'rin vuelve' : 'rines vuelven'} a Por entregar con plazo de garantía. Se imprime el ticket para el taller.`}
      onDismiss={() => setConf(false)} onConfirm={() => { setConf(false); onListo(crearGarantia(r.id, v)); }} />}
    </div>, document.body);
}

// ─── Formularios del PC (14/11/2026, playground "Formularios PC") ─────────
// Panel de 560 px en tarjetas numeradas; el orden del celular: primero los datos de la placa,
// luego los ítems (bloqueados hasta completar el paso 1) y las fotos (obligatorias).
// Ítems con fichas como en el celular; "Listo" no cierra el ítem hasta que estén todos sus datos.
// Los campos obligatorios se marcan en rojo si se sale de ellos sin llenarlos.
const PC_ROJO = { border: '1px solid #c0584f', background: '#fdf3f1', boxShadow: '0 0 0 3px rgba(192,88,79,.12)' };
const PcErr = ({ on, children }) => on ? <div style={{ color: TOKENS.dangerText, fontSize: 12, fontWeight: 600, marginTop: 5 }}>{children}</div> : null;
function PcChips({ options, value, onChange, sm }) {
  return <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>{options.map((o) => { const [v, l] = Array.isArray(o) ? o : [o, o]; const on = value === v; return (
    <button key={v} type="button" onClick={() => onChange(on ? '' : v)} style={{ border: `1px solid ${on ? TOKENS.primary : TOKENS.borderInput}`, background: on ? TOKENS.primary : TOKENS.surface, color: on ? '#fff' : TOKENS.text, borderRadius: 9, padding: sm ? '6px 9px' : '7px 11px', minWidth: sm ? 38 : 42, fontFamily: 'inherit', fontSize: 13, fontWeight: 700, cursor: 'pointer' }}>{l}</button>); })}</div>;
}
function PcStepper({ value, onChange, min = 1 }) {
  const b = { width: 34, height: 36, border: 0, background: TOKENS.surfaceLow, fontSize: 17, fontWeight: 800, color: TOKENS.primary, cursor: 'pointer', fontFamily: 'inherit' };
  return <div style={{ display: 'inline-flex', alignItems: 'center', border: `1px solid ${TOKENS.borderInput}`, borderRadius: 10, overflow: 'hidden', background: TOKENS.surface }}>
    <button type="button" style={b} onClick={() => onChange(Math.max(min, (Number(value) || min) - 1))}>−</button>
    <span style={{ minWidth: 40, textAlign: 'center', fontWeight: 800, fontSize: 15 }}>{value}</span>
    <button type="button" style={b} onClick={() => onChange((Number(value) || 0) + 1)}>+</button></div>;
}
function PcSeccion({ n, estado, titulo, der, children, bloqueo }) {
  // estado: 'ok' | 'on' | 'off'
  return (
    <div style={{ background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 14, padding: 14, marginBottom: 12, position: 'relative' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
        {n != null && <span style={{ width: 24, height: 24, borderRadius: 99, display: 'grid', placeItems: 'center', fontSize: 12, fontWeight: 800, background: estado === 'ok' ? TOKENS.success : estado === 'off' ? TOKENS.surfaceLow : TOKENS.primary, color: estado === 'off' ? TOKENS.textSubtle : '#fff', border: estado === 'off' ? `1px solid ${TOKENS.border}` : 'none' }}>{estado === 'ok' ? I.check(13, '#fff') : n}</span>}
        <b style={{ flex: 1, fontSize: 14.5 }}>{titulo}</b>{der}
      </div>
      {children}
      {bloqueo && <div style={{ position: 'absolute', inset: 0, background: 'rgba(243,246,252,.85)', borderRadius: 14, display: 'grid', placeItems: 'center', textAlign: 'center', fontSize: 13, color: TOKENS.textMuted, fontWeight: 600, zIndex: 2, padding: 12 }}>{bloqueo === true ? '' : bloqueo}</div>}
    </div>);
}
function PcFotosGrid({ fotos, setFotos, max = 10 }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 6 }}>
      {fotos.map((u, i) => <div key={i} style={{ position: 'relative' }}><img src={u} style={{ width: '100%', aspectRatio: '1', objectFit: 'cover', borderRadius: 9, border: `1px solid ${TOKENS.border}`, display: 'block' }} /><button type="button" onClick={() => setFotos((arr) => arr.filter((_, j) => j !== i))} aria-label="Quitar foto" style={{ position: 'absolute', top: -6, right: -6, width: 20, height: 20, borderRadius: 99, border: 'none', background: TOKENS.danger, color: '#fff', fontSize: 11, cursor: 'pointer' }}>✕</button></div>)}
      {fotos.length < max &&
      <label style={{ aspectRatio: '1', border: `1.5px dashed ${TOKENS.borderInput}`, borderRadius: 9, display: 'grid', placeItems: 'center', textAlign: 'center', color: TOKENS.primary, fontWeight: 800, fontSize: 12, cursor: 'pointer', background: TOKENS.surface, lineHeight: 1.3 }}>
          <span>＋<br />Subir</span>
          <input type="file" accept="image/*" multiple style={{ display: 'none' }} onChange={(e) => { pcLeerFotos(e.target.files, (s) => setFotos((arr) => arr.length >= max ? arr : [...arr, s])); e.target.value = ''; }} />
        </label>}
    </div>);
}
// Envuelve un campo para saber cuándo se salió de él (también para el Select de la app).
function PcToque({ onSalir, children }) {
  return <div onBlur={(e) => { if (!e.currentTarget.contains(e.relatedTarget)) onSalir(); }}>{children}</div>;
}

const PC_ITEM_VACIO = () => ({ id: 'i' + Date.now() + Math.random().toString(36).slice(2, 5), tipo: '', cantidad: 1, tamano: '', material: '', huecos: '', tapa: '', tapaValvula: '', marca: '', referencia: '', dot: '', dotExceptions: [], calidad: '', calidadExceptions: [], valvulaSensor: '', observaciones: '' });
const PC_CALIDADES = ['Nueva', 'Usada', 'Mala'];
const PC_FALTA_NOM = { tipo: 'tipo', tamano: 'tamaño', material: 'material', huecos: 'huecos', tapa: 'tapa', tapaValvula: 'tapa válvula', marca: 'marca', referencia: 'referencia', dot: 'DOT', dotExceptions: 'DOT diferentes', calidad: 'calidad', calidadExceptions: 'calidades diferentes', valvulaSensor: 'sensor' };
// Mismas reglas del celular (formValid de Recoger).
function pcItemFaltas(it) {
  if (!it.tipo) return ['tipo'];
  const f = [];
  if (it.tipo === 'rin') ['tamano', 'material', 'huecos', 'tapa', 'tapaValvula'].forEach((k) => { if (!it[k]) f.push(k); });
  if (it.tipo === 'llanta') {
    if (!String(it.marca || '').trim()) f.push('marca');
    if (!String(it.referencia || '').trim()) f.push('referencia');
    const n = Math.max(1, Number(it.cantidad) || 1);
    [['dot', 'dotExceptions', 'dot'], ['calidad', 'calidadExceptions', 'calidad']].forEach(([k, ek, ev]) => {
      const ex = it[ek] || [];
      const usado = ex.reduce((a, x) => a + (Number(x.count) || 0), 0);
      if (usado > n || ex.some((x) => !(Number(x.count) >= 1) || !String(x[ev] || '').trim())) f.push(ek);
      if (n - usado > 0 && !String(it[k] || '').trim()) f.push(k);
    });
  }
  if (it.tipo === 'valvula' && !it.valvulaSensor) f.push('valvulaSensor');
  return f;
}
function pcItemResumen(it) {
  if (it.tipo === 'rin') return [it.tamano && it.tamano + '"', it.material, it.huecos, it.tapa && 'Tapa ' + it.tapa.toLowerCase(), it.tapaValvula && 'T. válvula ' + it.tapaValvula.toLowerCase()].filter(Boolean).join(' · ');
  if (it.tipo === 'llanta') { const nd = (it.dotExceptions || []).length, nc = (it.calidadExceptions || []).length;
    return [it.marca, it.referencia, it.dot && `DOT ${it.dot}${nd ? ` (+${nd} diferente${nd > 1 ? 's' : ''})` : ''}`, it.calidad && `${it.calidad}${nc ? ' + otras' : ''}`].filter(Boolean).join(' · '); }
  if (it.tipo === 'valvula') return it.valvulaSensor ? 'Sensor ' + it.valvulaSensor.toLowerCase() : '';
  return '';
}
function PcItemEditor({ it, n, set, onListo, onQuitar }) {
  const [intento, setIntento] = React.useState(false);
  const faltas = pcItemFaltas(it);
  const mal = (k) => intento && faltas.includes(k);
  const lbl = (k, txt) => <div style={{ ...pcLbl, marginBottom: 6, color: mal(k) ? TOKENS.dangerText : TOKENS.textMuted }}>{txt}</div>;
  const inp = (k, extra) => ({ ...pcInp, width: '100%', ...(mal(k) && !String(it[k] || '').trim() ? PC_ROJO : {}), ...extra });
  const fila = { marginTop: 20 };
  const cant = Math.max(1, Number(it.cantidad) || 1);
  const meta = PC_ITEM_META[it.tipo];
  const dif = (k, ek, ev, titulo, comun) => {
    const ex = it[ek] || [];
    const usado = ex.reduce((a, x) => a + (Number(x.count) || 0), 0);
    const setEx = (arr) => set({ [ek]: arr });
    return (
      <div style={fila}>
        {lbl(k, ex.length ? `${titulo} de las demás (${Math.max(0, cant - usado)})` : titulo)}
        {comun}
        {ex.length > 0 &&
        <div style={{ marginTop: 8, border: `1px solid ${mal(ek) ? '#c0584f' : TOKENS.border}`, borderRadius: 10, overflow: 'hidden', background: TOKENS.surface }}>
            {ex.map((x, j) =>
          <div key={j} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '7px 10px', borderTop: j ? `1px dashed ${TOKENS.border}` : 'none' }}>
                <div style={{ flex: 1, minWidth: 0 }}>{ev === 'dot' ?
              <input value={x.dot || ''} placeholder="DOT diferente" onChange={(e) => setEx(ex.map((y, q) => q === j ? { ...y, dot: e.target.value.toUpperCase() } : y))} style={{ ...pcInp, width: '100%', padding: '7px 9px', fontFamily: pcMono, ...(intento && !String(x.dot || '').trim() ? PC_ROJO : {}) }} /> :
              <PcChips sm options={PC_CALIDADES.filter((c) => c !== it.calidad)} value={x.calidad || ''} onChange={(v) => setEx(ex.map((y, q) => q === j ? { ...y, calidad: v } : y))} />}</div>
                <PcStepper value={x.count} onChange={(v) => setEx(ex.map((y, q) => q === j ? { ...y, count: v } : y))} />
                <span style={{ fontSize: 12, color: TOKENS.textMuted }}>{Number(x.count) === 1 ? 'llanta' : 'llantas'}</span>
                <button type="button" onClick={() => setEx(ex.filter((_, q) => q !== j))} aria-label="Quitar" style={{ width: 30, height: 30, borderRadius: 8, border: `1.5px solid ${TOKENS.borderInput}`, background: TOKENS.surface, color: TOKENS.danger, cursor: 'pointer' }}>✕</button>
              </div>)}
          </div>}
        {usado >= cant && <div style={{ color: TOKENS.dangerText, fontSize: 12, marginTop: 4 }}>Los diferentes no pueden cubrir todas las llantas.</div>}
        {cant > 1 && usado < cant - 1 && <button type="button" onClick={() => setEx([...ex, ev === 'dot' ? { count: 1, dot: '' } : { count: 1, calidad: '' }])} style={{ background: 'none', border: 0, color: TOKENS.primary, fontWeight: 800, fontSize: 12.5, cursor: 'pointer', padding: '7px 0 0', fontFamily: 'inherit' }}>＋ {titulo} diferente</button>}
      </div>);
  };
  return (
    <div style={{ border: `1px solid ${TOKENS.primaryBorder}`, background: '#f8faff', borderRadius: 12, padding: 12, marginBottom: 10 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <span style={{ background: TOKENS.primary, color: '#fff', fontSize: 10.5, fontWeight: 800, letterSpacing: '0.04em', padding: '3px 8px', borderRadius: 99 }}>ITEM {String(n).padStart(2, '0')}</span>
        <b style={{ flex: 1, fontSize: 14 }}>{meta ? meta[0] : 'Nuevo ítem'}</b>
        {onQuitar && <button type="button" onClick={onQuitar} title="Quitar" style={{ width: 32, height: 32, borderRadius: 9, border: `1.5px solid ${TOKENS.borderInput}`, background: TOKENS.surface, cursor: 'pointer', display: 'grid', placeItems: 'center' }}>{I.trash ? I.trash(15, TOKENS.danger) : '🗑'}</button>}
      </div>
      <div style={{ ...fila, display: 'flex', gap: 16, alignItems: 'flex-end' }}>
        <div style={{ flex: 1 }}>{lbl('tipo', 'Tipo')}<PcChips options={[['rin', 'Rin'], ['llanta', 'Llanta'], ['valvula', 'Válvula']]} value={it.tipo} onChange={(v) => { if (!v) return; setIntento(false); set({ ...PC_ITEM_VACIO(), id: it.id, photos: it.photos, cantidad: it.cantidad, tipo: v }); }} /></div>
        <div><div style={{ ...pcLbl, marginBottom: 6 }}>Cantidad</div><PcStepper value={cant} onChange={(v) => set({ cantidad: v })} /></div>
      </div>
      {it.tipo === 'rin' && <>
        <div style={fila}>{lbl('tamano', 'Tamaño')}<PcChips sm options={typeof RIN_TAMANOS !== 'undefined' ? RIN_TAMANOS : []} value={it.tamano} onChange={(v) => set({ tamano: v })} /></div>
        <div style={fila}>{lbl('material', 'Material')}<PcChips options={typeof RIN_MATERIALES !== 'undefined' ? RIN_MATERIALES : []} value={it.material} onChange={(v) => set({ material: v })} /></div>
        <div style={fila}>{lbl('huecos', 'Huecos')}<PcChips options={typeof RIN_HUECOS !== 'undefined' ? RIN_HUECOS : []} value={it.huecos} onChange={(v) => set({ huecos: v })} /></div>
        <div style={{ ...fila, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <div>{lbl('tapa', 'Tapa')}<PcChips options={['Sí', 'No']} value={it.tapa} onChange={(v) => set({ tapa: v })} /></div>
          <div>{lbl('tapaValvula', 'Tapa válvula')}<PcChips options={['Sí', 'No']} value={it.tapaValvula} onChange={(v) => set({ tapaValvula: v })} /></div>
        </div>
      </>}
      {it.tipo === 'llanta' && <>
        <div style={{ ...fila, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <div>{lbl('marca', 'Marca')}<input value={it.marca || ''} onChange={(e) => set({ marca: e.target.value })} style={inp('marca')} /></div>
          <div>{lbl('referencia', 'Referencia')}<input value={it.referencia || ''} placeholder="Ej: 205/55R16" onChange={(e) => set({ referencia: e.target.value.toUpperCase() })} style={inp('referencia')} /></div>
        </div>
        {dif('dot', 'dotExceptions', 'dot', 'DOT', <input value={it.dot || ''} onChange={(e) => set({ dot: e.target.value.toUpperCase() })} style={inp('dot', { fontFamily: pcMono, fontWeight: 700 })} />)}
        {dif('calidad', 'calidadExceptions', 'calidad', 'Calidad', <PcChips options={PC_CALIDADES} value={it.calidad} onChange={(v) => set({ calidad: v, calidadExceptions: (it.calidadExceptions || []).filter((x) => x.calidad !== v) })} />)}
      </>}
      {it.tipo === 'valvula' && <div style={fila}>{lbl('valvulaSensor', '¿Con sensor?')}<PcChips options={['Sí', 'No']} value={it.valvulaSensor} onChange={(v) => set({ valvulaSensor: v })} /></div>}
      {it.tipo && <div style={fila}><div style={{ ...pcLbl, marginBottom: 6 }}>Observaciones</div><input value={it.observaciones || ''} placeholder="Opcional" onChange={(e) => set({ observaciones: e.target.value })} style={{ ...pcInp, width: '100%' }} /></div>}
      <div style={{ ...fila, display: 'flex', alignItems: 'center', gap: 10, justifyContent: 'flex-end' }}>
        {intento && faltas.length > 0 && <span style={{ flex: 1, color: TOKENS.dangerText, fontSize: 12.5, fontWeight: 600 }}>Falta: {faltas.map((k) => PC_FALTA_NOM[k]).join(', ')}</span>}
        <PcBtn tone="p" disabled={!it.tipo} style={{ padding: '10px 18px', fontSize: 13.5 }} onClick={() => faltas.length ? setIntento(true) : onListo()}>Listo</PcBtn>
      </div>
    </div>);
}
// Editar desde el PC: el mismo formulario, lleno con los datos de la placa.
// En registros ya entregados solo se corrigen placa, aseguradora, taller y sede (igual que en el celular).
function PcRegistrarRecogida({ onClose, onGuardado, editar, onCerrarTodo }) {
  const ms = window.mensajerosApp ? window.mensajerosApp() : [];
  const ed = editar || null;
  const soloId = !!(ed && ed._estado === 'ent');
  const [f, setF] = React.useState(ed ? {
    como: ed.comoLlego || 'mensajero', mensajero: ed.recogidoPor || (ms[0] || {}).usuario || '', transp: ed.transportadoraLlegada || '', guia: ed.guiaLlegada || '',
    fecha: pcIso(ed.fecha) || pcHoyIso(), placa: ed.placa || '', aseg: ed.aseguradora || '', taller: ed.taller || '', sede: ed.sede || '', express: !!ed.express, cliente: ed.cliente || { nombre: '', telefono: '', direccion: '' }
  } : { como: 'mensajero', mensajero: (ms[0] || {}).usuario || '', transp: '', guia: '', fecha: pcHoyIso(), placa: '', aseg: '', taller: '', sede: '', express: false, cliente: { nombre: '', telefono: '', direccion: '' } });
  const [items, setItems] = React.useState(ed && (ed.items || []).length ? ed.items.map((it, i) => ({ ...PC_ITEM_VACIO(), ...it, dotExceptions: [...(it.dotExceptions || [])], calidadExceptions: [...(it.calidadExceptions || [])], id: it.id || 'i' + i + Date.now() })) : [PC_ITEM_VACIO()]);
  const [abierto, setAbierto] = React.useState(ed ? null : 0);
  const [fotos, setFotos] = React.useState(ed ? (ed.fotosPlaca || []).filter(Boolean) : []);
  const [toc, setToc] = React.useState({});
  const [confirmar, setConfirmar] = React.useState(false);
  const set = (p) => setF((x) => ({ ...x, ...p }));
  const tocar = (k) => setToc((t) => t[k] ? t : { ...t, [k]: true });
  const setIt = (i, p) => setItems((arr) => arr.map((x, j) => j === i ? { ...x, ...p } : x));
  const Sel = window.Select;
  const sedes = f.taller && window.catSedesDe ? window.catSedesDe(f.taller) : [];
  const partic = !!(window.esParticular && window.esParticular(f.taller));
  // 25/11/2026: en ciudades donde el mensajero no recoge, el rin llega por transportadora o lo trae el taller.
  const fueraRuta = !!(f.taller && f.sede && window.catMensajeroRecoge && !window.catMensajeroRecoge(f.taller, f.sede));
  React.useEffect(() => { if (!ed && fueraRuta && f.como === 'mensajero') set({ como: 'otra-ciudad' }); }, [f.taller, f.sede]);
  const cliOk = !partic || (f.cliente.nombre.trim() && f.cliente.telefono.trim().length >= 7 && f.cliente.direccion.trim());
  const idOk = f.placa.length >= 5 && (f.aseg || partic) && f.taller && (f.sede || partic) && cliOk;
  const datosOk = idOk && f.fecha && (f.como !== 'otra-ciudad' || f.transp.trim());
  const itemsListos = items.filter((it) => it.tipo);
  // Al editar, un registro viejo sin fotos no queda bloqueado por la foto.
  const fotosOk = fotos.length > 0 || (ed && !(ed.fotosPlaca || []).filter(Boolean).length);
  const faltas = soloId ? [!idOk && 'datos de la placa'].filter(Boolean) :
  [!datosOk && 'datos de la placa', !itemsListos.length && 'un ítem', abierto != null && 'terminar el ítem', !fotosOk && 'una foto'].filter(Boolean);
  const errPlaca = toc.placa && f.placa.length < 5;
  const guardar = () => {
    const m = ms.find((x) => x.usuario === f.mensajero);
    const limpiar = (arr) => arr.map((it) => { const o = Object.fromEntries(Object.entries(it).filter(([, v]) => v !== '' && !(Array.isArray(v) && !v.length))); o.cantidad = Number(it.cantidad) || 1; return o; });
    const comun = {
      recogidoPor: f.como === 'mensajero' ? (m || {}).usuario || '' : '', recogidoPorNombre: f.como === 'mensajero' ? (m || {}).nombre || '' : '',
      comoLlego: f.como, transportadoraLlegada: f.como === 'otra-ciudad' ? f.transp.trim() : '', guiaLlegada: f.como === 'otra-ciudad' ? f.guia.trim() : '',
      express: !!f.express
    };
    if (ed) {
      const id = { placa: f.placa, aseguradora: partic ? '' : f.aseg, taller: f.taller, sede: partic ? '' : f.sede, ...(partic ? { cliente: { ...f.cliente } } : {}) };
      if (soloId) { window.updateEntregaTicket(ed.id, id); pcAvisar(); onGuardado({ ...ed, ...id }); return; }
      const cambios = { ...id, ...comun, fecha: pcDeIso(f.fecha), items: limpiar(itemsListos), fotosPlaca: fotos };
      const lista = window.loadPendientesSaved ? window.loadPendientesSaved() : [];
      const idx = lista.findIndex((x) => x.id === ed.id);
      if (idx >= 0) { lista[idx] = { ...lista[idx], ...cambios }; window.safeSetItem('rodando.pendientes', JSON.stringify(lista)); } else
      window.savePendienteTicket({ ...ed._t, ...cambios }); // registro demo → queda guardado con sus cambios
      pcAvisar(); onGuardado({ ...ed, ...cambios, id: idx >= 0 ? ed.id : 'saved-' + ed.codigo });
      return;
    }
    const yo = window.usuarioActual ? window.usuarioActual() : {};
    const hoy = f.fecha === pcHoyIso(); const now = new Date();
    const t = {
      codigo: typeof getNextCode === 'function' ? getNextCode() : String(Date.now()).slice(-4), placa: f.placa, idType: 'placa',
      fecha: pcDeIso(f.fecha), horaRecogida: hoy ? `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}` : '09:00',
      aseguradora: partic ? '' : f.aseg, taller: f.taller, sede: partic ? '' : f.sede, ...(partic ? { cliente: { ...f.cliente } } : {}), items: limpiar(itemsListos), fotosPlaca: fotos, ...comun,
      digitadoPor: yo.usuario || '', digitadoPorNombre: yo.nombre || ''
    };
    window.savePendienteTicket(t);
    pcAvisar(); onGuardado(t);
  };
  const Modal = window.ConfirmActionModal;
  const lblS = { ...pcLbl, marginBottom: 6 };
  const campo = (k, label, nodo, msg, malo) => <div style={{ minWidth: 0 }}><div style={lblS}>{label}</div><PcToque onSalir={() => tocar(k)}>{nodo}</PcToque><PcErr on={malo}>{msg}</PcErr></div>;
  const ibtn = (tone) => ({ width: 32, height: 32, borderRadius: 9, border: tone === 'r' ? `1.5px solid ${TOKENS.borderInput}` : `1px solid ${TOKENS.border}`, background: TOKENS.surface, cursor: abierto != null ? 'not-allowed' : 'pointer', display: 'grid', placeItems: 'center', opacity: abierto != null ? 0.45 : 1 });
  const resumenItems = itemsListos.map((x) => { const k = Number(x.cantidad) || 1; return `${k} ${k === 1 ? PC_ITEM_META[x.tipo][0].toLowerCase() : PC_ITEM_META[x.tipo][1].toLowerCase()}`; }).join(' · ');
  return (
    <PcDrawer ancho={560} fondo onClose={onCerrarTodo || onClose} onAtras={ed ? onClose : null} atrasTxt="Volver a la ficha" titulo={ed ? <div><b style={{ fontSize: 17 }}>Editar registro</b>{window.CabeceraPlaca && <div style={{ marginTop: 10 }}><window.CabeceraPlaca ticket={ed} /></div>}</div> : <b style={{ fontSize: 17 }}>Registrar recogida</b>}
    pie={<><span style={{ flex: 1, fontSize: 12, color: TOKENS.textMuted, alignSelf: 'center' }}>{faltas.length ? 'Falta: ' + faltas.join(', ') : ''}</span><PcBtn onClick={onClose}>Cancelar</PcBtn><PcBtn tone="p" disabled={faltas.length > 0} onClick={() => setConfirmar(true)}>{ed ? 'Guardar cambios' : 'Guardar recogida'}</PcBtn></>}>
      {soloId && <div style={{ background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 10, padding: '10px 12px', fontSize: 12.5, color: TOKENS.textMuted, marginBottom: 12 }}>Esta placa ya se entregó: solo se corrigen placa, aseguradora, taller y sede. Los ítems y el soporte de la entrega no cambian.</div>}
      <PcSeccion n={1} estado={datosOk ? 'ok' : 'on'} titulo="Datos de la placa">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          {!soloId && <div style={{ gridColumn: '1 / -1' }}><div style={lblS}>¿Cómo llegó?</div><PcChips options={[...(fueraRuta ? [] : [['mensajero', 'Lo recogió el mensajero']]), ['otra-ciudad', 'Llegó por transportadora'], ['taller', 'Lo trajo el taller']]} value={f.como} onChange={(v) => v && set({ como: v })} />{fueraRuta && <div style={{ fontSize: 11.5, color: TOKENS.textMuted, marginTop: 6 }}>El mensajero no recoge en {(window.catUbicacion(f.taller, f.sede) || {}).ciudad}: llega por transportadora o lo trae el taller.</div>}</div>}
          {!soloId && f.como === 'mensajero' && <div style={{ gridColumn: '1 / -1' }}><div style={lblS}>Mensajero</div><PcChips options={ms.map((m) => [m.usuario, m.nombre])} value={f.mensajero} onChange={(v) => v && set({ mensajero: v })} /></div>}
          {!soloId && f.como === 'otra-ciudad' && <>
            {campo('transp', 'Transportadora', <input value={f.transp} onChange={(e) => set({ transp: e.target.value })} placeholder="Ej: Servientrega" style={{ ...pcInp, width: '100%', ...(toc.transp && !f.transp.trim() ? PC_ROJO : {}) }} />, 'Escribe la transportadora.', toc.transp && !f.transp.trim())}
            <div><div style={lblS}>N.º de guía</div><input value={f.guia} onChange={(e) => set({ guia: e.target.value })} style={{ ...pcInp, width: '100%', fontFamily: pcMono }} /></div>
          </>}
          {campo('placa', 'Placa', <input value={f.placa} maxLength={6} onChange={(e) => set({ placa: e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, '') })} placeholder="Ej: ABC123" className="pc-ph" style={{ ...pcInp, width: '100%', fontFamily: pcMono, fontWeight: 700, fontSize: 16, letterSpacing: '0.04em', ...(errPlaca ? PC_ROJO : {}) }} />, f.placa ? 'La placa debe tener al menos 5 caracteres.' : 'Escribe la placa.', errPlaca)}
          {!soloId ? <div><div style={lblS}>Fecha de recogida</div><input type="date" value={f.fecha} max={pcHoyIso()} onChange={(e) => set({ fecha: e.target.value })} style={{ ...pcInp, width: '100%' }} /></div> : <div />}
          {partic ? <div style={{ gridColumn: '1 / -1' }}><div style={lblS}>Aseguradora</div><div style={{ ...pcInp, background: TOKENS.surfaceLow, color: TOKENS.textSubtle }}>No aplica</div></div> :
          <div style={{ gridColumn: '1 / -1' }}>{campo('aseg', 'Aseguradora', Sel && <Sel value={f.aseg} error={!!(toc.aseg && !f.aseg)} options={window.catAseguradoras ? window.catAseguradoras().map((a) => a.nombre) : []} placeholder="Seleccionar" searchable onChange={(v) => set({ aseg: v })} />, 'Escoge la aseguradora.', toc.aseg && !f.aseg)}</div>}
          {campo('taller', 'Taller', Sel && <Sel value={f.taller} error={!!(toc.taller && !f.taller)} options={window.catTallerOpciones ? window.catTallerOpciones() : []} placeholder="Seleccionar" searchable onChange={(v) => { const ss = window.catSedesDe ? window.catSedesDe(v) : []; set({ taller: v, sede: ss.length === 1 ? ss[0] : '' }); }} />, 'Escoge el taller.', toc.taller && !f.taller)}
          {partic ? <div><div style={lblS}>Sede</div><div style={{ ...pcInp, background: TOKENS.surfaceLow, color: TOKENS.textSubtle }}>No aplica</div></div> :
          campo('sede', 'Sede', Sel && <Sel value={f.sede} error={!!(toc.sede && f.taller && !f.sede)} options={sedes} placeholder="Seleccionar" disabled={!f.taller} onChange={(v) => set({ sede: v })} />, 'Escoge la sede.', toc.sede && f.taller && !f.sede)}
          {partic && <div style={{ gridColumn: '1 / -1', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <div><div style={lblS}>Cliente · nombre</div><input value={f.cliente.nombre} onChange={(e) => set({ cliente: { ...f.cliente, nombre: e.target.value } })} style={{ ...pcInp, width: '100%' }} /></div>
            <div><div style={lblS}>Teléfono</div><input value={f.cliente.telefono} onChange={(e) => set({ cliente: { ...f.cliente, telefono: e.target.value.replace(/[^\d ]/g, '') } })} style={{ ...pcInp, width: '100%' }} /></div>
            <div style={{ gridColumn: '1 / -1' }}><div style={lblS}>Dirección</div><input value={f.cliente.direccion} onChange={(e) => set({ cliente: { ...f.cliente, direccion: e.target.value } })} placeholder="Ej: Cra 100 # 11-60, apto 302" style={{ ...pcInp, width: '100%' }} /></div>
          </div>}
          {!soloId && f.fecha !== pcHoyIso() && <div style={{ gridColumn: '1 / -1', fontSize: 11.5, color: TOKENS.textMuted }}>El plazo se cuenta desde la fecha de recogida que pongas.</div>}
          {!soloId &&
          <button type="button" onClick={() => set({ express: !f.express })} style={{ gridColumn: '1 / -1', display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left', border: `1.5px solid ${f.express ? '#e879b0' : TOKENS.border}`, background: f.express ? '#fce7f3' : TOKENS.surface, borderRadius: 12, padding: '11px 14px', cursor: 'pointer', fontFamily: 'inherit' }}>
              <span style={{ fontSize: 19 }}>⚡</span>
              <span style={{ flex: 1 }}><b style={{ display: 'block', fontSize: 14, color: TOKENS.text }}>Express</b><span style={{ fontSize: 12, color: TOKENS.textMuted }}>El taller pidió entregarla primero · plazo de {pcSlaDe(true)} días hábiles</span></span>
              <span style={{ width: 40, height: 22, borderRadius: 99, background: f.express ? '#be185d' : TOKENS.borderInput, position: 'relative', flexShrink: 0 }}><span style={{ position: 'absolute', top: 2, left: f.express ? 20 : 2, width: 18, height: 18, borderRadius: 99, background: '#fff', transition: 'left .15s' }} /></span>
            </button>}
        </div>
      </PcSeccion>
      {!soloId && <>
        <PcSeccion n={2} estado={datosOk ? 'on' : 'off'} titulo="Ítems" der={<span style={{ fontSize: 12, color: TOKENS.textSubtle }}>{resumenItems}</span>} bloqueo={!datosOk && <span>🔒 Completa los datos de la placa<br />para agregar los ítems.</span>}>
          {items.map((it, i) => abierto === i ?
          <PcItemEditor key={it.id} it={it} n={i + 1} set={(p) => setIt(i, p)} onListo={() => setAbierto(null)} onQuitar={items.length > 1 || it.tipo ? () => { setItems((arr) => { const r = arr.filter((_, j) => j !== i); return r.length ? r : [PC_ITEM_VACIO()]; }); setAbierto(items.length > 1 ? null : 0); } : null} /> :
          it.tipo ?
          <div key={it.id} style={{ display: 'flex', alignItems: 'center', gap: 10, border: `1px solid ${TOKENS.border}`, background: TOKENS.surfaceLow, borderRadius: 12, padding: '10px 12px', marginBottom: 8 }}>
                <span style={{ background: TOKENS.primary, color: '#fff', fontSize: 10.5, fontWeight: 800, letterSpacing: '0.04em', padding: '3px 8px', borderRadius: 99 }}>ITEM {String(i + 1).padStart(2, '0')}</span>
                <div style={{ flex: 1, minWidth: 0 }}><b style={{ fontSize: 13.5 }}>{PC_ITEM_META[it.tipo][0]} ×{it.cantidad}</b><div style={{ fontSize: 12.5, color: TOKENS.textMuted, marginTop: 2 }}>{pcItemResumen(it) || 'Sin más datos'}</div></div>
                <button type="button" title="Editar" disabled={abierto != null} onClick={() => setAbierto(i)} style={ibtn('p')}>{I.pencil(15, TOKENS.primary)}</button>
                <button type="button" title="Quitar" disabled={abierto != null} onClick={() => setItems((arr) => arr.filter((_, j) => j !== i))} style={ibtn('r')}>{I.trash ? I.trash(15, TOKENS.danger) : '🗑'}</button>
              </div> : null)}
          {abierto == null && <PcBtn style={{ width: '100%', borderStyle: 'dashed' }} onClick={() => { setItems((arr) => [...arr, PC_ITEM_VACIO()]); setAbierto(items.length); }}>＋ Agregar ítem</PcBtn>}
        </PcSeccion>
        <PcSeccion n={3} estado={datosOk ? 'on' : 'off'} titulo={<>Fotos <span style={{ color: TOKENS.dangerText }}>*</span></>} der={<span style={{ fontSize: 12, color: TOKENS.textSubtle }}>Al menos una</span>} bloqueo={!datosOk}>
          <PcFotosGrid fotos={fotos} setFotos={setFotos} />
        </PcSeccion>
        {!ed && <div style={{ fontSize: 11.5, color: TOKENS.textMuted, margin: '2px 2px 0' }}>Queda registrado que lo digitaste tú desde el PC.</div>}
      </>}
      {confirmar && Modal && (ed ?
      <Modal tone="primary" icon={I.pencil(22, TOKENS.primary)} title="Guardar cambios" confirmLabel="Guardar cambios"
      message={`${f.placa} · ${f.taller}${f.sede ? ' · ' + f.sede : ''}${soloId ? '' : ` · ${itemsListos.length} ${itemsListos.length === 1 ? 'ítem' : 'ítems'} · recogida el ${pcFechaCorta(pcDeIso(f.fecha))}`}`}
      onDismiss={() => setConfirmar(false)} onConfirm={() => { setConfirmar(false); guardar(); }} /> :
      <Modal tone="primary" icon={I.check(24, TOKENS.primary)} title="Guardar recogida" confirmLabel="Guardar"
      message={`${f.placa} · ${f.taller} · ${f.sede} · ${itemsListos.length} ${itemsListos.length === 1 ? 'ítem' : 'ítems'} · recogida el ${pcFechaCorta(pcDeIso(f.fecha))}`}
      onDismiss={() => setConfirmar(false)} onConfirm={() => { setConfirmar(false); guardar(); }} />)}
    </PcDrawer>);
}
// Registrar entrega (14/11/2026): desde la ficha sale solo esa placa; desde la barra primero se
// escoge la placa. "¿Cómo se entrega?" va primero. En mano = una placa con su propia factura o
// remisión. Transportadora = varias placas pueden ir con la misma guía. Foto obligatoria.
// ─── Asignar encargo (21/11/2026) ────────────────────────────────────────
// Encargos (23/11/2026): tarea de la oficina para el mensajero (Entregar · Recoger · Hacer), con
// taller del catálogo (placa opcional) u otro lugar escrito. No crea registro ni número de orden.
// Si la placa tiene un registro abierto, ofrece agregarlo como suministro de ese registro.
const pcLugaresUsados = () => [...new Set((window.loadEncargos ? window.loadEncargos() : []).filter((e) => e.lugarTipo === 'otro' && e.direccion).map((e) => e.direccion))];
// 23/11/2026: "Nueva tarea" — un solo formulario. Recoger placas para reparar = solicitud de recogida
// (nace el registro con orden); Recoger otra cosa, Entregar y Hacer = encargo.
const PC_TAREA_TIPOS = [['placas', '↙ Recoger placas', 'para reparar · nace el registro'], ['recoger', '↙ Recoger otra cosa', 'pintura, un repuesto…'], ['entregar', '↗ Entregar', 'llevar algo a un lugar'], ['hacer', '✓ Hacer', 'pagar, un trámite…']];
function PcAsignarEncargo({ onClose, onGuardado, inicial }) {
  const ms = window.mensajerosApp ? window.mensajerosApp() : [];
  const ini = inicial || {};
  const [f, setF] = React.useState({ tipo: ini.tipo || 'placas', que: ini.que || '', lugarTipo: ini.lugarTipo || 'taller', taller: ini.taller || '', sede: ini.sede || '', direccion: ini.direccion || '', placa: ini.placa || '', placas: ini.placas || [], placaTxt: '', cliente: ini.cliente || { nombre: '', telefono: '', direccion: '' }, cuando: ini.fechaIso && ini.fechaIso !== pcHoyIso() ? 'fecha' : 'hoy', fecha: ini.fechaIso || '', prioridad: !!(ini.urgente || ini.prioridad), nota: ini.nota || '', para: ini.para || (ms[0] || {}).usuario || 'cesar' });
  const [toc, setToc] = React.useState(false);
  const [sumDlg, setSumDlg] = React.useState(null);
  const [listo, setListo] = React.useState(null); // { msg, res }
  const set = (p) => setF((x) => ({ ...x, ...p }));
  const Sel = window.Select;
  const esP = f.tipo === 'placas';
  const lugarTipo = esP ? 'taller' : f.lugarTipo;
  const partic = lugarTipo === 'taller' && !!(window.esParticular && window.esParticular(f.taller));
  // 25/11/2026: para recoger placas solo salen las sedes donde el mensajero recoge.
  const soloRuta = f.tipo === 'placas' && !!window.catSedesRuta;
  const sedes = f.taller ? (soloRuta ? window.catSedesRuta(f.taller) : window.catSedesDe ? window.catSedesDe(f.taller) : []) : [];
  const lblS = { ...pcLbl, marginBottom: 6 };
  const inp = { ...pcInp, width: '100%', boxSizing: 'border-box' };
  const noAplica = <div style={{ ...inp, background: TOKENS.surfaceLow, color: TOKENS.textSubtle }}>No aplica</div>;
  const opc = <span style={{ textTransform: 'none', letterSpacing: 0, fontWeight: 600, color: TOKENS.textSubtle }}>(opcional)</span>;
  const manIso = (() => { const d = new Date(); d.setDate(d.getDate() + 1); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; })();
  const fechaIso = f.cuando === 'hoy' ? pcHoyIso() : f.cuando === 'manana' ? manIso : f.fecha;
  const placasL = [...f.placas, ...f.placaTxt.split(/[,\s]+/).map((x) => x.trim().toUpperCase()).filter((x) => x.length >= 5)].filter((x, i, a) => a.indexOf(x) === i);
  const cliOk = !partic || (f.cliente.nombre.trim() && f.cliente.telefono.trim().length >= 7 && f.cliente.direccion.trim());
  const lugarFalta = lugarTipo === 'taller' ? (f.tipo === 'hacer' && !f.taller ? null : (!f.taller && 'taller') || (!partic && sedes.length > 1 && !f.sede && 'sede') || (!cliOk && 'datos del cliente')) : (f.tipo !== 'hacer' && !f.direccion.trim() && 'dónde');
  const queCorto = f.que.trim().length < 5;
  const faltas = [queCorto && 'describe qué (mín. 5 letras)', lugarFalta, esP && !placasL.length && 'placa', f.cuando === 'fecha' && !f.fecha && 'la fecha'].filter(Boolean);
  const abierto = f.tipo === 'entregar' && lugarTipo === 'taller' && f.placa.length >= 5 ? pcRegistros().find((r) => r._estado === 'pend' && !r._gar && r.placa === f.placa) : null;
  const msgDe = () => {
    const nom = (ms.find((m) => m.usuario === f.para) || {}).nombre || f.para;
    const cuando = f.cuando === 'hoy' ? 'hoy' : f.cuando === 'manana' ? 'mañana' : pcFechaCorta(pcDeIso(f.fecha));
    const co = lugarTipo === 'taller' && f.taller && !partic && window.tallerCoords ? window.tallerCoords(f.taller, f.sede) : {};
    const conLugar = lugarTipo === 'taller' ? !!f.taller : !!f.direccion.trim();
    return window.tareaWhatsAppTexto({ tipo: f.tipo, prioridad: f.prioridad, placas: esP ? placasL : (f.placa && !partic && lugarTipo === 'taller' ? [f.placa] : []), que: f.que.trim(),
      cliente: partic ? { nombre: f.cliente.nombre.trim(), telefono: f.cliente.telefono.trim(), direccion: f.cliente.direccion.trim() } : null,
      donde: !conLugar || partic ? '' : lugarTipo === 'taller' ? [f.taller, f.sede].filter(Boolean).join(' · ') : f.direccion.trim(),
      direccion: lugarTipo === 'taller' && !partic ? co.direccion : '', lat: co.lat, lng: co.lng, para: cuando, asignada: nom, nota: f.nota.trim() });
  };
  const guardar = () => {
    if (faltas.length) { setToc(true); return; }
    const yo = (window.usuarioActual && window.usuarioActual()) || {};
    if (esP) {
      const now = Date.now(); const co = !partic && window.tallerCoords ? window.tallerCoords(f.taller, f.sede) : {};
      const p = { id: 'p-' + now, fecha: pcDeIso(fechaIso), asignadoA: f.para, tipo: 'recoger', tallerId: co.tallerId, taller: f.taller, sede: partic ? f.cliente.nombre.trim() : f.sede,
        direccion: partic ? f.cliente.direccion.trim() : co.direccion, ciudad: co.ciudad || 'Cali', lat: partic ? null : co.lat, lng: partic ? null : co.lng,
        referencia: f.que.trim(), estado: 'solicitud', placas: placasL, creadaPor: 'admin', prioridad: f.prioridad ? 'alta' : 'normal', notas: f.nota.trim(),
        ...(partic ? { cliente: { nombre: f.cliente.nombre.trim(), telefono: f.cliente.telefono.trim(), direccion: f.cliente.direccion.trim() } } : {}), createdAt: now, updatedAt: now };
      window.addParada(p);
      if (window.addNotif) window.addNotif({ id: 'n-' + now, tipo: 'autoasignacion', para: 'mensajero', paraUsuario: f.para, estado: 'pendiente', taller: p.taller, sede: p.sede, accion: 'recoger', referencia: p.referencia, paradaId: p.id, actor: yo.usuario || 'admin', createdAt: now, resolucion: null });
      pcAvisar(); setListo({ msg: msgDe(), res: { que: `Recoger ${placasL.join(', ')}`, solicitud: p } });
      return;
    }
    const conLugar = lugarTipo === 'taller' ? !!f.taller : !!f.direccion.trim();
    const e = window.crearEncargo({ tipo: f.tipo, que: f.que.trim(), lugarTipo: conLugar ? lugarTipo : 'otro', taller: lugarTipo === 'taller' ? f.taller : '', sede: lugarTipo === 'taller' && !partic ? f.sede : '', direccion: partic ? f.cliente.direccion.trim() : lugarTipo === 'otro' ? f.direccion.trim() : '', placa: lugarTipo === 'taller' && !partic ? f.placa : '', fechaIso, urgente: f.prioridad, nota: f.nota.trim(), para: f.para, ...(partic ? { cliente: { ...f.cliente } } : {}) });
    pcAvisar(); setListo({ msg: msgDe(), res: e });
  };
  const chip = (on, l, fn) => <button type="button" onClick={fn} style={{ border: `1px solid ${on ? TOKENS.primary : TOKENS.borderInput}`, background: on ? TOKENS.primary : TOKENS.surface, color: on ? '#fff' : TOKENS.text, borderRadius: 99, padding: '7px 13px', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>{l}</button>;
  const tallerSel = <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: 12 }}>
    <div><div style={lblS}>Taller {f.tipo === 'hacer' && opc}</div>{Sel && <Sel value={f.taller} error={toc && !f.taller && !(f.tipo === 'hacer')} options={soloRuta ? window.catTallerOpcionesRuta() : window.catTallerOpciones ? window.catTallerOpciones() : []} placeholder="Seleccionar" searchable onChange={(v) => { const ss = soloRuta ? window.catSedesRuta(v) : window.catSedesDe ? window.catSedesDe(v) : []; set({ taller: v, sede: ss.length === 1 ? ss[0] : '' }); }} />}</div>
    <div><div style={lblS}>Sede</div>{partic ? noAplica : Sel && <Sel value={f.sede} error={toc && !!f.taller && sedes.length > 1 && !f.sede} options={sedes} placeholder="Seleccionar" disabled={!f.taller} onChange={(v) => set({ sede: v })} />}</div>
  </div>;
  const clienteCampos = partic && <div style={{ marginTop: 12 }}>
    <div style={lblS}>Cliente</div>
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
      <input value={f.cliente.nombre} onChange={(e) => set({ cliente: { ...f.cliente, nombre: e.target.value } })} placeholder="Nombre" style={{ ...inp, ...(toc && !f.cliente.nombre.trim() ? PC_ROJO : {}) }} />
      <input value={f.cliente.telefono} onChange={(e) => set({ cliente: { ...f.cliente, telefono: e.target.value.replace(/[^\d ]/g, '') } })} placeholder="Teléfono" style={{ ...inp, ...(toc && f.cliente.telefono.trim().length < 7 ? PC_ROJO : {}) }} />
    </div>
    <input value={f.cliente.direccion} onChange={(e) => set({ cliente: { ...f.cliente, direccion: e.target.value } })} placeholder="Dirección · ej. Cra 100 # 11-60, apto 302" style={{ ...inp, marginTop: 10, ...(toc && !f.cliente.direccion.trim() ? PC_ROJO : {}) }} />
  </div>;
  const va = esP ? 'Va a Por planear › Por recoger' : (lugarTipo === 'taller' ? !!f.taller : !!f.direccion.trim()) ? 'Va a Por planear › Por encargar' : 'Va a las Tareas del mensajero';
  return (
    <PcDrawer ancho={580} fondo="#eef1f6" onClose={onClose} titulo={<div><b style={{ fontSize: 17 }}>Nueva tarea</b><div style={{ fontSize: 12.5, color: TOKENS.textMuted, marginTop: 2 }}>Para el mensajero · la app la ubica según lo que hay que hacer</div></div>}
    pie={<><span style={{ flex: 1, fontSize: 12, color: toc && faltas.length ? TOKENS.dangerText : TOKENS.textMuted, alignSelf: 'center' }}>{toc && faltas.length ? 'Falta: ' + faltas.join(', ') : va}</span><PcBtn onClick={onClose}>Cancelar</PcBtn><PcBtn tone="p" onClick={guardar}>Crear tarea</PcBtn></>}>
      <PcSeccion titulo="¿Qué hay que hacer?">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          {PC_TAREA_TIPOS.map(([k, l, d]) => { const on = f.tipo === k; return <button key={k} type="button" onClick={() => set({ tipo: k })} style={{ textAlign: 'left', border: `1.5px solid ${on ? TOKENS.primary : TOKENS.border}`, background: on ? TOKENS.primaryBg : TOKENS.surface, borderRadius: 12, padding: '9px 12px', fontFamily: 'inherit', cursor: 'pointer' }}><b style={{ display: 'block', fontSize: 13.5, color: on ? TOKENS.primary : TOKENS.text }}>{l}</b><span style={{ fontSize: 11.5, color: TOKENS.textMuted }}>{d}</span></button>; })}
        </div>
        <div style={{ ...lblS, marginTop: 12 }}>{esP ? 'Qué recoger' : f.tipo === 'entregar' ? 'Qué entregar' : f.tipo === 'recoger' ? 'Qué recoger' : 'Qué hay que hacer'}</div>
        <input value={f.que} onChange={(e) => set({ que: e.target.value })} placeholder={esP ? 'Ej: 4 rines y llantas' : f.tipo === 'entregar' ? 'Ej: 1 llanta Michelin 205/55 R16' : f.tipo === 'recoger' ? 'Ej: 2 galones de pintura plata' : 'Ej: pagar el recibo de la bodega'} style={{ ...inp, ...(toc && queCorto ? PC_ROJO : {}) }} />
      </PcSeccion>
      <PcSeccion titulo={<>¿Dónde? {f.tipo === 'hacer' && opc}</>}>
        {!esP && <PcSeg value={f.lugarTipo} onChange={(v) => set({ lugarTipo: v })} options={[['taller', 'Taller del catálogo'], ['otro', 'Otro lugar']]} />}
        {lugarTipo === 'taller' ? <>
          {tallerSel}
          {clienteCampos}
          {esP && <>
            <div style={{ ...lblS, marginTop: 12 }}>Placa(s)</div>
            <div style={{ ...inp, display: 'flex', flexWrap: 'wrap', gap: 6, alignItems: 'center', padding: '6px 8px', ...(toc && !placasL.length ? PC_ROJO : {}) }}>
              {f.placas.map((pl) => <span key={pl} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, border: `1px solid ${TOKENS.borderInput}`, borderRadius: 6, padding: '2px 7px', fontFamily: pcMono, fontWeight: 700, fontSize: 12.5, background: TOKENS.surfaceLow }}>{pl}<button type="button" onClick={() => set({ placas: f.placas.filter((x) => x !== pl) })} style={{ border: 0, background: 'none', padding: 0, cursor: 'pointer', color: TOKENS.textMuted }}>✕</button></span>)}
              <input value={f.placaTxt} onChange={(e) => { const v = e.target.value.toUpperCase().replace(/[^A-Z0-9, ]/g, ''); if (/[, ]$/.test(v)) { const x = v.replace(/[, ]/g, ''); if (x.length >= 5 && !f.placas.includes(x)) set({ placas: [...f.placas, x], placaTxt: '' }); else set({ placaTxt: '' }); } else set({ placaTxt: v }); }} onBlur={() => { const x = f.placaTxt.trim(); if (x.length >= 5 && !f.placas.includes(x)) set({ placas: [...f.placas, x], placaTxt: '' }); }} placeholder={f.placas.length ? 'Otra placa…' : 'ABC123 · coma o espacio para agregar otra'} style={{ border: 0, outline: 'none', flex: 1, minWidth: 140, fontFamily: pcMono, fontWeight: 700, fontSize: 13, background: 'transparent', color: TOKENS.text, caretColor: TOKENS.text, padding: '4px 2px' }} />
            </div>
          </>}
          {!esP && !partic && f.taller && <>
            <div style={{ ...lblS, marginTop: 12 }}>Placa {opc}</div>
            <input value={f.placa} onChange={(e) => set({ placa: e.target.value.toUpperCase().replace(/\s/g, '') })} placeholder="ABC123" style={{ ...inp, fontFamily: pcMono, fontWeight: 700 }} />
          </>}
          {abierto && <div style={{ marginTop: 8, background: TOKENS.primaryBg, border: `1px solid ${TOKENS.primaryBorder}`, borderRadius: 10, padding: '9px 12px', fontSize: 12.5, color: TOKENS.primary, lineHeight: 1.45 }}>
            {abierto.placa} tiene un registro abierto (orden {abierto.codigo}, {abierto.taller}). ¿Es para esa placa? <button type="button" onClick={() => setSumDlg(abierto)} style={{ background: 'none', border: 0, padding: 0, color: TOKENS.primary, fontFamily: 'inherit', fontSize: 12.5, fontWeight: 800, cursor: 'pointer' }}>Agregar como suministro ›</button></div>}
        </> : <>
          <div style={{ marginTop: 12 }}>{Sel && <Sel value={f.direccion} error={toc && f.tipo !== 'hacer' && !f.direccion.trim()} searchable options={[...new Set([...pcLugaresUsados(), ...(f.direccion ? [f.direccion] : [])])]} placeholder={f.tipo === 'hacer' ? 'Opcional · vacío = no va a la ruta' : 'Escoge o escribe el lugar'} onChange={(v) => set({ direccion: v })}
            footer={(q, cerrar) => q.trim() && !pcLugaresUsados().some((x) => x.toLowerCase() === q.trim().toLowerCase()) ? <button type="button" onClick={() => { set({ direccion: q.trim() }); cerrar(); }} style={{ display: 'block', width: '100%', textAlign: 'left', border: 0, borderTop: `1px solid ${TOKENS.border}`, background: 'none', padding: '10px 12px', fontFamily: 'inherit', fontSize: 13, fontWeight: 700, color: TOKENS.primary, cursor: 'pointer' }}>Usar “{q.trim()}” ›</button> : null} />}
            {f.tipo === 'hacer' && f.direccion && <button type="button" onClick={() => set({ direccion: '' })} style={{ marginTop: 6, background: 'none', border: 0, padding: 0, color: TOKENS.primary, fontFamily: 'inherit', fontSize: 12.5, fontWeight: 600, cursor: 'pointer' }}>Quitar lugar</button>}
          </div>
          <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 5 }}>{f.tipo === 'hacer' ? 'Sin lugar no va a la ruta: queda en las Tareas del mensajero.' : 'Se guarda para la próxima.'}</div>
        </>}
      </PcSeccion>
      <PcSeccion titulo="¿Para cuándo?">
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', alignItems: 'center' }}>
          {chip(f.cuando === 'hoy', 'Hoy', () => set({ cuando: 'hoy' }))}{chip(f.cuando === 'manana', 'Mañana', () => set({ cuando: 'manana' }))}{chip(f.cuando === 'fecha', '📅 Fecha', () => set({ cuando: 'fecha' }))}
          <button type="button" onClick={() => set({ prioridad: !f.prioridad })} style={{ border: `1px solid ${f.prioridad ? TOKENS.primaryBorder : TOKENS.borderInput}`, background: f.prioridad ? TOKENS.primaryBg : TOKENS.surface, color: f.prioridad ? TOKENS.primary : TOKENS.text, borderRadius: 99, padding: '7px 13px', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>↑ Prioridad</button>
        </div>
        {f.cuando === 'fecha' && <input type="date" value={f.fecha} min={pcHoyIso()} onChange={(e) => set({ fecha: e.target.value })} style={{ ...inp, marginTop: 10, ...(toc && !f.fecha ? PC_ROJO : {}) }} />}
        <div style={{ display: 'grid', gridTemplateColumns: ms.length > 1 ? '1fr 180px' : '1fr', gap: 12, marginTop: 12 }}>
          <input value={f.nota} onChange={(e) => set({ nota: e.target.value })} placeholder="Nota para el mensajero (opcional)" style={inp} />
          {ms.length > 1 && <select value={f.para} onChange={(e) => set({ para: e.target.value })} style={inp}>{ms.map((m) => <option key={m.usuario} value={m.usuario}>{m.nombre}</option>)}</select>}
        </div>
      </PcSeccion>
      {listo && ReactDOM.createPortal(<div style={{ position: 'fixed', inset: 0, background: 'rgba(11,28,48,.45)', zIndex: 1250, display: 'grid', placeItems: 'center' }}>
        <div style={{ background: TOKENS.surface, borderRadius: 18, padding: 22, width: 420 }}>
          <div style={{ width: 52, height: 52, borderRadius: 99, margin: '0 auto 10px', display: 'grid', placeItems: 'center', background: TOKENS.successBg, color: TOKENS.success, fontSize: 22 }}>✓</div>
          <div style={{ textAlign: 'center', fontWeight: 800, fontSize: 17 }}>Tarea creada</div>
          <div style={{ textAlign: 'center', fontSize: 12.5, color: TOKENS.textMuted, margin: '4px 0 12px' }}>¿La compartes en el grupo de WhatsApp?</div>
          <div style={{ background: '#e7f7ec', border: '1px solid #c3e6cd', borderRadius: 12, padding: '10px 12px', fontSize: 12.5, lineHeight: 1.55, whiteSpace: 'pre-wrap', color: TOKENS.text }}>{listo.msg.replace(/\*/g, '').replace(/```/g, '')}</div>
          <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
            <PcBtn style={{ flex: 1, padding: '11px 14px' }} onClick={() => { const r = listo.res; setListo(null); onGuardado(r); }}>Listo</PcBtn>
            <PcBtn style={{ flex: 1, padding: '11px 14px', background: '#25D366', color: '#fff', border: 'none' }} onClick={() => { window.open('https://wa.me/?text=' + encodeURIComponent(listo.msg), '_blank'); const r = listo.res; setListo(null); onGuardado(r); }}>Compartir en WhatsApp</PcBtn>
          </div>
        </div>
      </div>, document.body)}
      {sumDlg && window.PcSuministroDlg && <window.PcSuministroDlg r={sumDlg} onCancel={() => setSumDlg(null)} onOk={(v) => { window.agregarSuministro(sumDlg.id, v); pcAvisar(); setSumDlg(null); onGuardado(null, sumDlg); }} />}
    </PcDrawer>);
}
// Rutas › Encargos (23/11/2026): lista de encargos con su estado.
function PcEncargosTab({ toast }) {
  const L = window.useEncargos ? window.useEncargos() : [];
  const [ver, setVer] = React.useState('pend');
  const [nuevo, setNuevo] = React.useState(false);
  const [conf, setConf] = React.useState(null);
  const [foto, setFoto] = React.useState(null);
  const nom = (u) => (window.nombreDeUsuario && window.nombreDeUsuario(u)) || u || '—';
  // 23/11/2026: la pestaña se llama Tareas: también las recogidas de placas que creó la oficina.
  const [, bump] = React.useReducer((x) => x + 1, 0);
  React.useEffect(() => { window.addEventListener('rodando-paradas', bump); return () => window.removeEventListener('rodando-paradas', bump); }, []);
  const isoDe = (d) => { const m = String(d || '').match(/(\d{1,2})\s*\/\s*(\d{1,2})\s*\/\s*(\d{4})/); return m ? `${m[3]}-${m[2].padStart(2, '0')}-${m[1].padStart(2, '0')}` : ''; };
  const sols = (window.loadParadas ? window.loadParadas() : []).filter((p) => p.tipo === 'recoger' && p.creadaPor === 'admin' && p.estado !== 'cancelada').map((p) => ({ id: 'sol:' + p.id, _sol: p, tipo: 'placas', que: p.referencia, fechaIso: isoDe(p.fecha), urgente: p.prioridad === 'alta', placas: p.placas || [], para: p.asignadoA, lugarTipo: 'taller', taller: p.taller, sede: p.sede, cliente: p.cliente, estado: p.estado === 'completada' ? 'hecho' : 'pend', hecho: p.estado === 'completada' ? { fecha: p.completadaEn ? fechaDDMMYYYY(new Date(p.completadaEn)) : '' } : null }));
  const T = [...L, ...sols];
  const pend = T.filter((e) => e.estado !== 'hecho').sort((a, b) => (b.urgente ? 1 : 0) - (a.urgente ? 1 : 0) || String(a.fechaIso || '9').localeCompare(String(b.fechaIso || '9')));
  const hechos = T.filter((e) => e.estado === 'hecho');
  const V = ver === 'pend' ? pend : hechos;
  const th = { textAlign: 'left', fontSize: 10.5, fontWeight: 800, letterSpacing: '.06em', textTransform: 'uppercase', color: TOKENS.textMuted, background: TOKENS.surfaceLow, padding: '10px 12px', borderBottom: `1px solid ${TOKENS.border}`, whiteSpace: 'nowrap' };
  const td = { padding: '10px 12px', borderBottom: `1px solid ${TOKENS.border}`, fontWeight: 500, fontSize: 13, verticalAlign: 'top' };
  const bl = { borderLeft: `1px solid ${TOKENS.border}` };
  const Modal = window.ConfirmActionModal;
  return <div style={{ display: 'flex', flexDirection: 'column', gap: 12, minHeight: 0, flex: 1 }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <div style={{ display: 'inline-flex', background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 10, padding: 3, gap: 3 }}>
        {[['pend', `Pendientes · ${pend.length}`], ['hecho', `Hechas · ${hechos.length}`]].map(([k, l]) => { const on = ver === k; return <button key={k} type="button" onClick={() => setVer(k)} style={{ border: 0, borderRadius: 8, padding: '6px 13px', fontFamily: 'inherit', fontSize: 13, fontWeight: 700, cursor: 'pointer', background: on ? TOKENS.surface : 'transparent', color: on ? TOKENS.primary : TOKENS.textMuted, boxShadow: on ? '0 1px 3px rgba(22,35,63,.12)' : 'none' }}>{l}</button>; })}
      </div>
      <span style={{ flex: 1 }} />
    </div>
    <div style={{ ...pcCard, overflow: 'auto' }}>
      <table style={{ borderCollapse: 'separate', borderSpacing: 0, width: '100%' }}>
        <thead><tr>{['Para', 'Tipo', 'Qué', 'Dónde', 'Placa', 'Mensajero', ver === 'pend' ? 'Estado' : 'Hecho', ''].map((h, k) => <th key={k} style={{ ...th, ...(k ? bl : {}) }}>{h}</th>)}</tr></thead>
        <tbody>
          {V.map((e) => <tr key={e.id}>
            <td style={{ ...td, whiteSpace: 'nowrap' }}>{window.encParaTxt(e)}{e.urgente && <span style={{ marginLeft: 6, color: TOKENS.primary, fontWeight: 700 }}>↑</span>}</td>
            <td style={{ ...td, ...bl, whiteSpace: 'nowrap' }}>{e._sol ? '↙ Recoger placas' : `${window.ENC_TIPO[e.tipo][0]} ${window.ENC_TIPO[e.tipo][1]}`}</td>
            <td style={{ ...td, ...bl }}>{e.que}{e.nota && <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>{e.nota}</div>}</td>
            <td style={{ ...td, ...bl }}>{window.encDonde(e) || <span style={{ color: TOKENS.textSubtle }}>—</span>}</td>
            <td style={{ ...td, ...bl }}>{e._sol ? <span style={{ display: 'inline-flex', gap: 4, flexWrap: 'wrap' }}>{e.placas.map((pl) => <PcPlaca key={pl} p={pl} />)}</span> : e.placa ? <PcPlaca p={e.placa} /> : <span style={{ color: TOKENS.textSubtle }}>—</span>}</td>
            <td style={{ ...td, ...bl, whiteSpace: 'nowrap' }}>{nom(e.para)}</td>
            <td style={{ ...td, ...bl, whiteSpace: 'nowrap' }}>{e.estado === 'hecho' ? <>{[e.hecho && e.hecho.fecha, e.hecho && e.hecho.comprobante].filter(Boolean).join(' · ') || 'Hecho'}{e.hecho && e.hecho.foto && <button type="button" onClick={() => setFoto(e.hecho.foto)} style={{ marginLeft: 6, background: 'none', border: 0, color: TOKENS.primary, fontFamily: 'inherit', fontWeight: 700, cursor: 'pointer' }}>📷 Ver</button>}</> : e._sol ? (e._sol.estado === 'solicitud' ? <PcChip bg="#fdf0d5" fg="#8a5a00">Por planear</PcChip> : <PcChip bg={TOKENS.primaryBg} fg={TOKENS.primary}>En la ruta</PcChip>) : <PcChip bg="#fdf0d5" fg="#8a5a00">Pendiente</PcChip>}</td>
            <td style={{ ...td, ...bl, whiteSpace: 'nowrap', textAlign: 'right' }}>{e._sol ? (e._sol.estado === 'solicitud' ? <PcBtn tone="r" style={{ padding: '4px 9px', fontSize: 12 }} onClick={() => setConf(e)}>Quitar</PcBtn> : null) : e.estado !== 'hecho' ? <PcBtn tone="r" style={{ padding: '4px 9px', fontSize: 12 }} onClick={() => setConf(e)}>Quitar</PcBtn> : <PcBtn style={{ padding: '4px 9px', fontSize: 12 }} onClick={() => { window.reabrirEncargo(e.id); toast('Encargo reabierto'); }}>Reabrir</PcBtn>}</td>
          </tr>)}
          {!V.length && <tr><td colSpan={8} style={{ padding: 36, textAlign: 'center', color: TOKENS.textMuted, fontSize: 13 }}>{ver === 'pend' ? 'No hay tareas pendientes.' : 'Todavía no hay tareas hechas.'}</td></tr>}
        </tbody>
      </table>
    </div>
    <div style={{ fontSize: 12, color: TOKENS.textMuted }}>Le aparecen al mensajero en Tareas (Inicio y libreta). Si tiene placa y es Entregar, al marcarlo hecho puede poner la factura o remisión.</div>
    {nuevo && <PcAsignarEncargo onClose={() => setNuevo(false)} onGuardado={(e, r) => { setNuevo(false); toast(e ? `Tarea creada · ${e.que}` : `Suministro agregado · ${r.placa}`, 'g'); }} />}
    {conf && Modal && <Modal tone="danger" icon={I.trash(22, TOKENS.danger)} title="Quitar tarea" message={conf.que} confirmLabel="Quitar" onDismiss={() => setConf(null)} onConfirm={() => { if (conf._sol) { window.removeParada && window.removeParada(conf._sol.id); try { window.dispatchEvent(new Event('rodando-paradas')); } catch (x) {} } else window.quitarEncargo(conf.id); setConf(null); toast('Tarea quitada'); }} />}
    {foto && <div onClick={() => setFoto(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(11,28,48,.7)', zIndex: 1200, display: 'grid', placeItems: 'center', cursor: 'zoom-out' }}><img src={foto} alt="Soporte" style={{ maxWidth: '86vw', maxHeight: '86vh', borderRadius: 12 }} /></div>}
  </div>;
}
// 19/11/2026: ← vuelve un paso (a la ficha o a escoger placa); la X cierra todo.
function PcRegistrarEntrega({ regs, inicial, onClose, onGuardado, onCerrarTodo }) {
  const pend = regs.filter((r) => r._estado === 'pend' && !r._gar);
  const [sel, setSel] = React.useState(inicial ? [inicial] : []);
  const [q, setQ] = React.useState('');
  const [agregar, setAgregar] = React.useState(false);
  const [f, setF] = React.useState({ modo: 'mano', doc: 'Factura', num: '', recibe: '', transp: '', guia: '', fecha: pcHoyIso() });
  const [fotos, setFotos] = React.useState([]);
  const [toc, setToc] = React.useState({});
  const [confirmar, setConfirmar] = React.useState(false);
  const [srV, setSrV] = React.useState(() => window.srVacio ? window.srVacio() : { on: false, rines: [] });
  const set = (p) => setF((x) => ({ ...x, ...p }));
  const tocar = (k) => setToc((t) => t[k] ? t : { ...t, [k]: true });
  const placas = sel.map((id) => pend.find((r) => r.id === id)).filter(Boolean);
  // 25/11/2026: si la sede está en una ciudad donde el mensajero no recoge, se despacha por transportadora (César la lleva).
  const p0 = placas[0];
  React.useEffect(() => { if (p0 && window.catMensajeroRecoge && !window.catMensajeroRecoge(p0.taller, p0.sede) && f.modo === 'mano' && !fotos.length) set({ modo: 'transp' }); }, [p0 && p0.id]);
  // 23/11/2026: si en la revisión ya se marcaron rines que no se reparan, vienen marcados.
  React.useEffect(() => { if (placas.length === 1 && window.srDesdeServicios) setSrV(window.srDesdeServicios(placas[0])); if (placas.length === 1 && placas[0].cliente && !f.recibe) set({ recibe: placas[0].cliente.nombre }); }, [sel.join('|')]);
  const mano = f.modo === 'mano';
  const faltas = mano ? [f.num.trim().length < 3 && `número de ${f.doc.toLowerCase()}`, !fotos.length && `foto de la ${f.doc.toLowerCase()}`].filter(Boolean) :
  [f.transp.trim().length < 2 && 'transportadora', !fotos.length && 'foto de la guía'].filter(Boolean);
  const nRinesSr = placas.length === 1 && window.servRinesDeItems ? window.servRinesDeItems(placas[0].items).length : 0;
  if (nRinesSr && window.srFaltas) faltas.push(...window.srFaltas(srV));
  const inp = { ...pcInp, width: '100%' };
  const lblS = { ...pcLbl, marginBottom: 6 };
  const guardar = () => {
    const fechaEnt = pcDeIso(f.fecha);
    placas.forEach((r) => {
      window.markTicketDelivered(r._t, mano ?
      { factura: docGuardar(f.doc, f.num), comprobanteTipo: f.doc, fotos, recibePor: f.recibe.trim(), sinReparar: nRinesSr && window.srLista ? window.srLista(srV) : [] } :
      { factura: '', comprobanteTipo: '', fotos: [], recibePor: '', despacho: { despachado: true, transportadora: f.transp.trim(), guia: f.guia.trim(), guiaFotos: fotos }, sinReparar: nRinesSr && window.srLista ? window.srLista(srV) : [] });
      if (f.fecha !== pcHoyIso() && window.updateEntregaTicket) window.updateEntregaTicket(r.id, { fechaEntrega: fechaEnt, horaEntrega: '12:00' });
    });
    pcAvisar(); onGuardado(placas.length);
  };
  const lista = (excluir, alEscoger) => {
    const k = q.trim().toLowerCase();
    // 19/11/2026: por urgencia (Vencido → Retrasado → Vence hoy → En plazo, más días primero; Express desempata).
    // Las placas en pausa no aparecen: no se pueden entregar.
    const L = pend.filter((r) => !excluir.includes(r.id) && !(r._est && r._est.pausa) && (!k || `${r.placa} ${r.codigo} ${r.taller} ${r.sede}`.toLowerCase().includes(k)))
    .sort((a, b) => ((a._est ? a._est.orden : 9) - (b._est ? b._est.orden : 9)) || ((b._est ? b._est.dias : 0) - (a._est ? a._est.dias : 0)) || ((b.express ? 1 : 0) - (a.express ? 1 : 0)));
    const thS = { ...pcLbl, position: 'sticky', top: 0, zIndex: 1, background: TOKENS.surfaceLow, textAlign: 'left', padding: '9px 10px', borderBottom: `1px solid ${TOKENS.border}`, whiteSpace: 'nowrap' };
    const tdS = (i) => ({ padding: '10px', borderBottom: `1px solid ${TOKENS.border}`, borderLeft: i ? `1px solid ${TOKENS.border}` : 'none', whiteSpace: 'nowrap', verticalAlign: 'middle', fontWeight: 500 });
    return <>
      <input autoFocus value={q} onChange={(e) => setQ(e.target.value)} placeholder="Buscar placa, orden o taller" style={{ ...inp, marginBottom: 8 }} />
      <div style={{ fontSize: 11.5, color: TOKENS.textSubtle, margin: '0 2px 8px' }}>Las más urgentes primero · toca una para entregarla</div>
      <div style={{ border: `1px solid ${TOKENS.border}`, borderRadius: 12, overflow: 'auto', maxHeight: 460, background: TOKENS.surface }}>
        <table style={{ borderCollapse: 'separate', borderSpacing: 0, width: '100%', fontSize: 13 }}>
          <thead><tr>{['Placa', 'Orden', 'Taller · sede · ítems', 'Días', 'Estado'].map((t, i) => <th key={t} style={{ ...thS, borderLeft: i ? `1px solid ${TOKENS.border}` : 'none' }}>{t}</th>)}</tr></thead>
          <tbody>
            {L.map((r) =>
            <tr key={r.id} className="pc-fila" onClick={() => { setQ(''); alEscoger(r.id); }} style={{ cursor: 'pointer' }}>
                <td style={tdS(0)}><span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><PcPlaca p={r.placa} />{r.express && <PcChipExpress solo />}</span></td>
                <td style={{ ...tdS(1), fontFamily: pcMono }}>{r.codigo}</td>
                <td style={{ ...tdS(2), whiteSpace: 'normal' }}>{r.taller}{r.sede ? <span style={{ color: TOKENS.textMuted }}> · {r.sede}</span> : null}<div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>{pcItemsTxt(r.items)}</div></td>
                <td style={tdS(3)}>{r._est ? r._est.dias : 0}</td>
                <td style={tdS(4)}>{pcEstadoCelda(r)}</td>
              </tr>)}
            {!L.length && <tr><td colSpan={5} style={{ padding: 14, fontSize: 13, color: TOKENS.textMuted, textAlign: 'center' }}>No hay placas por entregar con esa búsqueda.</td></tr>}
          </tbody>
        </table>
      </div>
    </>;
  };
  const tarjetaPlaca = (r, quitar) =>
  <div key={r.id} style={{ display: 'flex', alignItems: 'center', gap: 12, background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 14, padding: '12px 14px', marginBottom: 10 }}>
      {window.CabeceraPlaca ? <window.CabeceraPlaca ticket={r} grande /> : <b style={{ fontFamily: pcMono, fontSize: 22 }}>{r.placa}</b>}
      <div style={{ flex: 1, textAlign: 'right', fontSize: 13, color: TOKENS.textMuted, minWidth: 0 }}><b style={{ color: TOKENS.text }}>{r.taller}{r.sede ? ' · ' + r.sede : ''}</b><br />{r.aseguradora} · {pcItemsTxt(r.items)}</div>
      {quitar && <button type="button" title="Quitar de esta guía" onClick={() => setSel((s) => s.filter((x) => x !== r.id))} style={{ width: 32, height: 32, borderRadius: 9, border: `1.5px solid ${TOKENS.borderInput}`, background: TOKENS.surface, color: TOKENS.danger, cursor: 'pointer' }}>✕</button>}
    </div>;
  const modoBtn = (v, ico, t, s2) => <ModoEntregaTile on={f.modo === v} icon={v === 'mano' ? I.check : I.truck} titulo={t} sub={s2} onClick={() => { set({ modo: v }); setFotos([]); if (v === 'mano') { setSel((x) => x.slice(0, 1)); setAgregar(false); } }} />;
  const Modal = window.ConfirmActionModal;
  if (!placas.length) {
    return (
      <PcDrawer ancho={560} fondo onClose={onCerrarTodo || onClose} titulo={<b style={{ fontSize: 17 }}>Registrar entrega</b>} pie={<><span style={{ flex: 1, fontSize: 12, color: TOKENS.textMuted, alignSelf: 'center' }}>Escoge la placa que se entrega.</span><PcBtn onClick={onClose}>Cancelar</PcBtn></>}>
        <PcSeccion titulo="¿Qué placa se entrega?">{lista([], (id) => setSel([id]))}</PcSeccion>
      </PcDrawer>);
  }
  return (
    <PcDrawer ancho={560} fondo onClose={onCerrarTodo || onClose} onAtras={inicial ? onClose : () => { setSel([]); setAgregar(false); }} atrasTxt={inicial ? 'Volver a la ficha' : 'Escoger otra placa'} titulo={<b style={{ fontSize: 17 }}>Registrar entrega</b>}
    pie={<><span style={{ flex: 1, fontSize: 12, color: TOKENS.textMuted, alignSelf: 'center' }}>{faltas.length ? 'Falta: ' + faltas.join(', ') : ''}</span>{inicial ? <PcBtn onClick={onClose}>Volver a la ficha</PcBtn> : <PcBtn onClick={() => { setSel([]); setAgregar(false); }}>Cambiar placa</PcBtn>}<PcBtn tone="p" disabled={faltas.length > 0} onClick={() => setConfirmar(true)}>Finalizar entrega</PcBtn></>}>
      {placas.map((r) => tarjetaPlaca(r, !mano && placas.length > 1))}
      {!mano && (agregar ?
      <PcSeccion titulo="Agregar otra placa a esta guía" der={<button type="button" onClick={() => setAgregar(false)} style={{ background: 'none', border: 0, color: TOKENS.primary, fontWeight: 800, fontSize: 12.5, cursor: 'pointer', fontFamily: 'inherit' }}>Cerrar</button>}>{lista(sel, (id) => { setSel((s) => [...s, id]); setAgregar(false); })}</PcSeccion> :
      <PcBtn style={{ width: '100%', borderStyle: 'dashed', marginBottom: 12 }} onClick={() => setAgregar(true)}>＋ Agregar otra placa a esta guía</PcBtn>)}
      <PcSeccion titulo="¿Cómo se entrega?">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          {modoBtn('mano', null, 'Directo', 'Factura o remisión')}
          {modoBtn('transp', null, 'Transportadora', 'Guía del envío · varias placas pueden ir juntas')}
        </div>
      </PcSeccion>
      {mano ?
      <PcSeccion titulo="Comprobante" der={<PcSeg value={f.doc} onChange={(v) => set({ doc: v })} options={[['Factura', 'Factura'], ['Remisión', 'Remisión']]} />}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <div><div style={lblS}>N.º de {f.doc.toLowerCase()} <span style={{ color: TOKENS.dangerText }}>*</span></div><PcToque onSalir={() => tocar('num')}><DocNumInput doc={f.doc} value={f.num} onChange={(v) => set({ num: v })} invalid={toc.num && f.num.trim().length < 3} /></PcToque><PcErr on={toc.num && f.num.trim().length < 3}>Escribe el número (mínimo 3 caracteres).</PcErr></div>
            <div><div style={lblS}>Fecha de entrega</div><input type="date" value={f.fecha} max={pcHoyIso()} onChange={(e) => set({ fecha: e.target.value })} style={inp} /></div>
            <div style={{ gridColumn: '1 / -1' }}><div style={lblS}>Recibe</div><input value={f.recibe} onChange={(e) => set({ recibe: e.target.value })} placeholder="Nombre de quien recibe (opcional)" style={inp} /></div>
          </div>
        </PcSeccion> :
      <PcSeccion titulo="Guía">
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <div><div style={lblS}>Transportadora <span style={{ color: TOKENS.dangerText }}>*</span></div><PcToque onSalir={() => tocar('transp')}><input value={f.transp} onChange={(e) => set({ transp: e.target.value })} placeholder="Ej: Servientrega" style={{ ...inp, ...(toc.transp && f.transp.trim().length < 2 ? PC_ROJO : {}) }} /></PcToque><PcErr on={toc.transp && f.transp.trim().length < 2}>Escribe la transportadora.</PcErr></div>
            <div><div style={lblS}>N.º de guía</div><input value={f.guia} onChange={(e) => set({ guia: e.target.value })} style={{ ...inp, fontFamily: pcMono }} /></div>
            <div><div style={lblS}>Fecha de entrega</div><input type="date" value={f.fecha} max={pcHoyIso()} onChange={(e) => set({ fecha: e.target.value })} style={inp} /></div>
          </div>
        </PcSeccion>}
      <PcSeccion titulo={<>Foto {mano ? `de la ${f.doc.toLowerCase()}` : 'de la guía'} <span style={{ color: TOKENS.dangerText }}>*</span></>} der={<span style={{ fontSize: 12, color: TOKENS.textSubtle }}>Al menos una</span>}>
        <PcFotosGrid fotos={fotos} setFotos={setFotos} max={5} />
      </PcSeccion>
      {nRinesSr > 0 && window.SinRepararCampos && <div style={{ marginTop: -4, marginBottom: 12 }}><window.SinRepararCampos nRines={nRinesSr} v={srV} setV={setSrV} /></div>}
      {confirmar && Modal && <Modal tone="primary" icon={I.check(24, TOKENS.primary)} title="Finalizar entrega" confirmLabel="Finalizar"
      ticket={placas.length === 1 ? placas[0] : null} message={`${placas.length === 1 ? '' : placas.map((r) => r.placa).join(', ') + ' · '}${mano ? `${f.doc} ${fmtComprobante({ factura: docGuardar(f.doc, f.num), comprobanteTipo: f.doc })}` : `${f.transp}${f.guia ? ' · guía ' + f.guia : ''}`} · ${pcFechaCorta(pcDeIso(f.fecha))}`}
      onDismiss={() => setConfirmar(false)} onConfirm={() => { setConfirmar(false); guardar(); }} />}
    </PcDrawer>);
}
// Filtro de fecha (14/11/2026): atajos a la izquierda y calendario de dos meses; se toca el día de
// inicio y el final, y Aplicar (como en la Business Suite). No deja escoger días futuros.
const PC_MESES = ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre'];
function PcFechaPop({ fecha, desde, hasta, onElegir, onCerrar }) {
  const hoyIso = pcHoyIso();
  const aD = (iso) => { const [y, m, d] = iso.split('-').map(Number); return new Date(y, m - 1, d); };
  const aIso = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
  const [modo, setModo] = React.useState(fecha);
  const [ini, setIni] = React.useState(fecha === 'rango' ? desde : '');
  const [fin, setFin] = React.useState(fecha === 'rango' ? hasta : '');
  const ref0 = aD(ini || hoyIso);
  const [base, setBase] = React.useState(() => { const d = new Date(ref0.getFullYear(), ref0.getMonth() - 1, 1); const h = aD(hoyIso); return d > new Date(h.getFullYear(), h.getMonth() - 1, 1) ? new Date(h.getFullYear(), h.getMonth() - 1, 1) : d; });
  const hoy = aD(hoyIso);
  const sig = new Date(base.getFullYear(), base.getMonth() + 1, 1);
  const puedeSig = new Date(base.getFullYear(), base.getMonth() + 2, 1) <= new Date(hoy.getFullYear(), hoy.getMonth(), 1);
  const tocar = (iso) => { setModo('rango'); if (!ini || fin) { setIni(iso); setFin(''); } else if (iso < ini) { setFin(ini); setIni(iso); } else setFin(iso); };
  const mes = (m0) => {
    const y = m0.getFullYear(), m = m0.getMonth(); const pri = (new Date(y, m, 1).getDay() + 6) % 7; const n = new Date(y, m + 1, 0).getDate();
    const celdas = [...Array(pri).fill(null), ...Array.from({ length: n }, (_, i) => aIso(new Date(y, m, i + 1)))];
    return (
      <div>
        <div style={{ textAlign: 'center', fontWeight: 800, fontSize: 13.5, marginBottom: 8 }}>{PC_MESES[m][0].toUpperCase() + PC_MESES[m].slice(1)} {y}</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 34px)', rowGap: 2 }}>
          {['L', 'M', 'M', 'J', 'V', 'S', 'D'].map((d, i) => <span key={'h' + i} style={{ height: 28, display: 'grid', placeItems: 'center', fontSize: 10.5, fontWeight: 700, color: TOKENS.textSubtle }}>{d}</span>)}
          {celdas.map((iso, i) => { if (!iso) return <span key={i} />;
            const fut = iso > hoyIso, extremo = iso === ini || iso === fin, dentro = ini && fin && iso > ini && iso < fin;
            return <button key={iso} type="button" disabled={fut} onClick={() => tocar(iso)} style={{ height: 32, border: 0, fontFamily: 'inherit', fontSize: 13, cursor: fut ? 'not-allowed' : 'pointer', color: fut ? TOKENS.textSubtle : extremo ? '#fff' : TOKENS.text, background: extremo ? TOKENS.primary : dentro ? TOKENS.primaryBg : 'transparent', borderRadius: extremo ? 8 : 0, fontWeight: extremo || iso === hoyIso ? 800 : 500, textDecoration: iso === hoyIso && !extremo ? 'underline' : 'none' }}>{Number(iso.slice(8))}</button>; })}
        </div>
      </div>);
  };
  const nav = (dis) => ({ width: 28, height: 28, border: `1px solid ${TOKENS.border}`, background: TOKENS.surface, borderRadius: 8, cursor: dis ? 'not-allowed' : 'pointer', opacity: dis ? 0.4 : 1, fontFamily: 'inherit' });
  return (
    <div style={{ position: 'absolute', top: 'calc(100% + 6px)', left: 0, ...pcCard, borderRadius: 14, boxShadow: '0 14px 34px rgba(11,28,48,.18)', zIndex: 50, display: 'flex' }}>
      <div style={{ width: 170, borderRight: `1px solid ${TOKENS.border}`, padding: 8 }}>
        {[['todas', 'Todas las fechas'], ['hoy', 'Hoy'], ['semana', 'Esta semana'], ['mes', 'Este mes'], ['rango', 'Rango personalizado']].map(([v, l]) =>
        <button key={v} type="button" onClick={() => v === 'rango' ? setModo('rango') : onElegir({ fecha: v, desde: '', hasta: '' })} style={{ display: 'block', width: '100%', textAlign: 'left', border: 0, borderRadius: 8, padding: '9px 10px', fontFamily: 'inherit', fontSize: 13.5, cursor: 'pointer', background: modo === v ? TOKENS.primaryBg : 'transparent', color: modo === v ? TOKENS.primary : TOKENS.text, fontWeight: modo === v ? 800 : 500 }}>{l}</button>)}
      </div>
      <div style={{ padding: '12px 16px' }}>
        <div style={{ display: 'flex', alignItems: 'center', marginBottom: 6 }}>
          <button type="button" style={nav(false)} onClick={() => setBase(new Date(base.getFullYear(), base.getMonth() - 1, 1))}>‹</button><span style={{ flex: 1 }} />
          <button type="button" style={nav(!puedeSig)} disabled={!puedeSig} onClick={() => setBase(sig)}>›</button>
        </div>
        <div style={{ display: 'flex', gap: 22 }}>{mes(base)}{mes(sig)}</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 10, paddingTop: 10, borderTop: `1px solid ${TOKENS.border}`, fontSize: 12.5, color: TOKENS.textMuted }}>
          <span style={{ flex: 1 }}>{ini ? <>Desde <b style={{ color: TOKENS.text }}>{pcFechaCorta(pcDeIso(ini))}</b> hasta <b style={{ color: TOKENS.text }}>{fin ? pcFechaCorta(pcDeIso(fin)) : '…'}</b></> : 'Toca el día de inicio y luego el día final.'}</span>
          <PcBtn style={{ padding: '7px 12px' }} onClick={onCerrar}>Cancelar</PcBtn>
          <PcBtn tone="p" style={{ padding: '7px 12px' }} disabled={!ini} onClick={() => onElegir({ fecha: 'rango', desde: ini, hasta: fin || ini })}>Aplicar</PcBtn>
        </div>
      </div>
    </div>);
}
// Registros = historial de todo lo recogido (14/11/2026). Abre en Todos, lo más reciente primero.
// Fecha y Orden (único) quedan fijos al moverse a los lados.
const PC_FECHAS = [['todas', 'Todas las fechas'], ['hoy', 'Hoy'], ['semana', 'Esta semana'], ['mes', 'Este mes'], ['rango', 'Rango…']];
function pcEnFecha(iso, f) {
  if (!f || f.fecha === 'todas' || !f.fecha) return true;
  const hoy = pcHoyIso();
  if (f.fecha === 'hoy') return iso === hoy;
  if (f.fecha === 'semana') { const d = new Date(); const dia = (d.getDay() + 6) % 7; d.setDate(d.getDate() - dia); const ini = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; return iso >= ini && iso <= hoy; }
  if (f.fecha === 'mes') return iso >= hoy.slice(0, 8) + '01' && iso <= hoy;
  return (!f.desde || iso >= f.desde) && (!f.hasta || iso <= f.hasta);
}
// 19/11/2026: la celda dice solo el estado (sin "a tiempo / tarde"); el cumplimiento se lee en Días.
function pcEstadoCelda(x) {
  if (x._estado === 'anu') return <PcChip bg={TOKENS.anuladoBg} fg={TOKENS.anulado}>Anulado</PcChip>;
  if (x._estado === 'ent') return <PcChip bg="#1c7c46" fg="#fff">Entregado</PcChip>;
  if (x._gar) return <PcChip bg="#e6f7fa" fg="#0e7490">Garantía</PcChip>;
  if (x._est && x._est.pausa) return <PcChipPausa />;
  return x._est ? <PcChipEst k={x._est.orden} /> : null;
}
// Días "N de M": lo que lleva y el plazo que le toca.
function pcDiasPlazo(x) {
  if (x._estado === 'anu') return null;
  const m = x._gar ? ((window.loadCatServicios ? window.loadCatServicios().slaGarantia : 2) || 2) : pcSlaDe(!!x.express);
  const n = x._estado === 'ent' ? (x._dias || 0) : x._est ? (x._est.dias || 0) : 0;
  return { n, m, tarde: n > m };
}
function PcDiasCelda({ x }) {
  const d = pcDiasPlazo(x); if (!d) return <span style={{ color: TOKENS.textSubtle }}>—</span>;
  return <span>{d.n}</span>;
}
const pcFacturaTxt = (e) => !e ? '' : e.despachado ? `Guía ${e.guia || ''}${e.transportadora ? ' (' + e.transportadora + ')' : ''}` : e.factura ? pcComprobante(e) : '';
const pcComprobante = (e) => window.fmtComprobante ? window.fmtComprobante(e) : (e.factura || '');
// 22/11/2026: novedad de un rin: 'nr' No reparable | 'na' No autorizado (servicios o registro de entrega).
function pcNovedadRin(rr, e, i) {
  const sr = (rr && rr.sinReparar) || (e && (e.sinReparar || []).find((x) => x.i === i));
  if (sr) return /autoriz/i.test(sr.motivo || '') ? 'na' : 'nr';
  if (rr && rr.aut && rr.aut.estado === 'no') return 'na';
  return null;
}
function PcChipNovedad({ t }) {
  const c = t === 'na' ? ['#efe9f7', '#6c4aa6', 'No autorizado'] : ['#fbe3e1', '#9c443c', 'No reparable'];
  return <span style={{ background: c[0], color: c[1], fontSize: 11.5, fontWeight: 500, borderRadius: 99, padding: '2px 8px', whiteSpace: 'nowrap' }}>{c[2]}</span>;
}
function PcRegistros({ regs, filtro, setFiltro, onEditTicket, toast }) {
  const [selId, setSelId] = React.useState(null);
  const [drawer, setDrawer] = React.useState(null); // 'rec' | {ent: id|null}
  const [anular, setAnular] = React.useState(null);
  const [editar, setEditar] = React.useState(null);
  const [reactivar, setReactivar] = React.useState(null);
  const RM = (window.PC_MEMO = window.PC_MEMO || {}).reg || {};
  const [pag, setPag] = React.useState(RM.pag || 0);
  const [porPag, setPorPag] = React.useState(RM.porPag || 50);
  const [orden, setOrden] = React.useState(RM.orden || null); // { k, dir }
  React.useEffect(() => { window.PC_MEMO.reg = { pag, porPag, orden }; }, [pag, porPag, orden]);
  const [fpop, setFpop] = React.useState(false);
  const tablaRef = React.useRef(null);
  // Los botones de la barra del título abren los formularios.
  React.useEffect(() => { const f = (e) => setDrawer(e.detail === 'rec' ? 'rec' : e.detail === 'enc' ? 'enc' : { ent: null }); window.addEventListener('pc-registrar', f); return () => window.removeEventListener('pc-registrar', f); }, []);
  React.useEffect(() => { if (!fpop) return; const f = (e) => { if (!e.target.closest('[data-pc-fecha]')) setFpop(false); }; document.addEventListener('mousedown', f); return () => document.removeEventListener('mousedown', f); }, [fpop]);
  const { tab = 'todos', est = null, taller = '', aseg = '', q = '', fecha = 'todas', desde = '', hasta = '', sinsv = false, exp = false, gar = false, nov = false, novT = 'todas' } = filtro;
  const [abiertas, setAbiertas] = React.useState({});
  const SR = {}; regs.forEach((x) => { SR[x.id] = typeof servResumen === 'function' ? servResumen(x) : { txt: '', total: 0, siniestro: '', rines: [], con: false, n: 0 }; });
  const set = (p) => { setFiltro({ ...filtro, ...p }); setPag(0); if (tablaRef.current) tablaRef.current.scrollTop = 0; };
  const k = q.trim().toLowerCase();
  const base = regs.filter((r) => pcEnFecha(r._iso, { fecha, desde, hasta }) && (!taller || r.taller === taller) && (!aseg || r.aseguradora === aseg) &&
  (!k || `${r.placa} ${r.codigo} ${r.taller} ${r.sede} ${r.aseguradora} ${pcFacturaTxt(r._ent)} ${SR[r.id].siniestro} ${(r.items || []).map(pcItemDetalle).join(' ')}`.toLowerCase().includes(k)));
  const conteo = { todos: base.length, pend: base.filter((x) => x._estado === 'pend').length, ent: base.filter((x) => x._estado === 'ent').length, anu: base.filter((x) => x._estado === 'anu').length };
  const valorCol = (x, c) => ({ f: x._iso, c: Number(x.codigo) || 0, p: x.placa, a: x.aseguradora, t: `${x.taller} ${x.sede || ''}`, it: (x.items || []).reduce((n, i) => n + (Number(i.cantidad) || 0), 0),
    d: x._estado === 'ent' ? x._dias : x._est ? x._est.dias : -1, e: x._estado === 'anu' ? 9 : x._estado === 'ent' ? 4 + (3 - x._plazo) / 10 : x._est ? x._est.orden : 5,
    en: x._estado === 'ent' ? 1 : 0, fe: x._isoEnt || '', fa: pcFacturaTxt(x._ent), por: x._ent ? x._ent.entregadoPorNombre || '' : '', sv: SR[x.id].txt, tv: SR[x.id].total, si: SR[x.id].siniestro })[c];
  const sinServ = (r) => r._estado !== 'anu' && SR[r.id].n > 0 && !SR[r.id].con;
  const nSin = base.filter((r) => (tab === 'todos' || r._estado === tab) && sinServ(r)).length;
  const nExp = base.filter((r) => (tab === 'todos' || r._estado === tab) && r.express).length;
  const tieneGar = (r) => !!(window.garantiasDe && window.garantiasDe(r.id).length);
  const nGar = base.filter((r) => (tab === 'todos' || r._estado === tab) && tieneGar(r)).length;
  // 23/11/2026: novedades de la placa (rin en pausa, no reparable, no autorizado).
  const novsDe = (r) => r._estado === 'anu' ? [] : [...new Set(SR[r.id].rines.map((rr, i) => rr.aut && rr.aut.estado === 'espera' ? 'pausa' : pcNovedadRin(rr, r._ent, i)).filter(Boolean))];
  const novOk = (r) => { const n = novsDe(r); return n.length && (novT === 'todas' || n.includes(novT)); };
  const baseTab = base.filter((r) => tab === 'todos' || r._estado === tab);
  const nNov = baseTab.filter((r) => novsDe(r).length).length;
  const L = base.filter((r) => (tab === 'todos' || r._estado === tab) && (est == null || (est === 'p' ? !!(r._est && r._est.pausa) : !!(r._est && !r._est.pausa && r._est.orden === est))) && (!sinsv || sinServ(r)) && (!exp || r.express) && (!gar || tieneGar(r)) && (!nov || novOk(r)));
  if (orden) L.sort((a, b) => { const va = valorCol(a, orden.k), vb = valorCol(b, orden.k); if ((va === '' || va == null) !== (vb === '' || vb == null)) return va === '' || va == null ? 1 : -1; return (va > vb ? 1 : va < vb ? -1 : 0) * orden.dir; });else
  // Orden (19/11/2026), igual que el celular. Por entregar: urgencia (Express solo desempata).
  // Resto: garantía abierta > Express pendiente > lo demás, y lo más reciente primero.
  if (tab === 'pend') L.sort((a, b) => ((a._est ? a._est.orden : 9) - (b._est ? b._est.orden : 9)) || ((b._est ? b._est.dias : 0) - (a._est ? a._est.dias : 0)) || ((b.express ? 1 : 0) - (a.express ? 1 : 0)));else {
    const rango = (r) => r._gar ? 0 : (r.express && r._estado === 'pend') ? 1 : 2;
    L.sort((a, b) => rango(a) - rango(b) || (b._iso || '').localeCompare(a._iso || '') || (Number(b.codigo) || 0) - (Number(a.codigo) || 0));
  }
  const paginas = Math.max(1, Math.ceil(L.length / porPag)); const pg = Math.min(pag, paginas - 1);
  const P = L.slice(pg * porPag, (pg + 1) * porPag);
  const talleres = [...new Set(regs.map((r) => r.taller))].sort((a, b) => a.localeCompare(b, 'es'));
  const asegs = [...new Set(regs.map((r) => r.aseguradora))].sort((a, b) => a.localeCompare(b, 'es'));
  const r = selId ? regs.find((x) => x.id === selId) : null;
  const Modal = window.ConfirmActionModal, AnuModal = window.AnularTicketModal;
  const hayFiltros = q || fecha !== 'todas' || taller || aseg || tab !== 'todos' || est != null || sinsv || exp || gar || nov;
  const fechaTxt = fecha === 'rango' && desde ? (desde === hasta || !hasta ? pcFechaCorta(pcDeIso(desde)) : `${pcFechaCorta(pcDeIso(desde))} – ${pcFechaCorta(pcDeIso(hasta))}`) : (PC_FECHAS.find((x) => x[0] === fecha) || PC_FECHAS[0])[1].replace('…', '');
  const COLS = [['f', 'Fecha', 0], ['c', 'Orden', 92], ['p', 'Placa'], ['a', 'Aseguradora'], ['t', 'Taller · sede'], ['it', 'Ítems'], ['d', 'Días'], ['e', 'Estado'], ...(nov ? [['nv', 'Novedad']] : []), ['sv', 'Servicios'], ['tv', 'Total sin IVA'], ['fa', 'Factura / remisión'], ['si', 'Siniestro'], ['en', 'Entregado'], ['fe', 'Fecha de entrega'], ['por', 'Entregó']];
  const fijo = (left, extra) => left == null ? {} : { position: 'sticky', left, zIndex: extra ? 3 : 1, boxSizing: 'border-box', ...(left === 92 ? { boxShadow: '6px 0 6px -6px rgba(11,28,48,.18)', width: 76, minWidth: 76, maxWidth: 76 } : { width: 92, minWidth: 92, maxWidth: 92, paddingRight: 6 }) };
  // Líneas entre columnas (19/11/2026): mismo gris de las filas.
  const th = { ...pcLbl, position: 'sticky', top: 0, background: TOKENS.surfaceLow, textAlign: 'left', padding: '10px 12px', borderBottom: `1px solid ${TOKENS.border}`, borderRight: `1px solid ${TOKENS.border}`, zIndex: 2, whiteSpace: 'nowrap', cursor: 'pointer', userSelect: 'none' };
  // 19/11/2026: un solo peso (500) en todo el cuerpo; solo la placa en negrita.
  const td = { padding: '10px 12px', borderBottom: `1px solid ${TOKENS.border}`, borderRight: `1px solid ${TOKENS.border}`, whiteSpace: 'nowrap', background: TOKENS.surface, fontWeight: 500 };
  const vacio = <span style={{ color: TOKENS.textSubtle }}>—</span>;
  const ordenarPor = (c) => setOrden((o) => o && o.k === c ? { k: c, dir: -o.dir } : { k: c, dir: c === 'f' || c === 'd' || c === 'fe' || c === 'c' ? -1 : 1 });
  const segOpts = [['todos', 'Todos', null], ['pend', 'Por entregar', '#f2c037'], ['ent', 'Entregados', '#1c7c46'], ['anu', 'Anulados', TOKENS.anulado]];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12, height: '100%', minHeight: 0 }}>
      <div style={{ ...pcCard, borderRadius: 16, padding: 12, display: 'flex', flexDirection: 'column', gap: 10 }}>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <div style={{ flex: '0 1 420px', minWidth: 240, position: 'relative' }}>
            <span style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', display: 'flex' }}>{I.consultar(16, TOKENS.textMuted)}</span>
            <input value={q} onChange={(e) => set({ q: e.target.value })} placeholder="Buscar placa, orden, factura, siniestro, taller…" style={{ ...pcInp, width: '100%', background: TOKENS.surfaceLow, borderRadius: 12, padding: '11px 14px 11px 38px', fontSize: 14 }} />
          </div>
          <div data-pc-fecha style={{ position: 'relative' }}>
            <button type="button" onClick={() => setFpop((v) => !v)} style={{ display: 'flex', alignItems: 'center', gap: 8, border: `1px solid ${TOKENS.borderInput}`, background: TOKENS.surface, borderRadius: 12, padding: '10px 14px', fontFamily: 'inherit', fontSize: 14, fontWeight: 700, cursor: 'pointer', color: TOKENS.text, whiteSpace: 'nowrap' }}>{I.cal(16, TOKENS.text)} {fechaTxt} {I.chev(14, TOKENS.textMuted)}</button>
            {fpop && <PcFechaPop fecha={fecha} desde={desde} hasta={hasta} onElegir={(p) => { set(p); setFpop(false); }} onCerrar={() => setFpop(false)} />}
          </div>
        </div>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
          <div style={{ display: 'inline-flex', background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 12, padding: 4, gap: 2 }}>
            {segOpts.map(([v, l, c]) => { const on = tab === v; return (
              <button key={v} type="button" onClick={() => set({ tab: v, est: null })} style={{ border: 0, borderRadius: 9, padding: '7px 12px', fontFamily: 'inherit', fontSize: 13, fontWeight: 700, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 7, whiteSpace: 'nowrap', background: on ? TOKENS.surface : 'transparent', color: on ? TOKENS.text : TOKENS.textMuted, boxShadow: on ? '0 1px 3px rgba(11,28,48,.12)' : 'none' }}>
                  {c && <span style={{ width: 9, height: 9, borderRadius: 99, background: c }} />}{l}
                  <span style={{ fontSize: 11.5, fontWeight: 500, borderRadius: 99, padding: '1px 5px', minWidth: 26, textAlign: 'center', boxSizing: 'border-box', fontVariantNumeric: 'tabular-nums', background: on ? TOKENS.primaryBg : TOKENS.border, color: on ? TOKENS.primary : TOKENS.textMuted }}>{conteo[v]}</span>
                </button>); })}
          </div>
          <span style={{ width: 1, height: 28, background: TOKENS.border, margin: '0 2px' }} />
          <div style={{ width: 210 }}>{window.Select && <window.Select value={taller} searchable options={[{ value: '', label: 'Todos los talleres' }, ...talleres.map((t) => ({ value: t, label: t }))]} onChange={(v) => set({ taller: v })} />}</div>
          <div style={{ width: 230 }}>{window.Select && <window.Select value={aseg} searchable options={[{ value: '', label: 'Todas las aseguradoras' }, ...asegs.map((t) => ({ value: t, label: t }))]} onChange={(v) => set({ aseg: v })} />}</div>
        </div>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
          {tab === 'pend' && (() => {
            // 21/11/2026: chips de estado de Por entregar, como en el celular (con su conteo).
            const P = base.filter((x) => x._estado === 'pend' && (!sinsv || sinServ(x)) && (!exp || x.express) && (!gar || tieneGar(x)));
            const ops = [[0, 'Vencido', PC_EST[0]], [1, 'Retrasado', PC_EST[1]], [2, 'Vence hoy', PC_EST[2]], [3, 'En plazo', PC_EST[3]], ['p', 'En pausa', ['', PAUSA_COLOR.bg, PAUSA_COLOR.fg, PAUSA_COLOR.solid]]];
            return <span style={{ display: 'inline-flex', gap: 6, flexWrap: 'wrap' }}>{ops.map(([k, l, c]) => { const n = P.filter((x) => k === 'p' ? x._est && x._est.pausa : x._est && !x._est.pausa && x._est.orden === k).length; const on = est === k; return (
              <button key={k} type="button" onClick={() => set({ est: on ? null : k })} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, borderRadius: 999, padding: '5px 10px', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 600, cursor: 'pointer', border: `1px solid ${on ? c[3] : TOKENS.borderInput}`, background: on ? c[1] : TOKENS.surface, color: on ? c[2] : TOKENS.text }}>
                <span style={{ width: 8, height: 8, borderRadius: 99, background: c[3] }} />{l}<span style={{ fontSize: 11, fontWeight: 500, color: on ? c[2] : TOKENS.textMuted }}>{n}</span></button>); })}</span>;
          })()}
          {tab === 'pend' && <span style={{ width: 1, height: 28, background: TOKENS.border, margin: '0 2px' }} />}
          <PcBtn style={{ padding: '8px 11px', fontSize: 12.5, ...(sinsv ? { background: TOKENS.primary, color: '#fff', border: 'none' } : {}) }} onClick={() => set({ sinsv: !sinsv })}>Sin servicios <span style={{ marginLeft: 4, fontSize: 11, fontWeight: 500, borderRadius: 99, padding: '1px 5px', minWidth: 26, textAlign: 'center', display: 'inline-block', boxSizing: 'border-box', fontVariantNumeric: 'tabular-nums', background: sinsv ? 'rgba(255,255,255,.22)' : '#fff2cc', color: sinsv ? '#fff' : '#7f6000' }}>{nSin}</span></PcBtn>
          <PcBtn style={{ padding: '8px 11px', fontSize: 12.5, ...(exp ? { background: '#fce7f3', color: '#be185d', border: '1px solid #e879b0' } : {}) }} onClick={() => set({ exp: !exp })}>⚡ Express <span style={{ marginLeft: 4, fontSize: 11, fontWeight: 500, borderRadius: 99, padding: '1px 5px', minWidth: 26, textAlign: 'center', display: 'inline-block', boxSizing: 'border-box', fontVariantNumeric: 'tabular-nums', background: exp ? '#fff' : '#fce7f3', color: '#be185d' }}>{nExp}</span></PcBtn>
          <PcBtn style={{ padding: '8px 11px', fontSize: 12.5, color: '#0e7490', ...(gar ? { background: '#e6f7fa', color: '#0e7490', border: '1px solid #5bb8cc' } : {}) }} onClick={() => set({ gar: !gar })}>↺ Garantía <span style={{ marginLeft: 4, fontSize: 11, fontWeight: 500, borderRadius: 99, padding: '1px 5px', minWidth: 26, textAlign: 'center', display: 'inline-block', boxSizing: 'border-box', fontVariantNumeric: 'tabular-nums', background: gar ? '#fff' : '#e6f7fa', color: '#0e7490' }}>{nGar}</span></PcBtn>
          <PcBtn style={{ padding: '8px 11px', fontSize: 12.5, ...(nov ? { background: TOKENS.primary, color: '#fff', border: 'none' } : {}) }} onClick={() => set({ nov: !nov, novT: 'todas' })}>◆ Con novedad <span style={{ marginLeft: 4, fontSize: 11, fontWeight: 500, borderRadius: 99, padding: '1px 5px', minWidth: 26, textAlign: 'center', display: 'inline-block', boxSizing: 'border-box', fontVariantNumeric: 'tabular-nums', background: nov ? 'rgba(255,255,255,.22)' : TOKENS.surfaceLow, color: nov ? '#fff' : TOKENS.textMuted }}>{nNov}</span></PcBtn>
          {hayFiltros && <PcBtn style={{ padding: '7px 12px' }} onClick={() => { setFiltro({ tab: 'todos' }); setOrden(null); setPag(0); }}>Limpiar filtros</PcBtn>}
          <span style={{ marginLeft: 'auto', fontSize: 12.5, color: TOKENS.textMuted, whiteSpace: 'nowrap', flexShrink: 0 }}>{L.length} {L.length === 1 ? 'placa' : 'placas'}</span>
        </div>
        {nov && <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 8, flexWrap: 'wrap' }}><span style={{ fontSize: 12, color: TOKENS.textMuted }}>Novedad:</span>
          {[['todas', 'Todas', null], ['pausa', 'En pausa', PAUSA_COLOR.bg, PAUSA_COLOR.fg], ['nr', 'No reparable', '#fbe3e1', '#9c443c'], ['na', 'No autorizado', '#efe9f7', '#6c4aa6']].map(([k, l, bg, fg]) => { const on = novT === k; const n = k === 'todas' ? nNov : baseTab.filter((r) => novsDe(r).includes(k)).length; return <button key={k} type="button" onClick={() => set({ novT: k })} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, border: `1px solid ${on ? TOKENS.primary : TOKENS.borderInput}`, background: on ? TOKENS.primary : TOKENS.surface, color: on ? '#fff' : TOKENS.text, borderRadius: 99, padding: '4px 10px', fontFamily: 'inherit', fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>{bg ? <span style={{ fontSize: 11, fontWeight: 500, borderRadius: 99, padding: '1px 7px', background: bg, color: fg }}>{l}</span> : l} {n}</button>; })}
        </div>}
      </div>
      <div ref={tablaRef} style={{ ...pcCard, overflow: 'auto', flex: 1, minHeight: 200 }}>
        <table style={{ borderCollapse: 'separate', borderSpacing: 0, fontSize: 13, minWidth: 1980, width: '100%' }}>
          <thead><tr>{COLS.map(([c, l, left]) => <th key={c} onClick={() => ordenarPor(c)} style={{ ...th, ...fijo(left, true) }}>{l}{orden && orden.k === c && <span style={{ color: TOKENS.primary, marginLeft: 4 }}>{orden.dir > 0 ? '▲' : '▼'}</span>}</th>)}</tr></thead>
          <tbody>
            {P.map((x) => { const e = x._ent; const sel = selId === x.id; const bg = sel ? { background: TOKENS.primaryBg } : {}; const sv = SR[x.id]; const pzN = sv.rines.filter((q) => q.aut && q.aut.estado === 'espera').length; const novs = sv.rines.map((q, k) => pcNovedadRin(q, e, k)); const nNov = novs.filter(Boolean).length; const multi = sv.n > 1 && (sv.con || nNov > 0) && (new Set(sv.rines.map((q) => servCodigo(q) + '|' + servValor(q))).size > 1 || pzN > 0 || nNov > 0); const ab = !!abiertas[x.id]; return (
              <React.Fragment key={x.id + x._estado}>
              <tr className="pc-fila" onClick={() => setSelId(x.id)} style={{ cursor: 'pointer' }}>
                  <td style={{ ...td, ...fijo(0), ...bg }}>{pcFechaCorta(x.fecha)}</td>
                  <td style={{ ...td, ...fijo(92), ...bg, fontFamily: pcMono }}>{x.codigo}</td>
                  <td style={{ ...td, ...bg }}><span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}><PcPlaca p={x.placa} />{window.InsigniasPlaca && <window.InsigniasPlaca ticket={{ ...x, id: x.id }} alto={24} />}</span>{x._estado === 'ent' && window.correccionEnEspera && window.correccionEnEspera(x.id) && <span style={{ marginLeft: 6 }}><window.ChipCorreccion /></span>}</td>
                  <td style={{ ...td, ...bg }}>{x.aseguradora}</td>
                  <td style={{ ...td, ...bg }}>{x.taller}{x.sede ? <span style={{ color: TOKENS.textMuted }}> · {x.sede}</span> : null}</td>
                  <td style={{ ...td, ...bg }}><div style={{ display: 'flex', alignItems: 'center', gap: 10 }}><span>{pcItemsTxt(x.items)}</span>{!multi && novs.filter(Boolean).map((t, k) => <PcChipNovedad key={k} t={t} />)}{multi && <button type="button" title={ab ? 'Ocultar cada rin' : 'Ver cada rin'} onClick={(ev) => { ev.stopPropagation(); setAbiertas((m) => ({ ...m, [x.id]: !m[x.id] })); }} style={{ marginLeft: 'auto', width: 28, height: 28, borderRadius: 8, border: `1px solid ${ab ? TOKENS.primary : TOKENS.primaryBorder}`, background: ab ? TOKENS.primary : TOKENS.primaryBg, color: ab ? '#fff' : TOKENS.primary, display: 'grid', placeItems: 'center', cursor: 'pointer', flexShrink: 0 }}><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round" style={{ transform: ab ? 'rotate(180deg)' : 'none', transition: 'transform .15s' }}><path d="M6 9l6 6 6-6" /></svg></button>}</div></td>
                  <td style={{ ...td, ...bg }}><PcDiasCelda x={x} /></td>
                  <td style={{ ...td, ...bg }}>{multi && ab ? <span style={{ color: TOKENS.textSubtle, fontStyle: 'italic', fontSize: 12.5 }}>Por rin ↓</span> : <>{pcEstadoCelda(x)}{pzN > 0 && <span style={{ fontSize: 12, color: TOKENS.textMuted }}> · {pzN} de {sv.n}</span>}</>}</td>
                  {nov && <td style={{ ...td, ...bg }}><span style={{ display: 'inline-flex', gap: 4, flexWrap: 'wrap' }}>{novsDe(x).map((t) => t === 'pausa' ? <PcChipPausa key={t} /> : <PcChipNovedad key={t} t={t} />)}</span></td>}
                  <td style={{ ...td, ...bg }}>{multi && ab ? <span style={{ color: TOKENS.textSubtle, fontStyle: 'italic', fontSize: 12.5 }}>Por rin ↓</span> : x._estado === 'anu' || !sv.n ? vacio : sv.con ? <ServChips sv={sv} /> : <PcChip bg="#fff2cc" fg="#7f6000">Sin servicios</PcChip>}</td>
                  <td style={{ ...td, ...bg, textAlign: 'right' }}>{sv.total ? pcPesos(sv.total) : vacio}</td>
                  <td style={{ ...td, ...bg }}>{pcFacturaTxt(e) || vacio}</td>
                  <td style={{ ...td, ...bg, fontFamily: pcMono }}>{sv.siniestro || vacio}</td>
                  <td style={{ ...td, ...bg }}>{e ? 'Sí' : <span style={{ color: TOKENS.textSubtle }}>No</span>}</td>
                  <td style={{ ...td, ...bg }}>{e ? pcFechaCorta(e.fechaEntrega) : vacio}</td>
                  <td style={{ ...td, ...bg }}>{(e && e.entregadoPorNombre) || vacio}</td>
                </tr>
              {multi && ab && sv.rines.map((rr, i) => { const esp = rr.aut && rr.aut.estado === 'espera'; const otro = sv.rines.map((q, k) => k).filter((k) => sv.rines[k].aut && sv.rines[k].aut.estado === 'espera' && k !== i); const nov = novs[i]; const sb = { ...td, background: '#f8faff' }; const ten = { ...sb, color: '#c3ccd9' }; const tach = nov ? { textDecoration: 'line-through', opacity: .55 } : {}; return (
                <tr key={'r' + i} onClick={() => setSelId(x.id)} style={{ cursor: 'pointer' }}>
                  <td style={{ ...ten, ...fijo(0), background: '#f8faff', borderLeft: `3px solid ${TOKENS.primaryBorder}` }}>{pcFechaCorta(x.fecha)}</td>
                  <td style={{ ...ten, ...fijo(92), background: '#f8faff', fontFamily: pcMono }}>{x.codigo}</td>
                  <td style={ten}><span style={{ fontFamily: pcMono, fontWeight: 700, border: '1px solid #edf0f5', background: '#fafbfd', borderRadius: 6, padding: '2px 6px' }}>{x.placa}</span></td>
                  <td style={ten}>{x.aseguradora}</td>
                  <td style={ten}>{x.taller}{x.sede ? ' · ' + x.sede : ''}</td>
                  <td style={{ ...sb, fontSize: 12.5, paddingLeft: 24 }}><span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>Rin {i + 1}{nov && <PcChipNovedad t={nov} />}</span></td>
                  <td style={ten}>{(pcDiasPlazo(x) || {}).n ?? ''}</td>
                  <td style={{ ...sb, fontSize: 12.5 }}>{esp ? <><PcChipPausa /><span style={{ color: PAUSA_COLOR.fg }}> · {rr.aut.motivo}</span></> : nov ? pcEstadoCelda(x) : pzN > 0 ? <><PcChipPausa /><span style={{ color: TOKENS.textMuted }}> · espera al rin {otro.map((k) => k + 1).join(', ')}</span></> : pcEstadoCelda(x)}</td>
                  {nov && <td style={ten} />}
                  <td style={sb}>{servCodigo(rr) ? <span style={{ ...SERV_CHIP, fontSize: 12, fontWeight: 500, borderRadius: 6, padding: '2px 7px', display: 'inline-block', ...tach }}>{servCodigo(rr)}</span> : vacio}</td>
                  <td style={{ ...sb, textAlign: 'right', fontSize: 12.5 }}>{nov ? <span style={tach}>{Number(rr.precio) ? pcPesos(Number(rr.precio)) : '$ 0'}</span> : servValor(rr) ? pcPesos(servValor(rr)) : vacio}</td>
                  <td style={nov ? { ...sb, ...tach } : ten}>{pcFacturaTxt(e) || ''}</td>
                  <td style={nov ? { ...sb, ...tach, fontFamily: pcMono } : { ...ten, fontFamily: pcMono }}>{sv.siniestro || ''}</td>
                  <td style={ten}>{e ? 'Sí' : 'No'}</td>
                  <td style={ten}>{e ? pcFechaCorta(e.fechaEntrega) : ''}</td>
                  <td style={ten}>{(e && e.entregadoPorNombre) || ''}</td>
                </tr>); })}
              </React.Fragment>); })}
            {!L.length && <tr><td colSpan={COLS.length} style={{ padding: 40, textAlign: 'center', color: TOKENS.textMuted }}>No hay placas con esos filtros.</td></tr>}
          </tbody>
        </table>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 12.5, color: TOKENS.textMuted }}>
        <span>Mostrando {L.length ? pg * porPag + 1 : 0}–{Math.min(L.length, (pg + 1) * porPag)} de {L.length}</span>
        <span style={{ flex: 1 }} />
        Por página <select value={porPag} onChange={(e) => { setPorPag(+e.target.value); setPag(0); }} style={{ ...pcInp, padding: '4px 6px', fontSize: 12.5 }}>{[50, 100].map((n) => <option key={n}>{n}</option>)}</select>
        <PcBtn style={{ padding: '5px 10px', fontSize: 12 }} disabled={pg === 0} onClick={() => { setPag(pg - 1); if (tablaRef.current) tablaRef.current.scrollTop = 0; }}>‹ Anterior</PcBtn>
        <span>Página {pg + 1} de {paginas}</span>
        <PcBtn style={{ padding: '5px 10px', fontSize: 12 }} disabled={pg >= paginas - 1} onClick={() => { setPag(pg + 1); if (tablaRef.current) tablaRef.current.scrollTop = 0; }}>Siguiente ›</PcBtn>
      </div>
      {r && !drawer && !editar && <PcDetalle r={r} toast={toast} onClose={() => setSelId(null)} onEntregar={() => setDrawer({ ent: r.id })} onEditar={() => setEditar(r)} onAnular={() => setAnular(r)} onReactivar={() => setReactivar(r)} />}
      {drawer === 'enc' && <PcAsignarEncargo onClose={() => setDrawer(null)} onGuardado={(e, r) => { setDrawer(null); toast(e ? `Tarea creada · ${e.que}` : `Suministro agregado · ${r.placa}`, 'g'); }} />}
      {drawer === 'rec' && <PcRegistrarRecogida onClose={() => setDrawer(null)} onGuardado={(t) => { setDrawer(null); set({ tab: 'todos', est: null, q: '', fecha: 'todas' }); setOrden(null); toast(`Recogida guardada · ${t.placa}`); }} />}
      {drawer && drawer.ent !== undefined && <PcRegistrarEntrega regs={regs} inicial={drawer.ent} onClose={() => setDrawer(null)} onCerrarTodo={() => { setDrawer(null); setSelId(null); }} onGuardado={(n) => { setDrawer(null); setSelId(null); toast(n === 1 ? 'Entrega registrada' : `${n} entregas registradas`, 'g'); }} />}
      {editar && <PcRegistrarRecogida editar={editar} onClose={() => setEditar(null)} onCerrarTodo={() => { setEditar(null); setSelId(null); }} onGuardado={(t) => { setEditar(null); setSelId(t.id); toast(`Cambios guardados · ${t.placa}`, 'y'); }} />}
      {anular && AnuModal && <AnuModal ticket={anular._t} onDismiss={() => setAnular(null)} onConfirm={({ motivo, nota }) => { const yo = window.usuarioActual ? window.usuarioActual() : {}; window.anularTicket(anular._t, { motivo, nota, por: yo.nombre }); setAnular(null); setSelId(null); pcAvisar(); toast('Registro anulado', 'm'); }} />}
      {reactivar && Modal && <Modal tone="primary" icon={I.check(24, TOKENS.primary)} title="Reactivar registro" confirmLabel="Reactivar"
      ticket={reactivar} message={`Vuelve a quedar por entregar. El plazo se cuenta desde hoy.`} onDismiss={() => setReactivar(null)} onConfirm={() => { const yo = window.usuarioActual ? window.usuarioActual() : {}; window.reactivarTicket(reactivar._t, { por: yo.nombre }); setReactivar(null); setSelId(null); pcAvisar(); toast('Registro reactivado'); }} />}
    </div>);
}

// ─── Informes: un solo informe, un solo Excel ────────────────────────────
const SUM_TIPO_TXT = { llanta: 'Llanta', rin: 'Rin', valvula: 'Válvula' };
// ── Informes v2 (24/11/2026): periodo con atajos, comparación, filtros y pestañas ──────────────
// Reglas del diseño de informes de Control Subastas: TODO EN RINES; recogidos por fecha de recogida y
// entregados por fecha de entrega; semanas de lunes a sábado con el domingo en la semana siguiente
// (S1 empieza el día 1); cumplimiento en días hábiles netos (sin pausas).
const INF_ELIGE = ['taller directo', 'allianz', 'renting', 'estado', 'seguros del estado', 'solidaria', 'previsora', 'taller'];
const infElige = (a) => INF_ELIGE.includes(String(a || '').toLowerCase().trim());
const INF_MES = ['ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic'];
const infD = (iso) => { const [y, m, d] = iso.split('-').map(Number); return new Date(y, m - 1, d); };
const infIso = (dt) => `${dt.getFullYear()}-${String(dt.getMonth() + 1).padStart(2, '0')}-${String(dt.getDate()).padStart(2, '0')}`;
const infMas = (iso, n) => { const d = infD(iso); d.setDate(d.getDate() + n); return infIso(d); };
const infFinMes = (y, m) => infIso(new Date(y, m + 1, 0)); // m 0-based
const infMeses = (iso, n) => { const [y, m, d] = iso.split('-').map(Number); const fin = infFinMes(y, m - 1 + n); const dd = Math.min(d, Number(fin.slice(8))); return fin.slice(0, 8) + String(dd).padStart(2, '0'); };
const infTxtF = (iso, conAno) => { const d = infD(iso); return `${d.getDate()} ${INF_MES[d.getMonth()]}${conAno ? ' ' + d.getFullYear() : ''}`; };
const infTxtR = (d, h) => d === h ? infTxtF(d, true) : `${infTxtF(d, d.slice(0, 4) !== h.slice(0, 4))} – ${infTxtF(h, true)}`;
function infPeriodo(pre, hoy, rd, rh) {
  const [y, m] = hoy.split('-').map(Number);
  if (pre === 'sem') { const d = infD(hoy); return [infMas(hoy, -d.getDay()), hoy]; } // domingo a hoy
  if (pre === 'mes') return [hoy.slice(0, 8) + '01', hoy];
  if (pre === 'ant') { const i = infMeses(hoy.slice(0, 8) + '01', -1); return [i, infFinMes(Number(i.slice(0, 4)), Number(i.slice(5, 7)) - 1)]; }
  if (pre === '30') return [infMas(hoy, -29), hoy];
  if (pre === 'ano') return [`${y}-01-01`, hoy];
  if (pre === 'pas') return [`${y - 1}-01-01`, `${y - 1}-12-31`];
  return rd <= rh ? [rd, rh] : [rh, rd];
}
function infComparar(cmp, d, h) {
  if (cmp === 'ano') return [infMeses(d, -12), infMeses(h, -12)];
  const [y1, m1, d1] = d.split('-').map(Number), [y2, m2] = h.split('-').map(Number);
  if (d1 === 1) { // meses: el mismo tramo del mes (o meses) anterior
    const n = (y2 - y1) * 12 + (m2 - m1) + 1; const esFin = h === infFinMes(y2, m2 - 1);
    if (d.slice(5) === '01-01' && n === 12 && esFin) return [infMeses(d, -12), infMeses(h, -12)];
    if (d.slice(5) === '01-01' && y1 === y2 && !esFin && n > 1) return [infMeses(d, -12), infMeses(h, -12)];
    const i = infMeses(d, -n); const f = esFin ? infFinMes(Number(i.slice(0, 4)), Number(i.slice(5, 7)) - 1 + n - 1) : infMeses(h, -n);
    return [i, f];
  }
  const dias = Math.round((infD(h) - infD(d)) / 864e5) + 1;
  return [infMas(d, -dias), infMas(d, -1)];
}
// Grupos de la tabla: semanas (S1… del mes) si el periodo cabe en un mes; si no, meses.
function infGrupos(d, h) {
  const out = [];
  if (d.slice(0, 7) === h.slice(0, 7)) {
    const [y, m] = d.split('-').map(Number); const fin = infFinMes(y, m - 1); let ini = d.slice(0, 8) + '01'; let n = 1; let cur = ini;
    while (cur <= fin) { const nx = infMas(cur, 1); if (nx > fin || infD(nx).getDay() === 0) { out.push({ k: 'S' + n, d: ini, h: cur }); n++; ini = nx; } cur = nx; }
    return out.filter((g) => g.h >= d && g.d <= h).map((g) => ({ ...g, lbl: `${g.d.slice(8)}/${g.d.slice(5, 7)}–${g.h.slice(8)}/${g.h.slice(5, 7)}` }));
  }
  let cur = d.slice(0, 8) + '01';
  while (cur <= h) { const [y, m] = cur.split('-').map(Number); out.push({ k: INF_MES[m - 1][0].toUpperCase() + INF_MES[m - 1].slice(1) + ' ' + y, d: cur, h: infFinMes(y, m - 1), lbl: '' }); cur = infMeses(cur, 1); }
  return out;
}
const infCnt = (r, t) => (r.items || []).filter((i) => i.tipo === t).reduce((a, i) => a + (Number(i.cantidad) || 0), 0);
const infRin = (r) => infCnt(r, 'rin');
const infSum = (L, f) => L.reduce((a, r) => a + f(r), 0);
// Cumplimiento de entregadas, en rines: [a tiempo (hasta el día límite), retrasado, vencido]
function infCumple(E) {
  const tot = infSum(E, infRin); if (!tot) return null;
  const p = (f) => Math.round(infSum(E.filter(f), infRin) / tot * 100);
  return [p((r) => r._plazo >= 2), p((r) => r._plazo === 1), p((r) => r._plazo === 0)];
}
// Cajas de días contra el límite: antes · el día límite · 1 · 2 · 3+ días tarde
function infCajas(E) {
  const c = [0, 0, 0, 0, 0];
  E.forEach((r) => { const S = pcSlaDe(r._ent && r._ent.express); const d = r._dias; c[d < S ? 0 : d === S ? 1 : d === S + 1 ? 2 : d === S + 2 ? 3 : 4] += infRin(r); });
  return c;
}
function infCalc(regs, d, h) {
  const en = (iso) => !!iso && iso >= d && iso <= h;
  const R = regs.filter((r) => r._estado !== 'anu' && en(r._iso));
  const E = regs.filter((r) => r._estado === 'ent' && en(r._isoEnt));
  const NV = (typeof novedadesLista === 'function' ? novedadesLista(regs) : []).filter((x) => en(String(x.iso || '').slice(0, 10)));
  const porAseg = {}; R.forEach((r) => { const k = r.aseguradora || '—'; porAseg[k] = (porAseg[k] || 0) + infRin(r); });
  return {
    R, E, NV, porAseg,
    rRec: infSum(R, infRin), rEnt: infSum(E, infRin), placas: R.length,
    elige: infSum(R.filter((r) => infElige(r.aseguradora)), infRin),
    cum: infCumple(E),
    prom: E.length ? infSum(E, (r) => r._dias) / E.length : null,
    fact: infSum(R, (r) => typeof servResumen === 'function' ? servResumen(r).total : 0)
  };
}

// ── Informes v3 (24/11/2026): selector de periodo (Mes · Semana · Año · Rango) con flechas, comparación como frase ──
const INF_MESL = ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre'];
const infCap = (s) => s ? s[0].toUpperCase() + s.slice(1) : s;
const infIniMes = (y, m) => `${y}-${String(m + 1).padStart(2, '0')}-01`;
const infSemDe = (y, m) => infGrupos(infIniMes(y, m), infFinMes(y, m)); // S1… del mes completo
function infPer(p, hoy) {
  const min = (a, b) => a < b ? a : b;
  if (p.modo === 'mes') {
    const d = infIniMes(p.y, p.m), fin = infFinMes(p.y, p.m), h = min(fin, hoy), curso = fin > hoy;
    return { d, h, curso, t: `${infCap(INF_MESL[p.m])} ${p.y}`, s: curso ? `1–${Number(h.slice(8))} ${INF_MES[p.m]} · mes en curso` : `1–${Number(fin.slice(8))} ${INF_MES[p.m]} · mes completo`, col: `${infCap(INF_MESL[p.m])} ${p.y}`, slug: d.slice(0, 7) };
  }
  if (p.modo === 'sem') {
    const ws = infSemDe(p.y, p.m); const w = ws[Math.min(p.w, ws.length - 1)]; const h = min(w.h, hoy), curso = w.h > hoy;
    return { d: w.d, h, curso, t: `Semana ${Math.min(p.w, ws.length - 1) + 1} de ${INF_MESL[p.m]}`, s: `${Number(w.d.slice(8))}–${Number(w.h.slice(8))} ${INF_MES[p.m]} ${p.y}${curso ? ' · en curso' : ''}`, col: `S${Math.min(p.w, ws.length - 1) + 1} ${INF_MES[p.m]}`, slug: `${w.d}_a_${h}` };
  }
  if (p.modo === 'ano') {
    const fin = `${p.y}-12-31`, h = min(fin, hoy), curso = fin > hoy;
    return { d: `${p.y}-01-01`, h, curso, t: `Año ${p.y}`, s: curso ? `1 ene – ${infTxtF(h)} · año en curso` : 'año completo', col: String(p.y), slug: String(p.y) };
  }
  const d = p.rd <= p.rh ? p.rd : p.rh, h = p.rd <= p.rh ? p.rh : p.rd;
  return { d, h, curso: false, t: 'Rango', s: infTxtR(d, h), col: 'Rango', slug: `${d}_a_${h}` };
}
// Comparación: [desde, hasta, frase, detalle, encabezado de columna]
function infCmpDe(p, P, cmp) {
  if (cmp === 'no') return null;
  const dias = Math.round((infD(P.h) - infD(P.d)) / 864e5) + 1;
  if (cmp === 'ano') {
    const d = infMeses(P.d, -12), h = infMeses(P.h, -12);
    const t = p.modo === 'mes' ? `vs ${INF_MESL[p.m]} ${p.y - 1}` : p.modo === 'ano' ? `vs año ${p.y - 1}` : p.modo === 'sem' ? `vs la misma semana de ${Number(P.d.slice(0, 4)) - 1}` : `vs el mismo rango de ${Number(P.d.slice(0, 4)) - 1}`;
    const col = p.modo === 'mes' ? `${infCap(INF_MESL[p.m])} ${p.y - 1}` : p.modo === 'ano' ? String(p.y - 1) : infTxtR(d, h);
    return { d, h, t, s: P.curso ? `mismos días (${infTxtR(d, h)})` : infTxtR(d, h), col };
  }
  if (p.modo === 'mes') {
    const y = p.m ? p.y : p.y - 1, m = p.m ? p.m - 1 : 11; const d = infIniMes(y, m); const h = P.curso ? infMeses(P.h, -1) : infFinMes(y, m);
    return { d, h, t: `vs ${INF_MESL[m]} ${y}`, s: P.curso ? `mismos días (1–${Number(h.slice(8))})` : 'mes completo', col: `${infCap(INF_MESL[m])} ${y}` };
  }
  if (p.modo === 'ano') { const d = `${p.y - 1}-01-01`, h = infMeses(P.h, -12); return { d, h, t: `vs año ${p.y - 1}`, s: P.curso ? `mismos días (hasta el ${infTxtF(h)})` : 'año completo', col: String(p.y - 1) }; }
  const d = infMas(P.d, -dias), h = infMas(P.d, -1);
  return { d, h, t: p.modo === 'sem' ? 'vs la semana anterior' : 'vs los días anteriores', s: infTxtR(d, h), col: infTxtR(d, h) };
}
function infPaso(p, dir) {
  if (p.modo === 'mes') { const m = p.m + dir; return { ...p, y: p.y + (m < 0 ? -1 : m > 11 ? 1 : 0), m: (m + 12) % 12 }; }
  if (p.modo === 'ano') return { ...p, y: p.y + dir };
  if (p.modo === 'sem') {
    const n = infSemDe(p.y, p.m).length; const w = p.w + dir;
    if (w >= 0 && w < n) return { ...p, w };
    const m = p.m + dir; const y = p.y + (m < 0 ? -1 : m > 11 ? 1 : 0), mm = (m + 12) % 12;
    return { ...p, y, m: mm, w: dir < 0 ? infSemDe(y, mm).length - 1 : 0 };
  }
  return p;
}
function infSemanaHoy(hoy) { const y = Number(hoy.slice(0, 4)), m = Number(hoy.slice(5, 7)) - 1; const w = infSemDe(y, m).findIndex((g) => hoy >= g.d && hoy <= g.h); return { modo: 'sem', y, m, w: Math.max(0, w) }; }
// Rines con novedad (distintos), express, garantías y cumplimiento en cantidad
function infExtra(regs, A, d, h) {
  const key = (x) => x.r.id + '#' + x.i;
  const nvR = new Set(A.NV.map(key)).size;
  const nvP = new Set(A.NV.filter((x) => x.tipo === 'pausa').map(key)).size;
  const nvNR = new Set(A.NV.filter((x) => x.tipo === 'sr' && x.nov === 'nr').map(key)).size;
  const nvNA = new Set(A.NV.filter((x) => x.nov === 'na').map(key)).size;
  const exR = infSum(A.R.filter((r) => r.express), infRin);
  const pr = (L) => L.length ? infSum(L, (r) => r._dias) / L.length : null;
  let garR = 0; regs.forEach((r) => (typeof garantiasDe === 'function' ? garantiasDe(r.id) : []).forEach((g) => { if (g.iso && g.iso.slice(0, 10) >= d && g.iso.slice(0, 10) <= h) garR += (g.rines || []).length || 1; }));
  const S = pcSlaDe(false);
  const cumN = [infSum(A.E.filter((r) => r._plazo >= 2), infRin), infSum(A.E.filter((r) => r._plazo === 1), infRin), infSum(A.E.filter((r) => r._plazo === 0), infRin)];
  return { nvR, nvP, nvNR, nvNA, exR, exProm: pr(A.E.filter((r) => r.express)), noProm: pr(A.E.filter((r) => !r.express)), garR, cumN, S };
}

function PcInformes({ regs: regsAll, toast }) {
  const cel = usePcCel();
  const hoy = pcHoyIso();
  const yHoy = Number(hoy.slice(0, 4)), mHoy = Number(hoy.slice(5, 7)) - 1;
  const [per, setPer] = React.useState({ modo: 'mes', y: yHoy, m: mHoy, w: 0, rd: hoy.slice(0, 8) + '01', rh: hoy });
  const [pop, setPop] = React.useState(null); // 'per' | 'cmp'
  const [pv, setPv] = React.useState({ modo: 'mes', y: yHoy, m: mHoy }); // lo que muestra el menú del periodo
  const [rTmp, setRTmp] = React.useState({ d: hoy.slice(0, 8) + '01', h: hoy });
  const [cmp, setCmp] = React.useState('ant');
  const [fa, setFa] = React.useState('');
  const [ft, setFt] = React.useState('');
  const [tab, setTab] = React.useState('res');
  // Una placa con garantía abierta cuenta su primera entrega como entregada (16/11/2026).
  const base = regsAll.map((r) => r._gar ? { ...r, _estado: 'ent', _dias: r._diasPrimera, _plazo: r._plazoPrimera } : r);
  const asegOpc = [...new Set(base.map((r) => r.aseguradora).filter(Boolean))].sort();
  const tallerOpc = [...new Set(base.map((r) => r.taller).filter(Boolean))].sort();
  const regs = base.filter((r) => (!fa || r.aseguradora === fa) && (!ft || r.taller === ft));
  const P = infPer(per, hoy);
  const desde = P.d, hasta = P.h;
  const C = infCmpDe(per, P, cmp);
  const [cd, ch] = C ? [C.d, C.h] : [desde, hasta];
  const primero = base.reduce((m, r) => r._iso && (!m || r._iso < m) ? r._iso : m, '');
  const A = infCalc(regs, desde, hasta);
  const B = C && primero && ch >= primero ? infCalc(regs, cd, ch) : null;
  const AX = infExtra(regs, A, desde, hasta), BX = B ? infExtra(regs, B, cd, ch) : null;
  const por = 'rec'; // el Excel sigue contando por fecha de recogida
  const L = regs.filter((r) => r._estado !== 'anu' && (por === 'rec' ? (r._iso >= desde && r._iso <= hasta) : (r._estado === 'ent' && r._isoEnt >= desde && r._isoEnt <= hasta)));
  const ent = L.filter((r) => r._estado === 'ent'), pen = L.filter((r) => r._estado === 'pend');
  const cnt = (r, t) => (r.items || []).filter((i) => i.tipo === t).reduce((a, i) => a + (Number(i.cantidad) || 0), 0);
  const prom = ent.length ? (ent.reduce((a, r) => a + r._dias, 0) / ent.length) : null;
  const S = window.loadSlaConfig ? window.loadSlaConfig().slaHabiles : 3;
  const aTiempo = ent.filter((r) => r._dias < S).length;
  const by = (f) => { const m = {}; L.forEach((r) => { const k = f(r); const o = m[k] = m[k] || { n: 0, r: 0, l: 0, v: 0, e: 0, p: 0, d: 0 }; o.n++; o.r += cnt(r, 'rin'); o.l += cnt(r, 'llanta'); o.v += cnt(r, 'valvula'); if (r._estado === 'ent') { o.e++; o.d += r._dias; } else o.p++; }); return Object.entries(m).sort((a, b) => b[1].n - a[1].n); };
  const porTaller = by((r) => r.taller + (r.sede ? ' · ' + r.sede : '')), porAseg = by((r) => r.aseguradora);
  // Express (16/11/2026): cuántos, qué taller pide más y días promedio express vs. normal.
  const exL = L.filter((r) => r.express), exE = ent.filter((r) => r.express), noE = ent.filter((r) => !r.express);
  const promDe = (arr) => arr.length ? arr.reduce((a, r) => a + r._dias, 0) / arr.length : null;
  const exTaller = (() => { const m = {}; exL.forEach((r) => { const k2 = r.taller + (r.sede ? ' · ' + r.sede : ''); m[k2] = (m[k2] || 0) + 1; }); return Object.entries(m).sort((a, b) => b[1] - a[1]); })();
  const valorTotal = L.reduce((a, r) => a + (typeof servResumen === 'function' ? servResumen(r).total : 0), 0);
  // Garantías registradas en el periodo (por la fecha en que el taller devolvió).
  const GL = []; regs.forEach((r) => (typeof garantiasDe === 'function' ? garantiasDe(r.id) : []).forEach((g) => { if (g.iso >= desde && g.iso <= hasta) GL.push({ r, g }); }));
  const cuenta = (f) => { const m = {}; GL.forEach((x) => { const k2 = f(x); m[k2] = (m[k2] || 0) + 1; }); return Object.entries(m).sort((a, b) => b[1] - a[1]); };
  const garTaller = cuenta((x) => x.r.taller + (x.r.sede ? ' · ' + x.r.sede : '')), garMotivo = cuenta((x) => x.g.motivo);
  const garEnt = GL.filter((x) => x.g.estado === 'entregada'); const garProm = garEnt.length ? garEnt.reduce((a, x) => a + (window.businessDaysElapsed ? window.businessDaysElapsed(window.effectiveStart(x.g.fecha, x.g.hora), pcFechaDate(x.g.entrega.fecha, x.g.entrega.hora)) : 0), 0) / garEnt.length : null;
  // ── 23/11/2026: Informes con todo: novedades, servicios, tareas y suministros, rutas ──
  const enRango = (iso) => iso && iso.slice(0, 10) >= desde && iso.slice(0, 10) <= hasta;
  const isoDeF = (f) => { const m = String(f || '').match(/(\d{1,2})\s*\/\s*(\d{1,2})\s*\/\s*(\d{4})/); return m ? `${m[3]}-${m[2].padStart(2, '0')}-${m[1].padStart(2, '0')}` : ''; };
  const NV = (typeof novedadesLista === 'function' ? novedadesLista(regs) : []).filter((x) => enRango(x.iso));
  const NVp = NV.filter((x) => x.tipo === 'pausa'), NVnr = NV.filter((x) => x.tipo === 'sr' && x.nov === 'nr'), NVna = NV.filter((x) => x.nov === 'na');
  const promPausa = NVp.length ? NVp.reduce((a, x) => a + servDiasEsperando(x.p), 0) / NVp.length : null;
  const noCobrado = NV.filter((x) => x.tipo === 'sr' || x.p.estado === 'no').reduce((a, x) => { const rin = servDe(x.r).rines[x.i] || {}; return a + (Number(rin.precio) || 0); }, 0);
  const asegPausas = (() => { const m = {}; NVp.forEach((x) => { const k2 = x.r.aseguradora || '—'; m[k2] = (m[k2] || 0) + 1; }); return Object.entries(m).sort((a, b) => b[1] - a[1]); })();
  const SVr = L.filter((r) => r._estado !== 'anu').map((r) => ({ r, s: servDe(r) }));
  const codN = {}; let nSold = 0; SVr.forEach(({ s }) => s.rines.forEach((x) => { const c = servCodigo(x); if (c) { codN[c] = (codN[c] || 0) + 1; } if (x.sol) nSold++; }));
  const nSinSv = SVr.filter(({ s }) => s.rines.length && !s.rines.some((x) => x.tipo)).length;
  const ENC = (window.loadEncargos ? window.loadEncargos() : []).filter((e) => enRango(e.fechaIso || (e.creadoAt ? new Date(e.creadoAt).toISOString() : '')));
  const SOLS = (window.loadParadas ? window.loadParadas() : []).filter((p) => p.tipo === 'recoger' && p.creadaPor === 'admin' && enRango(isoDeF(p.fecha)));
  const tHechas = ENC.filter((e) => e.estado === 'hecho').length + SOLS.filter((p) => p.estado === 'completada').length;
  const tPend = ENC.length + SOLS.length - tHechas;
  const SUM = []; L.forEach((r) => (window.suministrosDeReg ? window.suministrosDeReg(r) : []).forEach((x) => SUM.push({ r, x })));
  const sumTipo = (t) => SUM.filter((y) => y.x.tipo === t).reduce((a, y) => a + (Number(y.x.cantidad) || 1), 0);
  const PAR = (window.loadParadas ? window.loadParadas() : []).filter((p) => p.estado === 'completada' && enRango(isoDeF(p.fecha)));
  const diasRuta = new Set(PAR.map((p) => p.fecha)).size;
  const TIEMPOS = (() => { try { return JSON.parse(localStorage.getItem('rodando.tiempos') || '[]').filter((t) => enRango(isoDeF(t.fecha) || (t.ts ? new Date(t.ts).toISOString() : ''))); } catch (x) { return []; } })();
  const minSitio = TIEMPOS.length ? Math.round(TIEMPOS.reduce((a, t) => a + t.ms, 0) / TIEMPOS.length / 60000) : null;
  const visitas = (() => { const m = {}; PAR.forEach((p) => { m[p.taller] = (m[p.taller] || 0) + 1; }); return Object.entries(m).sort((a, b) => b[1] - a[1]); })();
  const bloqueNum = (n, t) => <div><b style={{ fontSize: 24 }}>{n}</b><div style={{ fontSize: 12, color: TOKENS.textMuted }}>{t}</div></div>;
  const th = { ...pcLbl, textAlign: 'right', padding: '8px 8px', background: TOKENS.surfaceLow, borderBottom: `1px solid ${TOKENS.border}` };
  const tabla = (titulo, rows) =>
  <div style={{ ...pcCard, padding: 14 }}>
      <div style={pcLbl}>{titulo}</div>
      <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, marginTop: 8 }}>
        <thead><tr><th style={{ ...th, textAlign: 'left' }}></th><th style={th}>Placas</th><th style={th}>Rines</th><th style={th}>Llantas</th><th style={th}>Entregadas</th><th style={th}>Pendientes</th><th style={th}>Prom. días</th></tr></thead>
        <tbody>{rows.slice(0, 10).map(([k, o]) => <tr key={k}>{[k, o.n, o.r, o.l, o.e, o.p, o.e ? (o.d / o.e).toFixed(1) : '—'].map((v, i) => <td key={i} style={{ padding: '8px 8px', borderBottom: `1px solid ${TOKENS.border}`, textAlign: i ? 'right' : 'left' }}>{v}</td>)}</tr>)}
          {!rows.length && <tr><td colSpan={7} style={{ padding: 16, textAlign: 'center', color: TOKENS.textMuted }}>Sin datos en el periodo.</td></tr>}</tbody>
      </table>
    </div>;
  const COLS = ['Orden', 'Placa', 'Aseguradora', 'Taller', 'Sede', 'Fecha recogida', 'Recogió / cómo llegó', 'Digitó', 'Tipo', 'Cantidad', 'Tamaño', 'Material', 'Huecos', 'Tapa', 'Tapa válvula', 'Marca', 'Referencia', 'DOT', 'Calidad', 'Sensor', 'Observación', 'Estado', 'Fecha entrega', 'Entregó', 'Factura / remisión', 'Días hábiles', 'Plazo', 'Express', 'Siniestro', 'Servicio', 'Valor sin IVA'];
  const descargar = () => {
    const TIPO = { rin: 'Rin', llanta: 'Llanta', valvula: 'Válvula' };
    const det = [{ bold: true, cells: COLS }];
    L.forEach((r) => {
      const e = r._ent; const dias = r._estado === 'ent' ? r._dias : (r._est ? r._est.dias : '');
      const plazo = r._estado === 'ent' ? PC_EST[r._plazo][0] : (r._est ? PC_EST[r._est.orden][0] : '');
      const base = [Number(r.codigo) || r.codigo, r.placa, r.aseguradora, r.taller, r.sede || '', pcFechaCorta(r.fecha), pcComoLlego(r) + (r.guiaLlegada ? ' · guía ' + r.guiaLlegada : ''), r.digitadoPorNombre || ''];
      const fin = [r._estado === 'ent' ? 'Entregada' : 'Por entregar', e ? pcFechaCorta(e.fechaEntrega) : '', e ? e.entregadoPorNombre || '' : '', e ? (e.despachado ? `Guía ${e.guia} (${e.transportadora})` : `${e.comprobanteTipo || 'Factura'} ${e.factura || ''}`.trim()) : '', dias, plazo];
      const its = (r.items || []).length ? r.items : [{}];
      const sv = typeof servDe === 'function' ? servDe(r) : { rines: [], siniestro: '' }; let k = 0;
      const svDe = (it) => { if (it.tipo !== 'rin') return ['', '']; const n = Math.max(1, Number(it.cantidad) || 1); const rs = sv.rines.slice(k, k + n); k += n; const m = {}; rs.forEach((x) => { const c = servCodigo(x); if (c) m[c] = (m[c] || 0) + 1; }); return [Object.entries(m).map(([c, q]) => q > 1 ? `${c} ×${q}` : c).join(' · '), rs.reduce((a, x) => a + servValor(x), 0) || '']; };
      its.forEach((it) => det.push({ cells: [...base, TIPO[it.tipo] || '', Number(it.cantidad) || '', it.tamano || '', it.material || '', it.huecos || '', it.tapa || '', it.tapaValvula || '', it.marca || '', it.referencia || '', it.dot || '', it.calidad || '', it.valvulaSensor || '', it.observaciones || '', ...fin, r.express ? 'Sí' : 'No', sv.siniestro || '', ...svDe(it)] }));
    });
    const res = [{ bold: true, cells: [`Rodando · Informe de mensajería · ${pcFechaCorta(pcDeIso(desde))} a ${pcFechaCorta(pcDeIso(hasta))} · por fecha de ${por === 'rec' ? 'recogida' : 'entrega'}`] }, null,
    { cells: ['Placas', L.length] }, { cells: ['Rines', L.reduce((a, r) => a + cnt(r, 'rin'), 0)] }, { cells: ['Llantas', L.reduce((a, r) => a + cnt(r, 'llanta'), 0)] }, { cells: ['Válvulas', L.reduce((a, r) => a + cnt(r, 'valvula'), 0)] },
    { cells: ['Entregadas', ent.length] }, { cells: ['Pendientes', pen.length] }, { cells: ['Tiempo promedio (días hábiles)', prom == null ? '' : Number(prom.toFixed(1))] }, null];
    const bloque = (titulo, rows) => { res.push({ bold: true, cells: [titulo, 'Placas', 'Rines', 'Llantas', 'Válvulas', 'Entregadas', 'Pendientes', 'Prom. días'] }); rows.forEach(([k, o]) => res.push({ cells: [k, o.n, o.r, o.l, o.v, o.e, o.p, o.e ? Number((o.d / o.e).toFixed(1)) : ''] })); res.push(null); };
    bloque('Por taller', porTaller); bloque('Por aseguradora', porAseg);
    res.push({ bold: true, cells: ['Por plazo', 'Entregadas', 'Pendientes'] });
    PC_EST.forEach((e, k) => res.push({ cells: [e[0], ent.filter((r) => r._plazo === k).length, pen.filter((r) => r._est && r._est.orden === k).length] }));
    res.push(null, { bold: true, cells: ['Express', 'Placas', 'Entregadas', 'Prom. días'] });
    res.push({ cells: ['Express', exL.length, exE.length, promDe(exE) == null ? '' : Number(promDe(exE).toFixed(1))] });
    res.push({ cells: ['Normal', L.length - exL.length, noE.length, promDe(noE) == null ? '' : Number(promDe(noE).toFixed(1))] });
    if (exTaller.length) { res.push({ bold: true, cells: ['Talleres que más piden express', 'Placas'] }); exTaller.forEach(([k2, n]) => res.push({ cells: [k2, n] })); }
    res.push(null, { cells: ['Valor de servicios sin IVA', valorTotal] });
    res.push(null, { bold: true, cells: ['Garantías', 'Rines devueltos'] }, { cells: ['Garantías registradas', GL.length] }, { cells: ['% sobre entregadas', ent.length ? Number((GL.length / ent.length * 100).toFixed(1)) : ''] }, { cells: ['Días promedio de la segunda entrega', garProm == null ? '' : Number(garProm.toFixed(1))] });
    if (garTaller.length) { res.push({ bold: true, cells: ['Garantías por taller', 'Cantidad'] }); garTaller.forEach(([k2, n]) => res.push({ cells: [k2, n] })); }
    if (garMotivo.length) { res.push({ bold: true, cells: ['Garantías por motivo', 'Cantidad'] }); garMotivo.forEach(([k2, n]) => res.push({ cells: [k2, n] })); }
    const H = (c) => ({ bold: true, cells: c });
    const shNov = [H(['Fecha', 'Placa', 'Orden', 'Rin', 'Novedad', 'Motivo', 'Resultado', 'Días hábiles', 'Taller', 'Aseguradora'])];
    NV.forEach((x) => shNov.push({ cells: [x.tipo === 'pausa' ? x.p.desde : x.fecha, x.r.placa, Number(x.r.codigo) || x.r.codigo, x.i + 1, x.tipo === 'pausa' ? 'Pausa' : x.nov === 'na' ? 'No autorizado' : 'No reparable', x.motivo || '', x.tipo === 'pausa' ? pausaEst(x.p)[0] : 'No se cobra', x.tipo === 'pausa' ? servDiasEsperando(x.p) : '', x.r.taller + (x.r.sede ? ' · ' + x.r.sede : ''), x.r.aseguradora || ''] }));
    const shSv = [H(['Placa', 'Orden', 'Rin', 'Servicio', 'Soldadura', 'Valor sin IVA', 'Estado de cobro', 'Siniestro', 'Taller', 'Aseguradora'])];
    SVr.forEach(({ r, s }) => s.rines.forEach((x, i) => shSv.push({ cells: [r.placa, Number(r.codigo) || r.codigo, i + 1, servCodigo(x) || '', x.sol ? 'Sí' : '', servValor(x), x.sinReparar ? 'No se cobra (no reparable)' : x.aut && x.aut.estado === 'no' ? 'No se cobra (no autorizado)' : x.aut && x.aut.estado === 'espera' ? 'En pausa' : x.tipo ? 'Se cobra' : 'Sin servicio', s.siniestro || '', r.taller, r.aseguradora || ''] })));
    const shSum = [H(['Placa', 'Orden', 'Qué', 'Cantidad', 'Detalle', 'Agregó', 'Fecha', 'Entregado'])];
    SUM.forEach(({ r, x }) => shSum.push({ cells: [r.placa, Number(r.codigo) || r.codigo, (SUM_TIPO_TXT[x.tipo] || x.tipo), Number(x.cantidad) || 1, x.detalle || '', x.por || '', x.fecha || '', r._estado === 'ent' ? 'Sí' : 'No'] }));
    const shTar = [H(['Tipo', 'Qué', 'Dónde', 'Placa', 'Mensajero', 'Para', 'Prioridad', 'Estado', 'Hecha'])];
    const nomU = (u) => (window.nombreDeUsuario && window.nombreDeUsuario(u)) || u || '';
    SOLS.forEach((p) => shTar.push({ cells: ['Recoger placas', p.referencia || '', p.taller + (p.sede ? ' · ' + p.sede : ''), (p.placas || []).join(', '), nomU(p.asignadoA), p.fecha, p.prioridad === 'alta' ? 'Sí' : '', p.estado === 'completada' ? 'Hecha' : p.estado === 'solicitud' ? 'Por planear' : 'En la ruta', ''] }));
    ENC.forEach((e) => shTar.push({ cells: [(window.ENC_TIPO[e.tipo] || ['', e.tipo])[1], e.que, window.encDonde(e), e.placa || '', nomU(e.para), e.fechaIso ? pcFechaCorta(pcDeIso(e.fechaIso)) : '', e.urgente ? 'Sí' : '', e.estado === 'hecho' ? 'Hecha' : 'Pendiente', e.hecho ? [e.hecho.fecha, e.hecho.porNombre, e.hecho.comprobante].filter(Boolean).join(' · ') : ''] }));
    const shRut = [H(['Día', 'Parada', 'Tipo', 'Mensajero', 'Llegó', 'Salió', 'Minutos en sitio'])];
    PAR.forEach((p) => shRut.push({ cells: [p.fecha, p.taller + (p.sede ? ' · ' + p.sede : ''), p.tipo === 'recoger' ? 'Recoger' : p.tipo === 'entregar' ? 'Entregar' : 'Tarea', nomU(p.asignadoA), p.iniciadaEn ? pcHora(p.iniciadaEn) : '', p.completadaEn ? pcHora(p.completadaEn) : '', p.iniciadaEn && p.completadaEn ? Math.round((p.completadaEn - p.iniciadaEn) / 60000) : ''] }));
    const shGar = [H(['Fecha', 'Placa', 'Orden', 'Rines', 'Motivo', 'Taller', 'Estado', 'Entregada'])];
    GL.forEach(({ r, g }) => shGar.push({ cells: [g.fecha, r.placa, Number(r.codigo) || r.codigo, (g.rines || []).map((i) => i + 1).join(', '), g.motivo || '', r.taller + (r.sede ? ' · ' + r.sede : ''), g.estado === 'entregada' ? 'Entregada' : 'Abierta', g.entrega ? g.entrega.fecha || '' : ''] }));
    res.push(null, { bold: true, cells: ['Novedades', 'Cantidad'] }, { cells: ['Pausas', NVp.length] }, { cells: ['Días hábiles promedio en pausa', promPausa == null ? '' : Number(promPausa.toFixed(1))] }, { cells: ['Rines no reparables', NVnr.length] }, { cells: ['Rines no autorizados', NVna.length] }, { cells: ['Valor que no se cobró', noCobrado] });
    res.push(null, { bold: true, cells: ['Tareas', 'Cantidad'] }, { cells: ['Hechas', tHechas] }, { cells: ['Pendientes', tPend] }, { cells: ['Recogidas de placas', SOLS.length] }, { cells: ['Encargos', ENC.length] });
    res.push(null, { bold: true, cells: ['Rutas', 'Cantidad'] }, { cells: ['Paradas', PAR.length] }, { cells: ['Días con ruta', diasRuta] }, { cells: ['Minutos promedio en sitio', minSitio == null ? '' : minSitio] });
    const extra = [{ nombre: 'Novedades', rows: shNov, anchos: [12, 10, 9, 6, 15, 26, 16, 12, 28, 16] }, { nombre: 'Servicios', rows: shSv, anchos: [10, 9, 6, 10, 10, 14, 26, 14, 28, 16] }, { nombre: 'Suministros', rows: shSum, anchos: [10, 9, 10, 9, 28, 16, 12, 10] }, { nombre: 'Tareas', rows: shTar, anchos: [16, 30, 32, 14, 14, 12, 10, 12, 30] }, { nombre: 'Rutas', rows: shRut, anchos: [12, 32, 10, 14, 10, 10, 14] }, { nombre: 'Garantías', rows: shGar, anchos: [12, 10, 9, 10, 26, 28, 12, 12] }];
    // Resumen v3 (24/11/2026): lo mismo que la pantalla, en rines, con la comparación.
    const H2x = (c) => ({ bold: true, cells: c });
    const rs = [H2x([`Rodando · Informe de mensajería · ${P.t} (${infTxtR(desde, hasta)})`]),
      { cells: [C ? `Comparado con: ${C.col} (${infTxtR(cd, ch)})${B ? '' : ' · sin datos en la app'}` : 'Sin comparar'] },
      { cells: [`Aseguradora: ${fa || 'Todas'} · Taller: ${ft || 'Todos'}`] }, null,
      H2x(['Indicador', P.col, '%', ...(C ? [C.col, 'Variación'] : [])])];
    IND.forEach((f) => { const t = indTxt(f); rs.push({ bold: f.n === 'h', cells: C ? t : t.slice(0, 3) }); });
    rs.push(null, H2x([`Rines recogidos por ${enUnMes ? 'semana' : 'mes'}`, cortoA, ...(BG ? [C.col] : [])]));
    Array.from({ length: Math.max(GA.length, GB.length) }).forEach((_, i) => rs.push({ cells: [enUnMes ? `S${i + 1}${GA[i] ? ' (' + rotulo(GA[i]) + ')' : ''}` : (GA[i] || GB[i]).k, serieA[i] == null ? '' : serieA[i], ...(BG ? [serieB[i] == null ? '' : serieB[i]] : [])] }));
    const shT = [H2x(['Taller', 'Sede', 'Rines recogidos', 'Rines entregados', '% a tiempo', 'Días R→E prom.', 'Más largo'])];
    talleresTop.forEach((o) => shT.push({ cells: [o.t, o.s, o.rr, o.re, o.c ? o.c[0] : '', o.prom == null ? '' : Number(o.prom.toFixed(1)), o.max == null ? '' : o.max] }));
    const shA = [H2x(['Aseguradora', 'Rines recogidos', '% del total', 'Rines entregados', '% a tiempo', 'Días R→E prom.', 'Novedades', ...(B ? [`Rines ${C.col}`] : [])])];
    asegTabla.forEach((o) => shA.push({ cells: [o.k, o.rr, A.rRec ? Math.round(o.rr / A.rRec * 100) : '', o.re, o.c ? o.c[0] : '', o.prom == null ? '' : Number(o.prom.toFixed(1)), o.nv || '', ...(B ? [o.ant] : [])] }));
    const shM = [H2x(['Taller', 'Sede', 'Visitas', 'Minutos promedio en sitio', 'Visita más larga (min)', 'Tiempo total (min)'])];
    tiemposTaller.forEach((o) => shM.push({ cells: [o.t, o.s, o.n, o.prom, o.maxM, o.totM] }));
    const blob = pcLibro([{ nombre: 'Resumen', rows: rs, anchos: [46, 16, 14, 16, 14] }, { nombre: 'Talleres', rows: shT, anchos: [30, 12, 14, 14, 11, 14, 10] }, { nombre: 'Aseguradoras', rows: shA, anchos: [26, 14, 11, 14, 11, 14, 11, 14] }, { nombre: 'Tiempos mensajero', rows: shM, anchos: [30, 12, 9, 22, 20, 18] },
      { nombre: 'Detalle', rows: det, anchos: [12, 10, 14, 24, 12, 14, 24, 14, 9, 9, 9, 12, 9, 7, 11, 14, 14, 10, 10, 8, 26, 13, 14, 14, 22, 12, 12, 9, 18, 14, 14] }, ...extra]);
    pcDescargar(blob, `Rodando_Informe_${P.slug}.xlsx`).then((ok) => ok && toast('Excel descargado'));
  };
  // ── Vista (24/11/2026): barra de periodo + pestañas ──────────────────────────────────────────
  const fN = (n) => (Number(n) || 0).toLocaleString('es-CO');
  const pct = (a, b) => b ? Math.round(a / b * 100) : 0;
  const chipD = (bg, fg, txt) => <span style={{ display: 'inline-block', whiteSpace: 'nowrap', marginTop: 8, fontSize: 12, fontWeight: 700, borderRadius: 6, padding: '2px 7px', background: bg, color: fg }}>{txt}</span>;
  const Delta = ({ a, b, menos, u }) => {
    if (cmp === 'no' || a == null) return null;
    if (!B || b == null) return chipD(TOKENS.surfaceLow, TOKENS.textMuted, '— sin comparación');
    const d = a - b; const ant = u === 'pp' ? b + '%' : u === 'd' ? b.toFixed(1) : u === '$' ? pcPesos(b) : fN(b);
    const fl = d > 0 ? '▲ ' : d < 0 ? '▼ ' : '';
    const txt = Math.abs(d) < 1e-9 ? '= igual' : u === 'pp' ? `${fl}${Math.abs(d)} pts` : u === 'd' ? `${fl}${Math.abs(d).toFixed(1)} días` : `${fl}${b ? Math.abs(Math.round(d / b * 100)) + '%' : fN(Math.abs(d))}`;
    const bueno = menos ? d < 0 : d > 0; const [bg, fg] = Math.abs(d) < 1e-9 ? [TOKENS.surfaceLow, TOKENS.textMuted] : bueno ? [TOKENS.successBg, TOKENS.successText] : [TOKENS.dangerBg, TOKENS.dangerText];
    return <span>{chipD(bg, fg, txt)}<span style={{ fontSize: 11.5, color: TOKENS.textSubtle, marginLeft: 6 }}>antes {ant}</span></span>;
  };
  const Kpi = ({ t, v, sub, color, children }) => <div style={{ ...pcCard, padding: '14px 16px' }}><div style={pcLbl}>{t}</div><b style={{ display: 'block', fontSize: 26, marginTop: 6, color: color || TOKENS.text, fontVariantNumeric: 'tabular-nums' }}>{v}</b>{sub && <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>{sub}</div>}{children}</div>;
  const thI = { ...pcLbl, textAlign: 'right', padding: '8px 9px', background: TOKENS.surfaceLow, borderBottom: `1px solid ${TOKENS.border}`, whiteSpace: 'nowrap' };
  const Tabla = ({ head, rows, tots = [], izq = 1 }) =>
  <div style={{ overflowX: cel ? 'auto' : 'visible' }}><table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, fontVariantNumeric: 'tabular-nums' }}>
      <thead><tr>{head.map((h, i) => <th key={i} style={{ ...thI, textAlign: i >= izq ? 'right' : 'left' }}>{h}</th>)}</tr></thead>
      <tbody>
        {rows.map((r, j) => <tr key={j}>{r.map((c, i) => <td key={i} style={{ padding: '8px 9px', borderBottom: `1px solid ${TOKENS.border}`, textAlign: i >= izq ? 'right' : 'left' }}>{c === '' || c == null ? <span style={{ color: TOKENS.textSubtle }}>—</span> : c}</td>)}</tr>)}
        {!rows.length && <tr><td colSpan={head.length} style={{ padding: 16, textAlign: 'center', color: TOKENS.textMuted }}>Sin datos en el periodo.</td></tr>}
        {tots.map((r, j) => <tr key={'t' + j} style={{ background: '#f8faff' }}>{r.map((c, i) => <td key={i} style={{ padding: '8px 9px', borderBottom: `1px solid ${TOKENS.border}`, textAlign: i >= izq ? 'right' : 'left', fontWeight: j === tots.length - 1 ? 800 : 700, color: j === tots.length - 1 ? TOKENS.text : TOKENS.textMuted }}>{c}</td>)}</tr>)}
      </tbody>
    </table></div>;
  const Card = ({ t, sub, children, style }) => <div style={{ ...pcCard, padding: 14, ...style }}>{t && <div style={pcLbl}>{t}</div>}{sub && <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 3 }}>{sub}</div>}<div style={{ marginTop: t ? 8 : 0 }}>{children}</div></div>;
  const H2 = ({ children, sub }) => <><div style={{ fontSize: 15, fontWeight: 800, margin: '22px 0 4px' }}>{children}</div>{sub && <div style={{ fontSize: 12.5, color: TOKENS.textMuted, marginBottom: 8 }}>{sub}</div>}{!sub && <div style={{ height: 6 }} />}</>;
  const Barra = ({ partes }) => { const tot = partes.reduce((a, p) => a + p[1], 0) || 1; return <>
      <div style={{ display: 'flex', height: 26, borderRadius: 8, overflow: 'hidden', margin: '6px 0 8px', background: TOKENS.surfaceLow }}>{partes.filter((p) => p[1] > 0).map(([l, n, c]) => <div key={l} title={`${l}: ${n}`} style={{ width: pct(n, tot) + '%', background: c, color: '#fff', fontSize: 12, fontWeight: 700, display: 'grid', placeItems: 'center' }}>{pct(n, tot) >= 8 ? pct(n, tot) + '%' : ''}</div>)}</div>
      <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', fontSize: 12.5, color: TOKENS.textMuted }}>{partes.map(([l, n, c]) => <span key={l}><i style={{ display: 'inline-block', width: 10, height: 10, borderRadius: 3, background: c, marginRight: 6, verticalAlign: -1 }} />{l} · <b style={{ color: TOKENS.text }}>{fN(n)}</b></span>)}</div></>; };
  const pctTxt = (c) => c ? [c[0] + '%', c[1] + '%', c[2] + '%'] : ['', '', ''];
  const G = infGrupos(desde, hasta); const esSem = G.length && G[0].k[0] === 'S';
  const enG = (iso, g) => !!iso && iso >= g.d && iso <= g.h;
  const grid = (n) => ({ display: 'grid', gridTemplateColumns: `repeat(${cel ? Math.min(n, 2) : n}, minmax(0, 1fr))`, gap: cel ? 10 : 14 });
  // Lo de hoy (no depende del periodo; sí de los filtros)
  const regsHoy = regsAll.filter((r) => (!fa || r.aseguradora === fa) && (!ft || r.taller === ft));
  const pendHoy = regsHoy.filter((r) => r._estado === 'pend' && !r._gar && r._est);
  const nEst = (o) => pendHoy.filter((r) => r._est.orden === o).length;
  const pausasLargas = (typeof novedadesLista === 'function' ? novedadesLista(regsHoy) : []).filter((x) => x.tipo === 'pausa' && x.p.estado === 'espera' && servDiasEsperando(x.p) > 3).length;
  const garAbiertas = regsHoy.filter((r) => r._gar).length;
  const sinDatos = !A.R.length && !A.E.length && (!primero || hasta < primero);
  const cotA = A.rRec - A.elige;
  const asegTop = Object.entries(A.porAseg).sort((a, b) => b[1] - a[1]);

  // ── Resumen v3: tabla de indicadores + cumplimiento + rines por semana vs comparación + 3 tablas ──
  const varDe = (a, b, o = {}) => {
    if (!B || a == null || b == null) return null;
    const d = a - b; if (Math.abs(d) < 1e-9) return { txt: '= igual', t: 'eq' };
    const fl = d > 0 ? '▲ ' : '▼ ';
    const txt = o.pp ? `${fl}${Math.abs(d)} pts` : o.d ? `${fl}${Math.abs(d).toFixed(1)} días` : b ? `${fl}${Math.round(Math.abs(d) / b * 100)}%` : `${fl}${fN(Math.abs(d))}`;
    return { txt, t: o.neutro ? 'eq' : (o.menos ? d < 0 : d > 0) ? 'up' : 'dn' };
  };
  const pctN = (a, b) => b ? Math.round(a / b * 100) : 0;
  const cPP = A.rEnt ? AX.cumN.map((n) => pctN(n, A.rEnt)) : null, cPPb = B && B.rEnt ? BX.cumN.map((n) => pctN(n, B.rEnt)) : null;
  const sNov = AX.nvP + AX.nvNR + AX.nvNA, sNovB = BX ? BX.nvP + BX.nvNR + BX.nvNA : 0;
  const d1 = (v) => v == null ? '—' : v.toFixed(1);
  const S0 = AX.S;
  // Filas: n = 'h' (principal) | 's' (subfila); p = % (texto); pc = color de la píldora del %
  const IND = [
    { n: 'h', l: 'Rines recogidos', v: A.rRec, pTxt: `en ${fN(A.placas)} placas`, b: B && B.rRec, va: varDe(A.rRec, B && B.rRec) },
    { n: 'h', l: 'Rines entregados', v: A.rEnt, pTxt: `en ${fN(A.E.length)} placas`, b: B && B.rEnt, va: varDe(A.rEnt, B && B.rEnt) },
    { n: 's', l: 'A tiempo', det: `hasta el día ${S0}`, dot: '#2f8a56', v: AX.cumN[0], p: cPP && cPP[0], pc: [TOKENS.successBg, TOKENS.successText], b: cPPb && cPPb[0] + '%', va: varDe(cPP && cPP[0], cPPb && cPPb[0], { pp: 1 }) },
    { n: 's', l: 'Atrasados', det: `día ${S0 + 1}`, dot: TOKENS.warning, v: AX.cumN[1], p: cPP && cPP[1], pc: [TOKENS.warningBg, TOKENS.warningText], b: cPPb && cPPb[1] + '%', va: varDe(cPP && cPP[1], cPPb && cPPb[1], { pp: 1, menos: 1 }) },
    { n: 's', l: 'Vencidos', det: `día ${S0 + 2} o más`, dot: '#b3261e', v: AX.cumN[2], p: cPP && cPP[2], pc: [TOKENS.dangerBg, TOKENS.dangerText], b: cPPb && cPPb[2] + '%', va: varDe(cPP && cPP[2], cPPb && cPPb[2], { pp: 1, menos: 1 }) },
    { n: 'h', l: 'Rines con novedades', v: AX.nvR, p: pctN(AX.nvR, A.rRec), b: BX && BX.nvR, va: varDe(AX.nvR, BX && BX.nvR, { menos: 1 }) },
    { n: 's', l: 'En pausa', dot: PAUSA_COLOR.solid, v: AX.nvP, p: sNov ? pctN(AX.nvP, sNov) : null, pc: [PAUSA_COLOR.bg, PAUSA_COLOR.fg], b: BX && BX.nvP, va: varDe(AX.nvP, BX && BX.nvP, { menos: 1 }) },
    { n: 's', l: 'No reparables', dot: '#5a6781', v: AX.nvNR, p: sNov ? pctN(AX.nvNR, sNov) : null, pc: [TOKENS.surfaceLow, TOKENS.textMuted], b: BX && BX.nvNR, va: varDe(AX.nvNR, BX && BX.nvNR, { menos: 1 }) },
    { n: 's', l: 'No autorizados', dot: '#6c4aa6', v: AX.nvNA, p: sNov ? pctN(AX.nvNA, sNov) : null, pc: ['#efe9f7', '#6c4aa6'], b: BX && BX.nvNA, va: varDe(AX.nvNA, BX && BX.nvNA, { menos: 1 }) },
    { n: 'h', l: 'Rines express', v: AX.exR, p: pctN(AX.exR, A.rRec), b: BX && BX.exR, va: varDe(AX.exR, BX && BX.exR, { neutro: 1 }) },
    { n: 's', l: 'Días promedio express vs normal', vTxt: `${d1(AX.exProm)} vs ${d1(AX.noProm)}`, b: BX && `${d1(BX.exProm)} vs ${d1(BX.noProm)}` },
    { n: 'h', l: 'Rines con garantía', v: AX.garR, p: pctN(AX.garR, A.rEnt), b: BX && BX.garR, va: varDe(AX.garR, BX && BX.garR, { menos: 1 }) },
    { n: 'h', l: 'Días R→E promedio', vTxt: d1(A.prom), pTxt: 'hábiles, sin pausas', b: B && B.prom != null ? d1(B.prom) : B ? '—' : null, va: varDe(A.prom == null ? null : Number(A.prom.toFixed(1)), B && B.prom != null ? Number(B.prom.toFixed(1)) : null, { d: 1, menos: 1 }) }
  ];
  const indTxt = (f) => [f.n === 's' ? '   ' + f.l + (f.det ? ' (' + f.det + ')' : '') : f.l, f.vTxt != null ? f.vTxt : f.v, f.pTxt || (f.p == null ? '' : f.p + '%'), f.b == null ? '' : f.b, f.va ? f.va.txt : ''];
  const VA_C = { up: [TOKENS.successBg, TOKENS.successText], dn: [TOKENS.dangerBg, TOKENS.dangerText], eq: [TOKENS.surfaceLow, TOKENS.textMuted] };
  const pill = (txt, [bg, fg]) => <span style={{ display: 'inline-block', borderRadius: 6, padding: '1px 7px', fontSize: 12, fontWeight: 700, background: bg, color: fg, whiteSpace: 'nowrap' }}>{txt}</span>;
  const dotS = (c) => <span style={{ display: 'inline-block', width: 9, height: 9, borderRadius: 3, background: c, marginRight: 7 }} />;
  // Rines recogidos por semana (o por mes) vs la comparación, alineados por posición (S1 con S1…)
  const enUnMes = desde.slice(0, 7) === hasta.slice(0, 7);
  const gruposDe = (d, h) => enUnMes ? infSemDe(Number(d.slice(0, 4)), Number(d.slice(5, 7)) - 1) : infGrupos(d, h);
  const GA = gruposDe(desde, hasta), GB = C ? gruposDe(cd, ch) : [];
  const rinesEn = (g, tope) => g.d > tope ? null : infSum(regs.filter((r) => r._estado !== 'anu' && r._iso && r._iso >= g.d && r._iso <= (g.h < tope ? g.h : tope)), infRin);
  const topeA = enUnMes && per.modo === 'sem' ? (infFinMes(per.y, per.m) < hoy ? infFinMes(per.y, per.m) : hoy) : hasta;
  const BG = per.modo === 'sem' ? null : B; // en Semana el gráfico muestra las semanas del mes, sin comparación
  const serieA = GA.map((g) => rinesEn(g, topeA)), serieB = GB.map((g) => BG ? rinesEn(g, g.h) : null);
  const cortoA = per.modo === 'sem' ? `${infCap(INF_MESL[per.m])} ${per.y}` : P.col, cortoB = C ? C.col : '';
  const rotulo = (g) => enUnMes ? `${Number(g.d.slice(8))}–${Number(g.h.slice(8))} ${INF_MES[Number(g.d.slice(5, 7)) - 1]}` : g.k;
  // Talleres, aseguradoras y tiempo del mensajero
  const keyT = (r) => r.taller + '|' + (r.sede || '');
  const talleresTop = (() => {
    const m = {}; A.R.forEach((r) => { const o = m[keyT(r)] = m[keyT(r)] || { t: r.taller, s: r.sede || '', R: [], E: [] }; o.R.push(r); });
    A.E.forEach((r) => { if (m[keyT(r)]) m[keyT(r)].E.push(r); else m[keyT(r)] = { t: r.taller, s: r.sede || '', R: [], E: [r] }; });
    return Object.values(m).map((o) => ({ ...o, rr: infSum(o.R, infRin), re: infSum(o.E, infRin), c: infCumple(o.E), prom: o.E.length ? infSum(o.E, (r) => r._dias) / o.E.length : null, max: o.E.length ? Math.max(...o.E.map((r) => r._dias)) : null })).sort((a, b) => b.rr - a.rr || b.re - a.re);
  })();
  const asegTabla = (() => {
    const ks = [...new Set([...A.R, ...A.E].map((r) => r.aseguradora || '—'))];
    return ks.map((k) => { const R2 = A.R.filter((r) => (r.aseguradora || '—') === k), E2 = A.E.filter((r) => (r.aseguradora || '—') === k);
      return { k, rr: infSum(R2, infRin), re: infSum(E2, infRin), c: infCumple(E2), prom: E2.length ? infSum(E2, (r) => r._dias) / E2.length : null, nv: A.NV.filter((x) => (x.r.aseguradora || '—') === k).length, ant: B ? B.porAseg[k] || 0 : null }; }).sort((a, b) => b.rr - a.rr || b.re - a.re);
  })();
  const tiemposTaller = (() => {
    const m = {}; TIEMPOS.filter((t) => !ft || t.taller === ft).forEach((t) => { const k = (t.taller || '—') + '|' + (t.sede || ''); const o = m[k] = m[k] || { t: t.taller || '—', s: t.sede || '', n: 0, ms: 0, max: 0 }; o.n++; o.ms += t.ms || 0; o.max = Math.max(o.max, t.ms || 0); });
    return Object.values(m).map((o) => ({ ...o, prom: Math.round(o.ms / o.n / 60000), maxM: Math.round(o.max / 60000), totM: Math.round(o.ms / 60000) })).sort((a, b) => b.n - a.n || b.prom - a.prom);
  })();
  const hm = (min) => min >= 60 ? `${Math.floor(min / 60)} h ${min % 60} min` : `${min} min`;
  const barraMini = (v, max, c) => <span style={{ display: 'inline-block', height: 6, borderRadius: 99, background: c || TOKENS.primary, width: Math.max(4, Math.round(v / (max || 1) * 50)), marginLeft: 8, verticalAlign: 'middle' }} />;
  const pctCum = (c) => c ? pill(c[0] + '%', c[0] >= 85 ? [TOKENS.successBg, TOKENS.successText] : c[0] >= 75 ? ['#fdf0d5', '#8a5a00'] : [TOKENS.dangerBg, TOKENS.dangerText]) : '';
  const Sec = ({ t, sub, ir }) => <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, margin: '22px 0 8px' }}><b style={{ fontSize: 15 }}>{t}</b>{sub && <span style={{ fontSize: 12, color: TOKENS.textMuted }}>{sub}</span>}{ir && <button type="button" onClick={() => setTab(ir)} style={{ marginLeft: 'auto', border: 0, background: 'none', color: TOKENS.primary, fontWeight: 700, fontSize: 12.5, cursor: 'pointer', fontFamily: 'inherit' }}>Ver todos ›</button>}</div>;
  const tablaTiempos = (lim) => <Card><Tabla head={['Taller', 'Visitas', 'Minutos promedio en sitio', 'Visita más larga', 'Tiempo total']}
    rows={tiemposTaller.slice(0, lim).map((o) => [<span>{o.t}{o.s && <span style={{ color: TOKENS.textMuted, fontSize: 12 }}> · {o.s}</span>}</span>, o.n, <span><b>{o.prom} min</b>{barraMini(o.prom, Math.max(...tiemposTaller.map((x) => x.prom)), o.prom >= 25 ? '#c08a2a' : null)}</span>, `${o.maxM} min`, <span style={{ color: TOKENS.textMuted }}>{hm(o.totM)}</span>])} /></Card>;

  const tdI = { padding: cel ? '8px 5px' : '9px 10px', borderBottom: `1px solid ${TOKENS.border}`, textAlign: 'right', whiteSpace: cel ? 'normal' : 'nowrap', fontSize: cel ? 12.5 : undefined };
  // Tabla de indicadores (Resumen y pestañas): filas { n: 'h' | 's' | 's2', l, det, dot, v | vTxt, p | pTxt, pc, b, va }
  const tablaInd = (rows, nota) =>
        <div style={{ ...pcCard, padding: cel ? '4px 6px' : '6px 10px', overflowX: cel ? 'auto' : 'visible' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, fontVariantNumeric: 'tabular-nums' }}>
            <thead><tr><th style={{ ...thI, textAlign: 'left' }}>Indicador</th><th style={thI}>{P.col}</th>{!cel && <th style={thI}>%</th>}{C && <>{!cel && <th style={thI}>{cortoB}</th>}<th style={thI}>{cel ? 'vs ' + cortoB : 'Variación'}</th></>}</tr></thead>
            <tbody>{rows.map((f, i) => <tr key={i} style={{ background: f.n === 'h' ? '#f8faff' : undefined }}>
              <td style={{ ...tdI, textAlign: 'left', fontWeight: f.n === 'h' ? 700 : 400, paddingLeft: f.n !== 'h' ? (f.dot ? 24 : 30) : 10, color: f.n !== 'h' && !f.dot ? TOKENS.textMuted : TOKENS.text, whiteSpace: 'normal' }}>{f.dot && dotS(f.dot)}{f.l}{f.det && <span style={{ fontSize: 12, color: TOKENS.textMuted }}> · {f.det}</span>}</td>
              <td style={{ ...tdI, fontWeight: 800 }}>{f.vTxt != null ? f.vTxt : f.v == null ? '' : fN(f.v)}{cel && (f.p != null || f.pTxt) && <div style={{ fontWeight: 400, marginTop: 2 }}>{f.pTxt ? <span style={{ fontSize: 11, color: TOKENS.textMuted }}>{f.pTxt}</span> : f.pc ? pill(f.p + '%', f.pc) : <span style={{ fontSize: 11.5, color: TOKENS.textMuted }}>{f.p}%</span>}</div>}</td>
              {!cel && <td style={tdI}>{f.pTxt ? <span style={{ color: TOKENS.textMuted }}>{f.pTxt}</span> : f.p == null ? '' : f.pc ? pill(f.p + '%', f.pc) : f.p + '%'}</td>}
              {C && <>{!cel && <td style={{ ...tdI, color: TOKENS.textMuted }}>{B ? (f.b == null ? '' : typeof f.b === 'number' ? fN(f.b) : f.b) : ''}</td>}<td style={tdI}>{cel && B && f.b != null && <div style={{ fontSize: 11, color: TOKENS.textSubtle, marginBottom: 2 }}>antes {typeof f.b === 'number' ? fN(f.b) : f.b}</div>}{f.va ? pill(f.va.txt, VA_C[f.va.t]) : B ? '' : i === 0 ? <span style={{ fontSize: 12, color: TOKENS.textSubtle }}>sin datos</span> : ''}</td></>}
            </tr>)}</tbody>
          </table>
          <div style={{ fontSize: 11.5, color: TOKENS.textSubtle, padding: '8px 10px 6px' }}>{nota}{C && !B && ' No hay datos en la app para el periodo de comparación.'}</div>
        </div>;
  const cardCumpl = () =>
          <Card t="Cumplimiento de lo entregado">
            {A.rEnt ? <>
              <div style={{ display: 'flex', height: 28, borderRadius: 8, overflow: 'hidden', margin: '4px 0 8px' }}>{[[0, '#2f8a56'], [1, '#c08a2a'], [2, '#b3261e']].filter(([k]) => AX.cumN[k]).map(([k, c]) => <div key={k} style={{ width: cPP[k] + '%', minWidth: 22, background: c, color: '#fff', fontSize: 12, fontWeight: 700, display: 'grid', placeItems: 'center' }}>{cPP[k] >= 6 ? cPP[k] + '%' : ''}</div>)}</div>
              <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap', fontSize: 12.5, color: TOKENS.textMuted }}><span>{dotS('#2f8a56')}A tiempo {fN(AX.cumN[0])}</span><span>{dotS('#c08a2a')}Atrasados {fN(AX.cumN[1])}</span><span>{dotS('#b3261e')}Vencidos {fN(AX.cumN[2])}</span></div>
              {cPPb && <div style={{ fontSize: 12, color: TOKENS.textSubtle, marginTop: 6 }}>{cortoB}: {cPPb.join('% · ')}%</div>}
            </> : <span style={{ fontSize: 13, color: TOKENS.textMuted }}>Sin entregas en el periodo.</span>}
          </Card>;
  const cardSemanas = () => {
    const maxBar = Math.max(1, ...serieA.map((v) => v || 0), ...serieB.map((v) => v || 0));
    const nBar = Math.max(GA.length, GB.length);
    return (
          <Card t={`Rines recogidos por ${enUnMes ? 'semana' : 'mes'}${BG ? ` · ${cortoA} vs ${cortoB}` : ''}`}>
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: 10, height: 150, marginTop: 10, padding: '0 4px' }}>
              {Array.from({ length: nBar }).map((_, i) => { const a = serieA[i], b = serieB[i], gA = GA[i], gB = GB[i]; const cur = gA && gA.d <= topeA && gA.h > topeA;
                const sel = per.modo === 'sem' && gA && gA.d === desde;
                return <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'flex-end', gap: 3, height: 118, width: '100%', justifyContent: 'center' }}>
                    <div style={{ flex: 1, maxWidth: BG ? 26 : 40, textAlign: 'center' }}><div style={{ fontSize: 11, fontWeight: 700, marginBottom: 3 }}>{a == null ? '' : a}</div><div style={{ height: (a || 0) / maxBar * 92, background: per.modo === 'sem' && !sel ? '#8aa6d6' : TOKENS.primary, opacity: cur ? 0.55 : 1, borderRadius: '5px 5px 0 0' }} /></div>
                    {BG && <div style={{ flex: 1, maxWidth: 26, textAlign: 'center' }}><div style={{ fontSize: 11, color: TOKENS.textMuted, marginBottom: 3 }}>{b == null ? '' : b}</div><div style={{ height: (b || 0) / maxBar * 92, background: '#b9c7de', borderRadius: '5px 5px 0 0' }} /></div>}
                  </div>
                  <div style={{ fontSize: 11.5, fontWeight: 700, marginTop: 5 }}>{enUnMes ? 'S' + (i + 1) : (gA || gB).k.split(' ')[0]}</div>
                  <div style={{ fontSize: 10.5, color: TOKENS.textMuted, lineHeight: 1.35, textAlign: 'center' }}>{enUnMes && gA ? rotulo(gA) : ''}{BG && gB && enUnMes && <><br /><span style={{ color: TOKENS.textSubtle }}>{rotulo(gB)}</span></>}</div>
                </div>; })}
            </div>
            <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap', fontSize: 12.5, color: TOKENS.textMuted, marginTop: 10 }}><span>{dotS(TOKENS.primary)}{cortoA}</span>{BG && <span>{dotS('#b9c7de')}{cortoB}</span>}{GA.some((g) => g.d <= topeA && g.h > topeA) && <span style={{ color: TOKENS.textSubtle }}>la barra clara va en curso</span>}</div>
            {BG && enUnMes && <div style={{ fontSize: 11.5, color: TOKENS.textSubtle, marginTop: 4 }}>Las semanas no tienen los mismos días en cada mes: S1 empieza el día 1 y corta el sábado.</div>}
          </Card>);
  };
  const NOTA_NOV = 'Un rin que estuvo en pausa y luego no se autorizó cuenta en las dos subfilas de novedades.';
  const dos = { display: 'grid', gridTemplateColumns: cel ? 'minmax(0, 1fr)' : 'minmax(0, 1.55fr) minmax(0, 1fr)', gap: 14, alignItems: 'start' };
  const vistaResumen = () => <>
      <div style={dos}>
        {tablaInd(IND, NOTA_NOV)}
        <div style={{ display: 'grid', gap: 14 }}>{cardCumpl()}{cardSemanas()}</div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: cel ? '1fr' : '1fr 1fr', gap: 14 }}>
        <div><Sec t="Talleres donde más se recogió" sub="top 10" ir="tal" />
          <Card><Tabla head={['Taller', 'Rines', '% a tiempo', 'Días R→E prom.', 'Más largo']}
            rows={talleresTop.filter((o) => o.rr).slice(0, 10).map((o) => [<span>{o.t}{o.s && <span style={{ color: TOKENS.textMuted, fontSize: 12 }}> · {o.s}</span>}</span>, <span><b>{fN(o.rr)}</b>{barraMini(o.rr, talleresTop[0] ? talleresTop[0].rr : 1)}</span>, pctCum(o.c), o.prom == null ? '' : o.prom.toFixed(1), o.max == null ? '' : o.max])} /></Card></div>
        <div><Sec t="Aseguradoras que más rines enviaron" sub="top 10" ir="ase" />
          <Card><Tabla head={['Aseguradora', 'Rines', '% del total', '% a tiempo', 'R→E prom.', ...(B ? [cortoB] : [])]}
            rows={asegTabla.filter((o) => o.rr).slice(0, 10).map((o) => [<span>{o.k}{infElige(o.k) && <span style={{ color: TOKENS.textMuted, fontSize: 12 }}> · elige el taller</span>}</span>, <b>{fN(o.rr)}</b>, pctN(o.rr, A.rRec) + '%', o.c ? o.c[0] + '%' : '', o.prom == null ? '' : o.prom.toFixed(1), ...(B ? [<span style={{ color: TOKENS.textMuted }}>{fN(o.ant)} {o.rr > o.ant ? <span style={{ color: TOKENS.successText }}>▲</span> : o.rr < o.ant ? <span style={{ color: TOKENS.dangerText }}>▼</span> : ''}</span>] : [])])} /></Card></div>
      </div>
      <Sec t="Tiempo del mensajero por taller" sub="desde que llega hasta que finaliza la parada" ir="ope" />
      {tablaTiempos(10)}
    </>;

  // ── Pestañas v3 (25/11/2026): tabla de indicadores + gráficos + tablas completas, como el Resumen ──
  const llego = (r) => r.comoLlego === 'otra-ciudad' ? 2 : r.comoLlego === 'taller' ? 1 : (r.encargo || r.comoLlego === 'encargo') ? 3 : 0;
  const rinL = (L2, f) => infSum(L2.filter(f), infRin);
  const piezas = (L2, t) => infSum(L2, (r) => infCnt(r, t));
  const habiles = (d, h) => { let n = 0, c = d; while (c <= h) { if (!window.isBusinessDay || window.isBusinessDay(infD(c))) n++; c = infMas(c, 1); } return n; };
  const promDias = (L2) => L2.length ? infSum(L2, (r) => r._dias) / L2.length : null;
  const mediana = (L2) => { if (!L2.length) return null; const v = L2.map((r) => r._dias).sort((a, b) => a - b); const m = Math.floor(v.length / 2); return v.length % 2 ? v[m] : (v[m - 1] + v[m]) / 2; };
  const fila = (n, l, a, b, o = {}) => ({ n, l, v: a, b, va: o.sinVar ? null : varDe(a, b, o), ...o });
  const pctDe = (a, t) => t ? pctN(a, t) : null;
  const sinCero = (v) => v ? v : '';
  const placaM = (p) => <b style={{ fontFamily: pcMono }}>{p}</b>;
  const barraSeg = (partes, alto) => <div style={{ display: 'flex', height: alto || 22, borderRadius: 6, overflow: 'hidden', background: TOKENS.surfaceLow }}>{partes.filter((x) => x[0] > 0).map(([w, c], k) => <div key={k} style={{ width: w + '%', background: c, color: '#fff', fontSize: 11, fontWeight: 700, display: 'grid', placeItems: 'center' }}>{w >= 8 ? w + '%' : ''}</div>)}</div>;
  const legend = (items) => <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap', fontSize: 12.5, color: TOKENS.textMuted, marginTop: 8 }}>{items.map(([c, t]) => <span key={t}>{dotS(c)}{t}</span>)}</div>;

  const vistaRecogidas = () => {
    const ll = (L2, k) => rinL(L2, (r) => llego(r) === k);
    const cotB = B ? B.rRec - B.elige : null;
    const hA = habiles(desde, hasta), hB = B ? habiles(cd, ch) : 0;
    const porDiaA = hA ? Number((A.rRec / hA).toFixed(1)) : null, porDiaB = B && hB ? Number((B.rRec / hB).toFixed(1)) : null;
    const rows = [
      fila('h', 'Rines recogidos', A.rRec, B && B.rRec, { pTxt: `en ${fN(A.placas)} placas` }),
      fila('s', 'De aseguradoras que cotizamos', cotA, cotB, { dot: TOKENS.primary, p: pctDe(cotA, A.rRec) }),
      fila('s', 'El taller elige', A.elige, B && B.elige, { dot: '#3a8a6a', det: 'taller directo, Allianz, Renting…', p: pctDe(A.elige, A.rRec) }),
      { n: 'h', l: 'Cómo llegaron' },
      ...[['Los recogió el mensajero', 0, TOKENS.primary], ['Los trajo el taller', 1, '#8aa6d6'], ['De otra ciudad', 2, '#c08a2a'], ['Encargo', 3, '#6c4aa6']].map(([l, k, c]) => fila('s', l, ll(A.R, k), B && ll(B.R, k), { dot: c, p: pctDe(ll(A.R, k), A.rRec) })),
      { n: 'h', l: 'Otras piezas recogidas' },
      fila('s2', 'Llantas', piezas(A.R, 'llanta'), B && piezas(B.R, 'llanta')),
      fila('s2', 'Válvulas', piezas(A.R, 'valvula'), B && piezas(B.R, 'valvula')),
      { n: 'h', l: 'Promedio de rines por día hábil', vTxt: porDiaA == null ? '—' : porDiaA.toFixed(1), pTxt: `${hA} ${hA === 1 ? 'día hábil' : 'días hábiles'}`, b: porDiaB == null ? (B ? '—' : null) : porDiaB.toFixed(1), va: varDe(porDiaA, porDiaB) }
    ];
    const cols = (L2) => { const el = rinL(L2, (r) => infElige(r.aseguradora)), t = infSum(L2, infRin); return [fN(t), fN(t - el), fN(el), fN(ll(L2, 0)), fN(ll(L2, 1)), fN(piezas(L2, 'llanta')), fN(piezas(L2, 'valvula')), fN(L2.length)]; };
    return <>
      <div style={dos}>
        {tablaInd(rows)}
        <div style={{ display: 'grid', gap: 14 }}>{cardSemanas()}
          <Card t="De quién vienen los rines">{A.rRec ? <>{barraSeg([[pctN(cotA, A.rRec), TOKENS.primary], [pctN(A.elige, A.rRec), '#3a8a6a']], 26)}{legend([[TOKENS.primary, `Cotizamos ${fN(cotA)}`], ['#3a8a6a', `El taller elige ${fN(A.elige)}`]])}{B && B.rRec ? <div style={{ fontSize: 12, color: TOKENS.textSubtle, marginTop: 4 }}>{cortoB}: {pctN(cotB, B.rRec)}% · {pctN(B.elige, B.rRec)}%</div> : null}</> : <span style={{ fontSize: 13, color: TOKENS.textMuted }}>Sin rines recogidos en el periodo.</span>}</Card>
        </div>
      </div>
      <Sec t={enUnMes ? 'Por semana' : 'Por mes'} sub={enUnMes ? 'semanas de lunes a sábado; el domingo cuenta con la semana siguiente' : null} />
      <Card><Tabla head={[enUnMes ? 'Semana' : 'Mes', ...(enUnMes ? ['Días'] : []), 'Rines', '— cotizamos', '— taller elige', 'Mensajero', 'Taller los trajo', 'Llantas', 'Válvulas', 'Placas', ...(BG ? [`${cortoB} (misma ${enUnMes ? 'semana' : 'posición'})`] : [])]}
        rows={GA.filter((g) => g.d <= topeA).map((g, i) => { const R2 = regs.filter((r) => r._estado !== 'anu' && r._iso && r._iso >= g.d && r._iso <= (g.h < topeA ? g.h : topeA)); return [enUnMes ? 'S' + (i + 1) : g.k, ...(enUnMes ? [rotulo(g) + (g.h > topeA ? ' · en curso' : '')] : []), ...cols(R2), ...(BG ? [serieB[i] == null ? '' : fN(serieB[i])] : [])]; })}
        tots={per.modo === 'sem' ? [] : [['Total', ...(enUnMes ? [''] : []), ...cols(A.R), ...(BG ? [B ? `${fN(B.rRec)} (${infTxtR(cd, ch)})` : ''] : [])]]} /></Card>
    </>;
  };

  const vistaEntregas = () => {
    const ex = (X) => X.E.filter((r) => r.express), exA = ex(A), exB = B ? ex(B) : [];
    const exAT = rinL(exA, (r) => r._plazo >= 2), exBT = B ? rinL(exB, (r) => r._plazo >= 2) : 0;
    const exPA = infSum(exA, infRin) ? pctN(exAT, infSum(exA, infRin)) : null, exPB = B && infSum(exB, infRin) ? pctN(exBT, infSum(exB, infRin)) : null;
    const nPend = pendHoy.length;
    const rows = [
      ...IND.slice(1, 5),
      { n: 'h', l: 'Días R→E promedio', vTxt: d1(A.prom), pTxt: 'hábiles, sin pausas', b: B ? d1(B.prom) : null, va: varDe(A.prom == null ? null : Number(A.prom.toFixed(1)), B && B.prom != null ? Number(B.prom.toFixed(1)) : null, { d: 1, menos: 1 }) },
      { n: 's2', l: 'Mediana', vTxt: mediana(A.E) == null ? '—' : String(mediana(A.E)), b: B ? (mediana(B.E) == null ? '—' : String(mediana(B.E))) : null },
      { n: 's2', l: 'Express vs normal', vTxt: `${d1(AX.exProm)} vs ${d1(AX.noProm)}`, b: BX ? `${d1(BX.exProm)} vs ${d1(BX.noProm)}` : null },
      fila('h', 'Rines express entregados', infSum(exA, infRin), B && infSum(exB, infRin), { p: pctDe(infSum(exA, infRin), A.rEnt), neutro: 1 }),
      { n: 's', l: 'Express a tiempo', det: `hasta el día ${pcSlaDe(true)}`, dot: '#2f8a56', v: exAT, p: exPA, pc: exPA == null ? null : exPA >= 85 ? [TOKENS.successBg, TOKENS.successText] : ['#fdf0d5', '#8a5a00'], b: exPB == null ? (B ? '—' : null) : exPB + '%', va: varDe(exPA, exPB, { pp: 1 }) },
      { n: 'h', l: 'Por entregar hoy', v: nPend, pTxt: 'placas recogidas sin entregar' },
      ...[['En plazo', 3, '#2f8a56'], ['Vencen hoy', 2, '#d9a400'], ['Retrasadas', 1, TOKENS.warning], ['Vencidas', 0, TOKENS.danger]].map(([l, k, c]) => ({ n: 's', l, dot: c, v: nEst(k), p: pctDe(nEst(k), nPend) }))
    ];
    const cajas = infCajas(A.E); const totC = cajas.reduce((a, b) => a + b, 0);
    const GE = GA.filter((g) => g.d <= topeA);
    const pasadas = pendHoy.filter((r) => r._est.orden <= 1).sort((a, b) => a._est.orden - b._est.orden || (b._est.dias || 0) - (a._est.dias || 0));
    return <>
      <div style={dos}>
        {tablaInd(rows)}
        <div style={{ display: 'grid', gap: 14 }}>{cardCumpl()}
          <Card t={`Cumplimiento por ${enUnMes ? 'semana' : 'mes'} de entrega`}>{GE.map((g, i) => { const E2 = A.E.filter((r) => enG(r._isoEnt, g)); const c = infCumple(E2); const t = infSum(E2, infRin);
            return <div key={i} style={{ display: 'grid', gridTemplateColumns: '44px 1fr 64px', gap: 10, alignItems: 'center', margin: '10px 0', fontSize: 12.5 }}><b>{enUnMes ? 'S' + (i + 1) : g.k.split(' ')[0]}</b>{c ? barraSeg([[c[0], '#2f8a56'], [c[1], '#c08a2a'], [c[2], '#b3261e']]) : <span style={{ color: TOKENS.textMuted }}>sin entregas</span>}<span style={{ textAlign: 'right', color: TOKENS.textMuted }}>{fN(t)} rines</span></div>; })}</Card>
        </div>
      </div>
      <Sec t="Días contra el límite" sub="rines entregados según cuántos días hábiles tardaron, sin contar pausas" />
      <Card><Tabla head={[enUnMes ? 'Entregados en' : 'Mes', `Antes del límite (0–${S0 - 1})`, `El día límite (${S0})`, `1 día tarde (${S0 + 1})`, `2 días tarde (${S0 + 2})`, `3+ días tarde (${S0 + 3}+)`, 'Total']}
        rows={GE.map((g, i) => { const E2 = A.E.filter((r) => enG(r._isoEnt, g)); return [enUnMes ? 'S' + (i + 1) : g.k, ...infCajas(E2).map((n) => n ? fN(n) : ''), fN(infSum(E2, infRin))]; })}
        tots={[['Total', ...cajas.map(fN), fN(totC)], ['% del total', ...cajas.map((n) => pctN(n, totC) + '%'), totC ? '100%' : '']]} /></Card>
      <Sec t="Placas por entregar que ya pasaron el límite" sub="hoy, las vencidas primero" />
      <Card><Tabla izq={3} head={['Placa', 'Taller', 'Aseguradora', 'Recogida', 'Días hábiles', 'Estado']}
        rows={pasadas.map((r) => [placaM(r.placa), r.taller + (r.sede ? ' · ' + r.sede : ''), r.aseguradora || '', pcFechaCorta(r.fecha), r._est.dias == null ? '' : r._est.dias, pill(r._est.orden === 0 ? 'Vencida' : 'Retrasada', r._est.orden === 0 ? [TOKENS.dangerBg, TOKENS.dangerText] : ['#fdf0d5', '#8a5a00'])])} /></Card>
    </>;
  };

  const vistaAseg = () => {
    const F = asegTabla;
    const rinA = (L2, k) => infSum(L2.filter((r) => (r.aseguradora || '—') === k), infRin);
    const filaA = (o) => { const E2 = A.E.filter((r) => (r.aseguradora || '—') === o.k); return [<span>{o.k}{infElige(o.k) && <span style={{ color: TOKENS.textMuted, fontSize: 12 }}> · elige el taller</span>}</span>, <b>{fN(o.rr)}</b>, pctN(o.rr, A.rRec) + '%', fN(o.re), pctCum(o.c), sinCero(rinL(E2, (r) => r._plazo === 1)), sinCero(rinL(E2, (r) => r._plazo === 0)), o.prom == null ? '' : o.prom.toFixed(1), sinCero(o.nv), ...(B ? [fN(o.ant), (() => { const v = varDe(o.rr, o.ant); return v ? pill(v.txt, VA_C[v.t]) : ''; })()] : [])]; };
    const tot = (ks, t) => { const R2 = A.R.filter((r) => ks.includes(r.aseguradora || '—')), E2 = A.E.filter((r) => ks.includes(r.aseguradora || '—')); const rr = infSum(R2, infRin), ant = B ? infSum(ks, (k) => B.porAseg[k] || 0) : 0; const v = varDe(rr, ant);
      return [t, fN(rr), pctN(rr, A.rRec) + '%', fN(infSum(E2, infRin)), pctCum(infCumple(E2)), fN(rinL(E2, (r) => r._plazo === 1)), fN(rinL(E2, (r) => r._plazo === 0)), E2.length ? promDias(E2).toFixed(1) : '—', fN(A.NV.filter((x) => ks.includes(x.r.aseguradora || '—')).length), ...(B ? [fN(ant), v ? pill(v.txt, VA_C[v.t]) : ''] : [])]; };
    const ks = F.map((o) => o.k), cot = ks.filter((k) => !infElige(k)), eli = ks.filter(infElige);
    const top = F.filter((o) => o.rr || (B && B.porAseg[o.k])).slice(0, 8); const mx = Math.max(1, ...top.map((o) => Math.max(o.rr, B ? B.porAseg[o.k] || 0 : 0)));
    const cumL = F.map((o) => ({ ...o, E2: A.E.filter((r) => (r.aseguradora || '—') === o.k) })).filter((o) => infSum(o.E2, infRin) >= 3).map((o) => ({ ...o, c: infCumple(o.E2) })).sort((a, b) => a.c[0] - b.c[0]);
    return <>
      <Card><Tabla head={['Aseguradora', 'Rines', '% del total', 'Entregados', '% a tiempo', 'Atrasados', 'Vencidos', 'R→E prom.', 'Novedades', ...(B ? [cortoB, 'Variación'] : [])]} rows={F.map(filaA)}
        tots={F.length ? [tot(cot, 'Las que cotizamos'), tot(eli, 'Donde el taller elige'), tot(ks, 'Total')] : []} /></Card>
      <div style={{ display: 'grid', gridTemplateColumns: cel ? '1fr' : '1fr 1fr', gap: 14, marginTop: 14, alignItems: 'start' }}>
        <Card t={`Rines recogidos${B ? ` · ${cortoA} vs ${cortoB}` : ''}`}>{top.map((o) => <div key={o.k} style={{ display: 'grid', gridTemplateColumns: '140px 1fr 70px', gap: 10, alignItems: 'center', margin: '9px 0', fontSize: 12.5 }}><span>{o.k}</span><span style={{ position: 'relative', height: B ? 16 : 10 }}><span style={{ position: 'absolute', top: 0, height: 8, borderRadius: 99, background: TOKENS.primary, width: pctN(o.rr, mx) + '%' }} />{B && <span style={{ position: 'absolute', top: 9, height: 6, borderRadius: 99, background: '#b9c7de', width: pctN(B.porAseg[o.k] || 0, mx) + '%' }} />}</span><b style={{ textAlign: 'right' }}>{fN(o.rr)}{B && <span style={{ color: TOKENS.textMuted, fontWeight: 400 }}> / {fN(B.porAseg[o.k] || 0)}</span>}</b></div>)}
          {!top.length ? <span style={{ fontSize: 13, color: TOKENS.textMuted }}>Sin rines en el periodo.</span> : legend([[TOKENS.primary, cortoA], ...(B ? [['#b9c7de', cortoB]] : [])])}</Card>
        <Card t="% a tiempo por aseguradora · del peor al mejor"><div style={{ fontSize: 11.5, color: TOKENS.textSubtle, marginTop: -4 }}>solo las que tienen 3 rines entregados o más</div>
          {cumL.map((o) => <div key={o.k} style={{ display: 'grid', gridTemplateColumns: '110px 1fr 60px', gap: 10, alignItems: 'center', margin: '9px 0', fontSize: 12.5 }}><span>{o.k}</span>{barraSeg([[o.c[0], '#2f8a56'], [o.c[1], '#c08a2a'], [o.c[2], '#b3261e']])}<span style={{ textAlign: 'right', color: TOKENS.textMuted }}>{fN(infSum(o.E2, infRin))} rines</span></div>)}
          {!cumL.length && <div style={{ fontSize: 13, color: TOKENS.textMuted, marginTop: 8 }}>Ninguna con 3 rines entregados o más.</div>}</Card>
      </div>
    </>;
  };

  const vistaTalleres = () => {
    const AS = asegTop.filter((x) => x[1]).slice(0, 10).map((x) => x[0]);
    const gar = {}; GL.forEach(({ r, g }) => { gar[keyT(r)] = (gar[keyT(r)] || 0) + ((g.rines || []).length || 1); });
    const tiem = {}; tiemposTaller.forEach((o) => { tiem[o.t + '|' + o.s] = o; });
    const antT = {}; if (B) B.R.forEach((r) => { antT[keyT(r)] = (antT[keyT(r)] || 0) + infRin(r); });
    const F = talleresTop.slice(0, 25);
    const nvT = (k) => A.NV.filter((x) => keyT(x.r) === k).length;
    const tt = tiemposTaller.reduce((a, o) => ({ n: a.n + o.n, ms: a.ms + o.ms }), { n: 0, ms: 0 });
    return <>
      <div style={{ fontSize: 12.5, color: TOKENS.textMuted, marginBottom: 8 }}>Taller + sede, ordenados por rines recogidos (top 25).</div>
      <Card style={{ overflow: 'auto' }}><Tabla head={['Taller', 'Rines', 'Entregados', '% a tiempo', 'R→E prom.', 'Más largo', 'Novedades', 'Garantías', 'Visitas', 'Min. en sitio', ...(B ? [cortoB, 'Variación'] : [])]}
        rows={F.map((o) => { const k = o.t + '|' + o.s, ti = tiem[k], ant = antT[k] || 0, v = varDe(o.rr, ant); return [<span>{o.t}{o.s && <span style={{ color: TOKENS.textMuted, fontSize: 12 }}> · {o.s}</span>}</span>, <b>{fN(o.rr)}</b>, fN(o.re), pctCum(o.c), o.prom == null ? '' : o.prom.toFixed(1), o.max == null ? '' : o.max, sinCero(nvT(k)), sinCero(gar[k]), ti ? ti.n : '', ti ? ti.prom + ' min' : '', ...(B ? [fN(ant), v ? pill(v.txt, VA_C[v.t]) : ''] : [])]; })}
        tots={F.length ? [['Total', fN(A.rRec), fN(A.rEnt), pctCum(A.cum), d1(A.prom), A.E.length ? Math.max(...A.E.map((r) => r._dias)) : '—', fN(A.NV.length), fN(AX.garR), fN(tt.n), tt.n ? Math.round(tt.ms / tt.n / 60000) + ' min' : '—', ...(B ? [fN(B.rRec), (() => { const v = varDe(A.rRec, B.rRec); return v ? pill(v.txt, VA_C[v.t]) : ''; })()] : [])]] : []} /></Card>
      <Sec t="Quién manda los rines de cada taller" sub="rines recogidos por taller y aseguradora" />
      <Card style={{ overflow: 'auto' }}><Tabla head={['Taller', 'Rines', ...AS]}
        rows={F.filter((o) => o.rr).map((o) => [<span>{o.t}{o.s && <span style={{ color: TOKENS.textMuted, fontSize: 12 }}> · {o.s}</span>}</span>, <b>{fN(o.rr)}</b>, ...AS.map((a) => { const n = infSum(o.R.filter((r) => r.aseguradora === a), infRin); return n ? fN(n) : <span style={{ color: TOKENS.textSubtle }}>·</span>; })])} /></Card>
    </>;
  };

  const vistaNovedades = () => {
    const noCob = (L2) => L2.filter((x) => x.tipo === 'sr' || (x.p && x.p.estado === 'no')).reduce((a, x) => { const rin = (servDe(x.r).rines || [])[x.i] || {}; return a + (Number(rin.precio) || 0); }, 0);
    const pausaProm = (L2) => { const p = L2.filter((x) => x.tipo === 'pausa'); return p.length ? p.reduce((a, x) => a + servDiasEsperando(x.p), 0) / p.length : null; };
    const abiertas = (typeof novedadesLista === 'function' ? novedadesLista(regsHoy) : []).filter((x) => x.tipo === 'pausa' && x.p.estado === 'espera').sort((a, b) => servDiasEsperando(b.p) - servDiasEsperando(a.p));
    const ppA = pausaProm(A.NV), ppB = B ? pausaProm(B.NV) : null;
    const ncA = noCob(A.NV), ncB = B ? noCob(B.NV) : null;
    const rows = [
      fila('h', 'Rines con novedades', AX.nvR, BX && BX.nvR, { pTxt: `${pctN(AX.nvR, A.rRec)}% de lo recogido`, menos: 1 }),
      IND[6],
      { n: 's2', l: 'Días hábiles promedio en pausa', vTxt: d1(ppA), b: B ? d1(ppB) : null, va: varDe(ppA == null ? null : Number(ppA.toFixed(1)), ppB == null ? null : Number(ppB.toFixed(1)), { d: 1, menos: 1 }) },
      { n: 's2', l: 'Pausas abiertas hoy', v: abiertas.length, pTxt: abiertas.filter((x) => servDiasEsperando(x.p) > 3).length ? `${abiertas.filter((x) => servDiasEsperando(x.p) > 3).length} con más de 3 días` : '' },
      IND[7], IND[8],
      { n: 'h', l: 'Valor que no se cobró', vTxt: pcPesos(ncA), pTxt: 'no reparables y no autorizados', b: B ? pcPesos(ncB) : null, va: varDe(ncA, ncB, { menos: 1 }) },
      fila('h', 'Rines con garantía', AX.garR, BX && BX.garR, { pTxt: `${pctN(AX.garR, A.rEnt)}% de lo entregado`, menos: 1 }),
      { n: 's2', l: 'Días promedio de la segunda entrega', vTxt: d1(garProm) },
      { n: 's2', l: 'Garantías abiertas hoy', v: garAbiertas }
    ];
    const pa = {}; NV.forEach((x) => { const k = x.r.aseguradora || '—'; const o = pa[k] = pa[k] || { p: 0, d: 0, na: 0, nr: 0, L: [] }; o.L.push(x); if (x.tipo === 'pausa') { o.p++; o.d += servDiasEsperando(x.p); } if (x.nov === 'na') o.na++; if (x.tipo === 'sr' && x.nov === 'nr') o.nr++; });
    const pt = {}; NV.forEach((x) => { const k = x.r.taller + (x.r.sede ? ' · ' + x.r.sede : ''); const o = pt[k] = pt[k] || { p: 0, na: 0, nr: 0, g: 0 }; if (x.tipo === 'pausa') o.p++; if (x.nov === 'na') o.na++; if (x.tipo === 'sr' && x.nov === 'nr') o.nr++; });
    GL.forEach(({ r }) => { const k = r.taller + (r.sede ? ' · ' + r.sede : ''); const o = pt[k] = pt[k] || { p: 0, na: 0, nr: 0, g: 0 }; o.g++; });
    const gm = {}; GL.forEach(({ r, g }) => { const o = gm[g.motivo || '—'] = gm[g.motivo || '—'] || { n: 0, t: new Set() }; o.n += (g.rines || []).length || 1; o.t.add(r.taller + (r.sede ? ' · ' + r.sede : '')); });
    const sN = AX.nvP + AX.nvNR + AX.nvNA;
    return <>
      <div style={dos}>
        {tablaInd(rows, NOTA_NOV)}
        <div style={{ display: 'grid', gap: 14 }}>
          <Card t="Novedades por tipo">{sN ? <>{barraSeg([[pctN(AX.nvP, sN), PAUSA_COLOR.solid], [pctN(AX.nvNR, sN), '#5a6781'], [pctN(AX.nvNA, sN), '#6c4aa6']], 26)}{legend([[PAUSA_COLOR.solid, `En pausa ${AX.nvP}`], ['#5a6781', `No reparables ${AX.nvNR}`], ['#6c4aa6', `No autorizados ${AX.nvNA}`]])}</> : <span style={{ fontSize: 13, color: TOKENS.textMuted }}>Sin novedades en el periodo.</span>}</Card>
          <Card t="Garantías por motivo"><Tabla izq={1} head={['Motivo', 'Rines', 'Talleres']} rows={Object.entries(gm).sort((a, b) => b[1].n - a[1].n).map(([k, o]) => [k, o.n, <span style={{ fontSize: 12, color: TOKENS.textMuted }}>{[...o.t].join(', ')}</span>])} /></Card>
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: cel ? '1fr' : '1fr 1fr', gap: 14 }}>
        <div><Sec t="Novedades por aseguradora" />
          <Card><Tabla head={['Aseguradora', 'En pausa', 'Días prom.', 'No reparables', 'No autorizados', 'No cobrado']}
            rows={Object.entries(pa).sort((a, b) => (b[1].p + b[1].na + b[1].nr) - (a[1].p + a[1].na + a[1].nr)).map(([k, o]) => [k, sinCero(o.p), o.p ? (o.d / o.p).toFixed(1) : '', sinCero(o.nr), sinCero(o.na), noCob(o.L) ? pcPesos(noCob(o.L)) : ''])}
            tots={NV.length ? [['Total', fN(NVp.length), d1(promPausa), fN(NVnr.length), fN(NVna.length), pcPesos(noCobrado)]] : []} /></Card></div>
        <div><Sec t="Novedades por taller" />
          <Card><Tabla head={['Taller', 'En pausa', 'No reparables', 'No autorizados', 'Garantías']}
            rows={Object.entries(pt).sort((a, b) => (b[1].p + b[1].na + b[1].nr + b[1].g) - (a[1].p + a[1].na + a[1].nr + a[1].g)).map(([k, o]) => [k, sinCero(o.p), sinCero(o.nr), sinCero(o.na), sinCero(o.g)])} /></Card></div>
      </div>
      <Sec t="Pausas abiertas hoy" sub="esperando autorización" />
      <Card><Tabla izq={5} head={['Placa', 'Rin', 'Taller', 'Aseguradora', 'Motivo', 'Desde', 'Días hábiles']}
        rows={abiertas.map((x) => { const d = servDiasEsperando(x.p); return [placaM(x.r.placa), 'Rin ' + (x.i + 1), x.r.taller + (x.r.sede ? ' · ' + x.r.sede : ''), x.r.aseguradora || '', x.motivo || '', x.p.desde || '', pill(String(d), d > 3 ? [TOKENS.dangerBg, TOKENS.dangerText] : d >= 2 ? ['#fdf0d5', '#8a5a00'] : [TOKENS.surfaceLow, TOKENS.textMuted])]; })} /></Card>
    </>;
  };

  const vistaOperacion = () => {
    const tt = [['Recoger placas', SOLS.map((p) => ({ h: p.estado === 'completada', u: p.prioridad === 'alta' }))]].concat(['recoger', 'entregar', 'hacer'].map((t) => [(window.ENC_TIPO && window.ENC_TIPO[t] ? window.ENC_TIPO[t][1] : t), ENC.filter((e) => e.tipo === t).map((e) => ({ h: e.estado === 'hecho', u: !!e.urgente }))]));
    const nSv = Object.values(codN).reduce((a, b) => a + b, 0);
    return <>
      <H2>Rutas</H2>
      <div style={grid(4)}>
        <Kpi t="Paradas hechas" v={fN(PAR.length)} sub={`en ${diasRuta} ${diasRuta === 1 ? 'día' : 'días'} con ruta`} />
        <Kpi t="Tiempo en sitio" v={minSitio == null ? '—' : minSitio + ' min'} sub="promedio por parada" />
        <Kpi t="Talleres visitados" v={fN(tiemposTaller.length)} sub={visitas.length ? `el que más: ${visitas[0][0]} (${visitas[0][1]})` : 'sin visitas'} />
        <Kpi t="Recogidas solicitadas" v={fN(SOLS.length)} sub={`desde la oficina · ${SOLS.filter((p) => p.estado === 'completada').length} hechas`} />
      </div>
      <H2 sub="Desde que el mensajero llega hasta que finaliza la parada.">Tiempo del mensajero por taller</H2>
      {tablaTiempos(100)}
      <H2>Tareas</H2>
      <Card><Tabla head={['Tipo', 'Creadas', 'Hechas', 'Pendientes', 'Con prioridad']} rows={tt.map(([l, L2]) => [l, L2.length, L2.filter((x) => x.h).length, L2.filter((x) => !x.h).length, L2.filter((x) => x.u).length || ''])}
        tots={[['Total', tHechas + tPend, tHechas, tPend, tt.reduce((a, [, L2]) => a + L2.filter((x) => x.u).length, 0) || '']]} /></Card>
      <H2>Servicios y suministros</H2>
      <div style={grid(4)}>
        <Kpi t="Facturable sin IVA" v={pcPesos(valorTotal)} sub="servicios de lo recogido" />
        <Kpi t="Servicios" v={fN(nSv)} sub={`${Object.entries(codN).map(([c, n]) => `${n} ${c}`).join(' · ') || 'sin servicios'}${nSold ? ` · ${nSold} con soldadura` : ''}`} />
        <Kpi t="Placas sin servicios" v={fN(nSinSv)} sub="recogidas sin servicio cargado" color={nSinSv ? '#7f6000' : undefined} />
        <Kpi t="Suministros" v={fN(SUM.length)} sub={SUM.length ? [sumTipo('llanta') && `${sumTipo('llanta')} llantas`, sumTipo('rin') && `${sumTipo('rin')} rines`, sumTipo('valvula') && `${sumTipo('valvula')} válvulas`].filter(Boolean).join(' · ') : 'ninguno en el periodo'} />
      </div>
    </>;
  };

  const TABS = [['res', 'Resumen', vistaResumen], ['rec', 'Recogidas', vistaRecogidas], ['ent', 'Entregas', vistaEntregas], ['ase', 'Aseguradoras', vistaAseg], ['tal', 'Talleres', vistaTalleres], ['nov', 'Novedades', vistaNovedades], ['ope', 'Operación', vistaOperacion]];
  const selI = { ...pcInp, padding: '9px 11px', fontSize: 13, maxWidth: cel ? '100%' : 240, flex: cel ? '1 1 140px' : undefined };
  const futuro = (p) => infPer(p, '9999-12-31').d > hoy;
  const sigFuturo = per.modo === 'ran' || futuro(infPaso(per, 1));
  const elegir = (p) => { setPer({ ...per, ...p }); setPop(null); };
  const abrirPer = () => { setPv({ modo: per.modo === 'ran' ? 'ran' : per.modo, y: per.y, m: per.m }); setRTmp({ d: desde, h: hasta }); setPop(pop === 'per' ? null : 'per'); };
  const btnS = (on) => ({ border: 0, borderRadius: 7, padding: '6px 8px', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 700, cursor: 'pointer', flex: 1, background: on ? TOKENS.surface : 'transparent', color: on ? TOKENS.primary : TOKENS.textMuted, boxShadow: on ? '0 1px 2px rgba(11,28,48,.12)' : 'none' });
  const flecha = (dis) => ({ border: 0, background: 'none', width: 38, fontSize: 18, fontWeight: 700, color: dis ? TOKENS.borderInput : TOKENS.primary, cursor: dis ? 'default' : 'pointer' });
  const navY = (txt, onL, onR, disR) => <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8, fontWeight: 800 }}><button type="button" onClick={onL} style={{ border: `1px solid ${TOKENS.border}`, background: TOKENS.surface, borderRadius: 8, width: 28, height: 28, cursor: 'pointer', color: TOKENS.primary, fontWeight: 700 }}>‹</button>{txt}<button type="button" disabled={disR} onClick={onR} style={{ border: `1px solid ${TOKENS.border}`, background: TOKENS.surface, borderRadius: 8, width: 28, height: 28, cursor: disR ? 'default' : 'pointer', color: disR ? TOKENS.borderInput : TOKENS.primary, fontWeight: 700 }}>›</button></div>;
  const itemL = (on, dis, onClick, txt, sub) => <button type="button" disabled={dis} onClick={onClick} style={{ display: 'block', width: '100%', textAlign: 'left', border: 0, borderRadius: 8, padding: '8px 10px', fontFamily: 'inherit', fontSize: 13, cursor: dis ? 'default' : 'pointer', background: on ? TOKENS.primaryBg : 'transparent', color: dis ? TOKENS.borderInput : on ? TOKENS.primary : TOKENS.text, fontWeight: on ? 700 : 400 }}>{txt}{sub && <span style={{ color: TOKENS.textMuted, fontWeight: 400, marginLeft: 6, fontSize: 12 }}>{sub}</span>}</button>;
  const popBox = { position: 'absolute', top: 'calc(100% + 6px)', left: 0, background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 14, boxShadow: '0 18px 40px rgba(11,28,48,.18)', padding: 12, zIndex: 30 };
  const sinDatosMes = (y, m) => !primero || infFinMes(y, m) < primero;
  const menuPer = () => {
    const ws = infSemDe(pv.y, pv.m);
    return <div style={{ ...popBox, width: 330 }} onClick={(e) => e.stopPropagation()}>
      <div style={{ display: 'flex', background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 10, padding: 3, gap: 2, marginBottom: 10 }}>{[['mes', 'Mes'], ['sem', 'Semana'], ['ano', 'Año'], ['ran', 'Rango']].map(([k, l]) => <button key={k} type="button" onClick={() => setPv({ ...pv, modo: k })} style={btnS(pv.modo === k)}>{l}</button>)}</div>
      {pv.modo === 'mes' && <>{navY(pv.y, () => setPv({ ...pv, y: pv.y - 1 }), () => setPv({ ...pv, y: pv.y + 1 }), pv.y >= yHoy)}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6 }}>{INF_MES.map((c, i) => { const fut = infIniMes(pv.y, i) > hoy; const on = per.modo === 'mes' && per.y === pv.y && per.m === i; const sin = sinDatosMes(pv.y, i);
          return <button key={i} type="button" disabled={fut} onClick={() => elegir({ modo: 'mes', y: pv.y, m: i })} title={sin ? 'Sin datos en la app' : ''} style={{ border: `1px solid ${on ? TOKENS.primary : TOKENS.border}`, background: on ? TOKENS.primary : TOKENS.surface, color: on ? '#fff' : fut ? TOKENS.borderInput : sin ? TOKENS.textSubtle : TOKENS.text, borderRadius: 9, padding: '9px 0', fontFamily: 'inherit', fontWeight: 600, fontSize: 13, cursor: fut ? 'default' : 'pointer' }}>{infCap(c)}</button>; })}</div>
        {primero && <div style={{ fontSize: 11.5, color: TOKENS.textMuted, marginTop: 8 }}>En gris: meses sin datos en la app (antes de {INF_MES[Number(primero.slice(5, 7)) - 1]} {primero.slice(0, 4)}).</div>}</>}
      {pv.modo === 'sem' && <>{navY(`${infCap(INF_MESL[pv.m])} ${pv.y}`, () => { const p2 = infPaso({ modo: 'mes', y: pv.y, m: pv.m }, -1); setPv({ ...pv, y: p2.y, m: p2.m }); }, () => { const p2 = infPaso({ modo: 'mes', y: pv.y, m: pv.m }, 1); setPv({ ...pv, y: p2.y, m: p2.m }); }, infIniMes(pv.y, pv.m) >= hoy.slice(0, 8) + '01')}
        <div>{ws.map((g, i) => itemL(per.modo === 'sem' && per.y === pv.y && per.m === pv.m && per.w === i, g.d > hoy, () => elegir({ modo: 'sem', y: pv.y, m: pv.m, w: i }), `Semana ${i + 1}`, `${Number(g.d.slice(8))}–${Number(g.h.slice(8))} ${INF_MES[pv.m]}${g.d <= hoy && g.h >= hoy ? ' · en curso' : ''}`))}</div></>}
      {pv.modo === 'ano' && <div>{[yHoy, yHoy - 1, yHoy - 2].map((y) => itemL(per.modo === 'ano' && per.y === y, false, () => elegir({ modo: 'ano', y }), String(y), y === yHoy ? 'en curso' : (!primero || `${y}-12-31` < primero) ? 'sin datos en la app' : ''))}</div>}
      {pv.modo === 'ran' && <div style={{ display: 'grid', gap: 8 }}>
        <label style={{ fontSize: 12, color: TOKENS.textMuted, fontWeight: 700 }}>Desde<input type="date" value={rTmp.d} max={hoy} onChange={(e) => e.target.value && setRTmp({ ...rTmp, d: e.target.value })} style={{ ...pcInp, width: '100%', marginTop: 4 }} /></label>
        <label style={{ fontSize: 12, color: TOKENS.textMuted, fontWeight: 700 }}>Hasta<input type="date" value={rTmp.h} max={hoy} onChange={(e) => e.target.value && setRTmp({ ...rTmp, h: e.target.value })} style={{ ...pcInp, width: '100%', marginTop: 4 }} /></label>
        <PcBtn tone="p" onClick={() => elegir({ modo: 'ran', rd: rTmp.d, rh: rTmp.h })}>Ver este rango</PcBtn></div>}
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 10, paddingTop: 10, borderTop: `1px solid ${TOKENS.border}` }}>
        {[['Este mes', { modo: 'mes', y: yHoy, m: mHoy }], ['Esta semana', infSemanaHoy(hoy)], ['Últimos 30 días', { modo: 'ran', rd: infMas(hoy, -29), rh: hoy }], ['Este año', { modo: 'ano', y: yHoy }]].map(([l, p]) => <button key={l} type="button" onClick={() => elegir(p)} style={{ border: `1px solid ${TOKENS.borderInput}`, background: TOKENS.surface, borderRadius: 99, padding: '4px 10px', fontFamily: 'inherit', fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>{l}</button>)}
      </div>
    </div>;
  };
  const menuCmp = () => <div style={{ ...popBox, width: 290 }} onClick={(e) => e.stopPropagation()}>
    {[['ant', per.modo === 'mes' ? 'El mes anterior' : per.modo === 'ano' ? 'El año anterior' : per.modo === 'sem' ? 'La semana anterior' : 'Los días anteriores'], ['ano', 'El mismo periodo del año pasado'], ['no', 'No comparar']].map(([k, l]) => <React.Fragment key={k}>{itemL(cmp === k, false, () => { setCmp(k); setPop(null); }, l)}</React.Fragment>)}
    <div style={{ fontSize: 11.5, color: TOKENS.textMuted, marginTop: 8, padding: '0 4px' }}>Si el periodo va en curso, se comparan los mismos días.</div>
  </div>;
  const sinCmp = C && (!primero || ch < primero);
  return (
    <>
      {pop && <div onClick={() => setPop(null)} style={{ position: 'fixed', inset: 0, zIndex: 7 }} />}
      <div style={cel ? { margin: '-14px -14px 14px', padding: '12px 14px 0', background: TOKENS.surface, borderBottom: `1px solid ${TOKENS.border}` } : { position: 'sticky', top: -18, zIndex: 8, margin: '-18px -24px 16px', padding: '12px 24px 0', background: TOKENS.surface, borderBottom: `1px solid ${TOKENS.border}` }}>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
          <div style={{ position: 'relative', display: 'inline-flex', alignItems: 'stretch', border: `1px solid ${TOKENS.borderInput}`, borderRadius: 12, background: TOKENS.surface }}>
            <button type="button" title="Periodo anterior" disabled={per.modo === 'ran'} onClick={() => setPer(infPaso(per, -1))} style={flecha(per.modo === 'ran')}>‹</button>
            <button type="button" onClick={abrirPer} style={{ border: 0, borderLeft: `1px solid ${TOKENS.border}`, borderRight: `1px solid ${TOKENS.border}`, background: 'none', padding: '7px 16px', fontFamily: 'inherit', cursor: 'pointer', textAlign: 'left', minWidth: cel ? 170 : 220 }}>
              <b style={{ display: 'block', fontSize: 15, color: TOKENS.text }}>{P.t}</b><span style={{ fontSize: 11.5, color: TOKENS.textMuted }}>{P.s} ▾</span></button>
            <button type="button" title="Periodo siguiente" disabled={sigFuturo} onClick={() => setPer(infPaso(per, 1))} style={flecha(sigFuturo)}>›</button>
            {pop === 'per' && menuPer()}
          </div>
          <div style={{ position: 'relative' }}>
            <button type="button" onClick={() => setPop(pop === 'cmp' ? null : 'cmp')} style={{ border: `1px solid ${TOKENS.border}`, background: TOKENS.surfaceLow, borderRadius: 12, padding: '7px 14px', fontFamily: 'inherit', cursor: 'pointer', textAlign: 'left' }}>
              <b style={{ display: 'block', fontSize: 13.5, color: TOKENS.text }}>{C ? C.t : 'Sin comparar'}</b><span style={{ fontSize: 11.5, color: TOKENS.textMuted }}>{C ? (sinCmp ? 'sin datos en la app' : C.s) : 'solo el periodo elegido'} ▾</span></button>
            {pop === 'cmp' && menuCmp()}
          </div>
          <select value={fa} onChange={(e) => setFa(e.target.value)} style={selI}><option value="">Todas las aseguradoras</option>{asegOpc.map((a) => <option key={a} value={a}>{a}</option>)}</select>
          <select value={ft} onChange={(e) => setFt(e.target.value)} style={selI}><option value="">Todos los talleres</option>{tallerOpc.map((a) => <option key={a} value={a}>{a}</option>)}</select>
          <PcBtn tone="p" style={{ marginLeft: cel ? 0 : 'auto', width: cel ? '100%' : undefined }} disabled={!L.length && !A.E.length} onClick={descargar}>⇩ Descargar Excel</PcBtn>
        </div>
        <div style={{ display: 'flex', gap: 2, marginTop: 10, overflowX: 'auto', whiteSpace: 'nowrap' }}>{TABS.map(([k, l]) => <button key={k} type="button" onClick={() => setTab(k)} style={{ border: 0, background: 'none', padding: '10px 14px', fontFamily: 'inherit', fontWeight: 700, fontSize: 13.5, color: tab === k ? TOKENS.primary : TOKENS.textMuted, cursor: 'pointer', borderBottom: `2.5px solid ${tab === k ? TOKENS.primary : 'transparent'}` }}>{l}</button>)}</div>
      </div>
      {sinDatos && tab !== 'ope' ?
      <div style={{ ...pcCard, padding: 40, textAlign: 'center', color: TOKENS.textMuted, fontSize: 13.5 }}><b style={{ color: TOKENS.text }}>Sin datos en este periodo.</b><br />La app tiene registros desde {primero ? 'el ' + infTxtF(primero, true) : 'que se empezó a usar'}. Los años anteriores llegan cuando se importe el histórico de mensajería.</div> :
      TABS.find((t) => t[0] === tab)[2]()}
    </>);
}

// ─── Usuarios ────────────────────────────────────────────────────────────
function PcUsuarios({ toast }) {
  const cel = usePcCel();
  const [list, setList] = React.useState(() => window.loadUsuarios ? window.loadUsuarios() : []);
  const [form, setForm] = React.useState(null); // {modo:'nuevo'|'editar'|'pin', ...}
  const [conf, setConf] = React.useState(null);
  const yo = (window.usuarioActual && window.usuarioActual()) || {};
  const guardarLista = (l, msg, rojo) => { window.saveUsuarios(l); setList(l); toast(msg, rojo); };
  const Modal = window.ConfirmActionModal;
  const inp = { ...pcInp, width: '100%' };
  const th = { ...pcLbl, textAlign: 'left', padding: '9px 12px', background: TOKENS.surfaceLow, borderBottom: `1px solid ${TOKENS.border}` };
  const td = { padding: '11px 12px', borderBottom: `1px solid ${TOKENS.border}` };
  const valido = form && (form.modo === 'pin' ? /^\d{4,6}$/.test(form.pin || '') : form.nombre && form.nombre.trim() && (form.modo === 'editar' || (/^[a-z0-9._-]{3,}$/.test(form.usuario || '') && !list.some((u) => u.usuario === form.usuario) && /^\d{4,6}$/.test(form.pin || ''))));
  return (
    <>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12, flexWrap: cel ? 'wrap' : 'nowrap' }}>
        <span style={{ flex: 1, fontSize: 13, color: TOKENS.textMuted, minWidth: 220 }}>Cada persona entra con su usuario y PIN. El rol decide qué ve: el mensajero, sus recogidas y su ruta; el administrador, todo.</span>
        <PcBtn tone="p" onClick={() => setForm({ modo: 'nuevo', nombre: '', usuario: '', rol: 'mensajero', pin: '' })}>＋ Agregar usuario</PcBtn>
      </div>
      {cel ? <div style={{ display: 'grid', gap: 8 }}>{list.map((u) => <div key={u.usuario} style={{ ...pcCard, padding: '12px 13px', opacity: u.activo === false ? 0.6 : 1 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><b style={{ flex: 1, fontSize: 14.5 }}>{u.nombre}{u.usuario === yo.usuario && <span style={{ fontSize: 11.5, color: TOKENS.textMuted, fontWeight: 400 }}> · tú</span>}</b>{u.activo === false ? <PcChip bg={TOKENS.surfaceLow} fg={TOKENS.textMuted}>Inactivo</PcChip> : <PcChip bg={TOKENS.primaryBg} fg={TOKENS.primary}>Activo</PcChip>}</div>
          <div style={{ fontSize: 12.5, color: TOKENS.textMuted, marginTop: 3 }}><span style={{ fontFamily: pcMono }}>{u.usuario}</span> · {u.rol === 'admin' ? 'Administrador' : 'Mensajero'}</div>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 10 }}>
            <PcBtn style={{ padding: '6px 10px', fontSize: 12 }} onClick={() => setForm({ modo: 'editar', usuario: u.usuario, nombre: u.nombre, rol: u.rol })}>Editar</PcBtn>
            <PcBtn style={{ padding: '6px 10px', fontSize: 12 }} onClick={() => setForm({ modo: 'pin', usuario: u.usuario, nombre: u.nombre, pin: '' })}>Cambiar PIN</PcBtn>
            {u.usuario !== yo.usuario && (u.activo === false ?
            <PcBtn tone="p" style={{ padding: '6px 10px', fontSize: 12 }} onClick={() => setConf({ tone: 'primary', t: 'Reactivar usuario', m: `${u.nombre} vuelve a poder entrar a la app.`, ok: 'Reactivar', fn: () => guardarLista(list.map((x) => x.usuario === u.usuario ? { ...x, activo: true } : x), 'Usuario reactivado') })}>Reactivar</PcBtn> :
            <PcBtn tone="r" style={{ padding: '6px 10px', fontSize: 12 }} onClick={() => setConf({ tone: 'danger', t: 'Desactivar usuario', m: `${u.nombre} ya no podrá entrar a la app. Sus registros se conservan.`, ok: 'Desactivar', fn: () => guardarLista(list.map((x) => x.usuario === u.usuario ? { ...x, activo: false } : x), 'Usuario desactivado', true) })}>Desactivar</PcBtn>)}
          </div>
        </div>)}</div> :
      <div style={{ ...pcCard, overflow: 'hidden' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13.5 }}>
          <thead><tr><th style={th}>Nombre</th><th style={th}>Usuario</th><th style={th}>Rol</th><th style={th}>Estado</th><th style={th}></th></tr></thead>
          <tbody>{list.map((u) =>
            <tr key={u.usuario} style={{ opacity: u.activo === false ? 0.6 : 1 }}>
                <td style={td}><b>{u.nombre}</b>{u.usuario === yo.usuario && <span style={{ fontSize: 11.5, color: TOKENS.textMuted }}> · tú</span>}</td>
                <td style={{ ...td, fontFamily: pcMono }}>{u.usuario}</td>
                <td style={td}>{u.rol === 'admin' ? 'Administrador' : 'Mensajero'}</td>
                <td style={td}>{u.activo === false ? <PcChip bg={TOKENS.surfaceLow} fg={TOKENS.textMuted}>Inactivo</PcChip> : <PcChip bg={TOKENS.primaryBg} fg={TOKENS.primary}>Activo</PcChip>}</td>
                <td style={{ ...td, textAlign: 'right', whiteSpace: 'nowrap' }}>
                  <PcBtn style={{ padding: '5px 10px', fontSize: 12 }} onClick={() => setForm({ modo: 'editar', usuario: u.usuario, nombre: u.nombre, rol: u.rol })}>Editar</PcBtn>{' '}
                  <PcBtn style={{ padding: '5px 10px', fontSize: 12 }} onClick={() => setForm({ modo: 'pin', usuario: u.usuario, nombre: u.nombre, pin: '' })}>Cambiar PIN</PcBtn>{' '}
                  {u.usuario !== yo.usuario && (u.activo === false ?
                  <PcBtn tone="p" style={{ padding: '5px 10px', fontSize: 12 }} onClick={() => setConf({ tone: 'primary', t: 'Reactivar usuario', m: `${u.nombre} vuelve a poder entrar a la app.`, ok: 'Reactivar', fn: () => guardarLista(list.map((x) => x.usuario === u.usuario ? { ...x, activo: true } : x), 'Usuario reactivado') })}>Reactivar</PcBtn> :
                  <PcBtn tone="r" style={{ padding: '5px 10px', fontSize: 12 }} onClick={() => setConf({ tone: 'danger', t: 'Desactivar usuario', m: `${u.nombre} ya no podrá entrar a la app. Sus registros se conservan.`, ok: 'Desactivar', fn: () => guardarLista(list.map((x) => x.usuario === u.usuario ? { ...x, activo: false } : x), 'Usuario desactivado', true) })}>Desactivar</PcBtn>)}
                </td>
              </tr>)}</tbody>
        </table>
      </div>}
      {form &&
      <div onClick={() => setForm(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(11,28,48,0.5)', zIndex: 1000, display: 'grid', placeItems: 'center' }}>
          <div onClick={(e) => e.stopPropagation()} style={{ background: TOKENS.surface, borderRadius: 16, padding: 20, width: 380, display: 'grid', gap: 12 }}>
            <b style={{ fontSize: 17 }}>{form.modo === 'nuevo' ? 'Agregar usuario' : form.modo === 'editar' ? 'Editar usuario' : `Cambiar PIN de ${form.nombre}`}</b>
            {form.modo !== 'pin' && <PcCampo label="Nombre"><input autoFocus value={form.nombre} onChange={(e) => setForm({ ...form, nombre: e.target.value })} style={inp} /></PcCampo>}
            {form.modo === 'nuevo' && <PcCampo label="Usuario" nota="Con este nombre entra a la app (minúsculas, sin espacios)."><input value={form.usuario} onChange={(e) => setForm({ ...form, usuario: e.target.value.toLowerCase().replace(/\s/g, '') })} style={{ ...inp, fontFamily: pcMono }} /></PcCampo>}
            {form.modo !== 'pin' && <PcCampo label="Rol"><PcPills value={form.rol} onChange={(v) => setForm({ ...form, rol: v })} options={[['mensajero', 'Mensajero'], ['admin', 'Administrador']]} /></PcCampo>}
            {form.modo !== 'editar' && <PcCampo label="PIN" nota="De 4 a 6 números. Entrégaselo a la persona."><input value={form.pin} inputMode="numeric" maxLength={6} onChange={(e) => setForm({ ...form, pin: e.target.value.replace(/\D/g, '') })} style={{ ...inp, fontFamily: pcMono, letterSpacing: '0.2em' }} /></PcCampo>}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 4 }}>
              <PcBtn onClick={() => setForm(null)}>Cancelar</PcBtn>
              <PcBtn tone="p" disabled={!valido} onClick={() => { const fm = form; setForm(null); setConf({ tone: 'primary', t: fm.modo === 'pin' ? 'Cambiar PIN' : 'Guardar usuario', m: fm.modo === 'pin' ? `${fm.nombre} entrará con el PIN nuevo.` : `${fm.nombre.trim()} · ${fm.rol === 'admin' ? 'Administrador' : 'Mensajero'}`, ok: 'Guardar', fn: () => {
                    if (fm.modo === 'nuevo') guardarLista([...list, { usuario: fm.usuario, nombre: fm.nombre.trim(), rol: fm.rol, pin: fm.pin, activo: true }], 'Usuario agregado');
                    else if (fm.modo === 'editar') guardarLista(list.map((x) => x.usuario === fm.usuario ? { ...x, nombre: fm.nombre.trim(), rol: fm.rol } : x), 'Cambios guardados');
                    else guardarLista(list.map((x) => x.usuario === fm.usuario ? { ...x, pin: fm.pin } : x), 'PIN cambiado');
                  } }); }}>Guardar</PcBtn>
            </div>
          </div>
        </div>}
      {conf && Modal && <Modal tone={conf.tone} icon={conf.tone === 'danger' ? I.alert(24, TOKENS.danger) : I.check(24, TOKENS.primary)} title={conf.t} message={conf.m} confirmLabel={conf.ok} onDismiss={() => setConf(null)} onConfirm={() => { const fn = conf.fn; setConf(null); fn(); }} />}
    </>);
}

// ─── Barra de arriba: encargos para el mensajero (23/11/2026, antes "notas") + notificaciones ───
function PcNotas({ toast, onClose }) {
  const L = window.useEncargos ? window.useEncargos() : [];
  const [nuevo, setNuevo] = React.useState(false);
  const pend = L.filter((e) => e.estado !== 'hecho').sort((a, b) => (b.urgente ? 1 : 0) - (a.urgente ? 1 : 0) || String(a.fechaIso || '9').localeCompare(String(b.fechaIso || '9')));
  const verTodos = () => { (window.PC_MEMO = window.PC_MEMO || {}).rutasTab = 'enc'; onClose && onClose(); window.dispatchEvent(new CustomEvent('pc-ir', { detail: 'rutas' })); };
  return (
    <div style={{ position: 'absolute', top: 58, right: 64, width: 400, maxHeight: 540, overflow: 'auto', ...pcCard, boxShadow: '0 18px 40px rgba(11,28,48,.18)', zIndex: 800, padding: 14 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}><b style={{ flex: 1, fontSize: 15 }}>Tareas pendientes</b><PcBtn tone="p" style={{ padding: '7px 12px', fontSize: 12.5 }} onClick={() => setNuevo(true)}>＋ Nueva tarea</PcBtn></div>
      {!pend.length && <div style={{ fontSize: 12.5, color: TOKENS.textMuted, padding: '10px 0' }}>No hay encargos pendientes.</div>}
      {pend.slice(0, 8).map((e) => <div key={e.id} style={{ display: 'flex', gap: 10, padding: '9px 0', borderTop: `1px solid ${TOKENS.border}`, fontSize: 13 }}>
        <span style={{ width: 74, flexShrink: 0, fontWeight: 700 }}>{window.ENC_TIPO[e.tipo][0]} {window.ENC_TIPO[e.tipo][1]}</span>
        <div style={{ flex: 1, minWidth: 0 }}>{e.que}{e.placa && <span style={{ fontFamily: pcMono, fontWeight: 700, fontSize: 11.5, marginLeft: 6 }}>{e.placa}</span>}
          <span style={{ display: 'block', fontSize: 11.5, color: TOKENS.textMuted, marginTop: 2 }}>{[window.encDonde(e), window.encParaTxt(e), e.urgente && '↑ Prioridad'].filter(Boolean).join(' · ')}</span></div>
      </div>)}
      <button type="button" onClick={verTodos} style={{ width: '100%', marginTop: 6, padding: 9, border: 0, borderTop: `1px solid ${TOKENS.border}`, background: 'transparent', color: TOKENS.primary, fontFamily: 'inherit', fontSize: 12.5, fontWeight: 700, cursor: 'pointer' }}>Ver todas en Rutas › Tareas</button>
      {nuevo && <PcAsignarEncargo onClose={() => setNuevo(false)} onGuardado={(e, r) => { setNuevo(false); toast(e ? `Tarea creada · ${e.que}` : `Suministro agregado · ${r.placa}`, 'g'); }} />}
    </div>);
}
function pcAvisosAdmin() {
  const ns = (window.notifsFor ? window.notifsFor('admin') : []).filter((n) => n.estado === 'pendiente');
  const nom = (u) => (window.nombreDeUsuario && window.nombreDeUsuario(u)) || 'El mensajero';
  const out = ns.map((n) => {
    if (n.tipo === 'anulacion') return { id: n.id, ic: I.ban(15, TOKENS.anulado), bg: TOKENS.anuladoBg, t: n.titulo || 'Solicitud de anulación', m: n.mensaje || `${n.taller || ''}`, ts: n.createdAt, ir: 'notificaciones' };
    if (n.tipo === 'autoasignacion') return { id: n.id, ic: I.route(15, TOKENS.textMuted), bg: TOKENS.surfaceLow, t: `${nom(n.actor)} agregó una parada`, m: `${n.taller || ''}${n.sede ? ' · ' + n.sede : ''}`, ts: n.createdAt, ir: 'rutas' };
    if (n.tipo === 'rechazo') return { id: n.id, ic: I.x(15, TOKENS.textMuted), bg: TOKENS.surfaceLow, t: `Ruta rechazada · ${n.taller || ''}`, m: n.motivo || '', ts: n.createdAt, ir: 'rutas' };
    return { id: n.id, ic: I.bell(15, TOKENS.textMuted), bg: TOKENS.surfaceLow, t: n.titulo || 'Aviso', m: n.mensaje || `${n.taller || ''}`, ts: n.createdAt, ir: 'notificaciones' };
  });
  const tns = window.catPendientesMensajero ? window.catPendientesMensajero() : [];
  if (tns.length) out.unshift({ id: 'tal', ic: I.building(15, '#7f6000'), bg: '#fff2cc', t: `${tns.length} ${tns.length === 1 ? 'taller nuevo por revisar' : 'talleres nuevos por revisar'}`, m: tns.slice(0, 2).map((x) => x.taller).join(', '), ts: tns[0].createdAt, ir: 'catalogos-revisar' });
  return out;
}
function PcAvisos({ ir, onClose }) {
  const av = pcAvisosAdmin();
  return (
    <div style={{ position: 'absolute', top: 58, right: 18, width: 390, maxHeight: 520, overflow: 'auto', ...pcCard, boxShadow: '0 18px 40px rgba(11,28,48,.18)', zIndex: 800, padding: 14 }}>
      <div style={{ display: 'flex', alignItems: 'center', marginBottom: 6 }}><b style={{ flex: 1, fontSize: 15 }}>Notificaciones</b><PcBtn style={{ padding: '4px 9px', fontSize: 12 }} onClick={() => { onClose(); ir('notificaciones'); }}>Ver todas</PcBtn></div>
      {!av.length && <div style={{ fontSize: 13, color: TOKENS.textMuted, padding: '12px 0' }}>Nada pendiente.</div>}
      {av.map((a) =>
      <button key={a.id} type="button" onClick={() => { onClose(); ir(a.ir); }} style={{ display: 'flex', gap: 10, alignItems: 'flex-start', width: '100%', textAlign: 'left', border: 0, borderTop: `1px solid ${TOKENS.border}`, background: 'none', padding: '10px 0', fontFamily: 'inherit', cursor: 'pointer', color: TOKENS.text }}>
          <span style={{ width: 30, height: 30, borderRadius: 9, display: 'grid', placeItems: 'center', background: a.bg, flexShrink: 0 }}>{a.ic}</span>
          <span style={{ flex: 1, minWidth: 0 }}><b style={{ fontSize: 13 }}>{a.t}</b><span style={{ display: 'block', fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>{a.m}</span>{a.ts && window.relTime && <span style={{ display: 'block', fontSize: 11.5, color: TOKENS.textSubtle, marginTop: 2 }}>{window.relTime(a.ts)}</span>}</span>
          <span style={{ fontSize: 12.5, fontWeight: 800, color: TOKENS.primary }}>Ver ›</span>
        </button>)}
    </div>);
}


// ─── Rutas en el PC (13/11/2026): dos columnas · izquierda lo que se trabaja, derecha el mapa ──
const pcHora = (ts) => ts ? new Date(ts).toLocaleTimeString('es-CO', { hour: 'numeric', minute: '2-digit' }) : '—';
const pcDur = (ms) => { if (!ms || ms < 0) return '—'; const m = Math.round(ms / 60000); return m < 60 ? `${m} min` : `${Math.floor(m / 60)} h ${String(m % 60).padStart(2, '0')} min`; };
// 27/11/2026: las secciones del PC se pueden ver en el celular (solo admin). PcCelCtx = true → diseño de una columna.
const PcCelCtx = React.createContext(false);
const usePcCel = () => React.useContext(PcCelCtx);
function pcDosColumnas(izqAncho, cabeza, izq, der, fondoIzq, fondoDer) {
  return <PcDosCol izqAncho={izqAncho} cabeza={cabeza} izq={izq} der={der} fondoIzq={fondoIzq} fondoDer={fondoDer} />;
}
function PcDosCol({ izqAncho, cabeza, izq, der, fondoIzq, fondoDer }) {
  const cel = usePcCel();
  const [verDer, setVerDer] = React.useState(false);
  if (cel) {
    // Celular: la lista ocupa la pantalla; al tocar un elemento de la lista, el detalle se abre encima con "‹ Volver".
    const abrir = (e) => { if (e.target.closest('button, input, select, textarea, a, label')) return; const d = e.target.closest('div'); let x = d; while (x && x !== e.currentTarget) { if (getComputedStyle(x).cursor === 'pointer') { setTimeout(() => setVerDer(true), 0); return; } x = x.parentElement; } };
    return <div>
      <div style={{ paddingBottom: 10 }}>{cabeza}</div>
      <div onClickCapture={abrir} style={{ background: fondoIzq || 'transparent' }}>{izq}</div>
      {verDer && <div style={{ position: 'fixed', top: 0, bottom: 0, ...PC_CEL_FIJO, zIndex: 60, background: fondoDer || TOKENS.bg, display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: '12px 14px', borderBottom: `1px solid ${TOKENS.border}`, background: TOKENS.surface }}><button type="button" onClick={() => setVerDer(false)} style={{ border: 0, background: 'none', color: TOKENS.primary, fontFamily: 'inherit', fontSize: 14, fontWeight: 700, cursor: 'pointer', padding: 0 }}>‹ Volver a la lista</button></div>
        <div style={{ flex: 1, overflow: 'auto', padding: '14px 14px 30px' }}>{der}</div>
      </div>}
    </div>;
  }
  return (
    <div style={{ display: 'grid', gridTemplateColumns: `${izqAncho}px 1fr`, height: '100%', minHeight: 0, margin: '-18px -24px -28px' }}>
      <div style={{ borderRight: `1px solid ${TOKENS.border}`, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
        <div style={{ padding: '14px 16px 10px', borderBottom: `1px solid ${TOKENS.border}` }}>{cabeza}</div>
        <div style={{ flex: 1, overflow: 'auto', padding: '12px 16px 16px', position: 'relative', background: fondoIzq || 'transparent' }}>{izq}</div>
      </div>
      <div style={{ minHeight: 0, overflow: 'auto', padding: '16px 20px', background: fondoDer || 'transparent' }}>{der}</div>
    </div>);
}
function PcTabs({ value, options, onChange }) {
  return (
    <div style={{ display: 'grid', gridAutoFlow: 'column', gridAutoColumns: '1fr', gap: 3, background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 11, padding: 3 }}>
      {options.map(([v, l, n]) => { const on = value === v; return <button key={v} type="button" onClick={() => onChange(v)} style={{ border: 0, borderRadius: 8, padding: '8px 6px', fontFamily: 'inherit', fontSize: 13, fontWeight: 700, whiteSpace: 'nowrap', cursor: 'pointer', background: on ? TOKENS.primary : 'transparent', color: on ? '#fff' : TOKENS.textMuted }}>{l}{n != null && <span style={{ display: 'inline-block', minWidth: 18, borderRadius: 99, fontSize: 11, padding: '0 5px', marginLeft: 5, background: on ? 'rgba(255,255,255,.25)' : TOKENS.border }}>{n}</span>}</button>; })}
    </div>);
}
const pcItemCard = (sel, hov, extra = {}) => { const { borderColor, ...rest } = extra; return { display: 'flex', gap: 10, alignItems: 'flex-start', padding: '11px 12px', border: `1px solid ${borderColor || (sel ? TOKENS.primary : hov ? '#9fb3d6' : TOKENS.border)}`, borderRadius: 12, background: sel ? TOKENS.primaryBg : TOKENS.surface, marginBottom: 8, cursor: 'pointer', ...rest }; };
const pcNum = (st, txt) => <span style={{ width: 24, height: 24, borderRadius: 99, display: 'grid', placeItems: 'center', fontSize: 11.5, fontWeight: 800, flexShrink: 0, background: st === 'done' ? TOKENS.primary : st === 'cur' ? '#fff' : TOKENS.surfaceLow, color: st === 'done' ? '#fff' : st === 'cur' ? TOKENS.cautionText : TOKENS.textMuted, border: `1px solid ${st === 'done' ? TOKENS.primary : st === 'cur' ? TOKENS.caution : TOKENS.border}` }}>{txt}</span>;
// 23/11/2026: tipo de parada como chip (mismos íconos del celular).
const pcTipoChip = (t) => <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11.5, fontWeight: 700, borderRadius: 999, padding: '3px 9px', background: TOKENS.surfaceLow, color: TOKENS.textMuted, border: `1px solid ${TOKENS.border}`, whiteSpace: 'nowrap' }}>{t === 'recoger' ? I.recoger(13, TOKENS.textMuted) : t === 'entregar' ? I.truck(13, TOKENS.textMuted) : <span>✓</span>}{t === 'recoger' ? 'Recoger' : t === 'entregar' ? 'Entregar' : 'Encargo'}</span>;
// 25/11/2026: entrega en una ciudad donde el mensajero no recoge: César la lleva a la transportadora.
const pcChipTransp = <span title="César deja los rines en la transportadora y registra la guía" style={{ fontSize: 11.5, fontWeight: 700, borderRadius: 999, padding: '3px 9px', background: '#fdf0d5', color: '#8a5a00', border: '1px solid #f0d9a8', whiteSpace: 'nowrap' }}>Por transportadora</span>;
const pcTag = (t) => <span style={{ fontSize: 11, fontWeight: 500, borderRadius: 999, padding: '2px 8px', background: TOKENS.surfaceLow, color: TOKENS.textMuted, border: `1px solid ${TOKENS.border}`, whiteSpace: 'nowrap' }}>{t}</span>;

function PcRutas({ toast }) {
  const ms = window.mensajerosApp ? window.mensajerosApp() : [];
  const [courier, setCourier] = React.useState((ms[0] || {}).usuario || (typeof mensajeroPorDefecto === 'function' ? mensajeroPorDefecto() : 'cesar'));
  const PM = window.PC_MEMO = window.PC_MEMO || {};
  const [tab, setTabSt] = React.useState(PM.rutasTab || 'hoy');
  const setTab = (v) => { PM.rutasTab = v; setTabSt(v); };
  const [hov, setHov] = React.useState(null);
  const [sel, setSel] = React.useState(() => new Set());
  const [histDia, setHistDia] = React.useState(null);
  const [conf, setConf] = React.useState(null);
  const [nueva, setNueva] = React.useState(false);
  const [drag, setDrag] = React.useState(null);
  const [vista, setVistaSt] = React.useState(() => { try { return localStorage.getItem('rodando.planearVista') || 'taller'; } catch (e) { return 'taller'; } });
  const setVista = (v) => { setVistaSt(v); try { localStorage.setItem('rodando.planearVista', v); } catch (e) {} };
  const [verDet, setVerDet] = React.useState(null);
  const [verSol, setVerSol] = React.useState(null);
  const [nuevoEnc, setNuevoEnc] = React.useState(false);
  React.useEffect(() => { const f = (e) => { if (e.detail === 'sol' || e.detail === 'enc') setNuevoEnc(true); }; window.addEventListener('pc-rutas', f); return () => window.removeEventListener('pc-rutas', f); }, []);
  // 23/11/2026: buscador y chips de estado en Por planear (se recuerdan mientras la app está abierta).
  const [qPlan, setQPlanSt] = React.useState(PM.rutasQ || '');
  const setQPlan = (v) => { PM.rutasQ = v; setQPlanSt(v); };
  const [estPlan, setEstPlanSt] = React.useState(PM.rutasEst || 'todas');
  const [subPlan, setSubPlanSt] = React.useState(PM.rutasSub || 'ent');
  const setSubPlan = (v) => { PM.rutasSub = v; setSubPlanSt(v); setHov(null); };
  const [recPrio, setRecPrio] = React.useState(false);
  const [encUrg, setEncUrg] = React.useState(false);
  const setEstPlan = (v) => { PM.rutasEst = v; setEstPlanSt(v); };
  const [alto, setAlto] = React.useState(() => window.innerHeight - 120);
  React.useEffect(() => { const f = () => setAlto(window.innerHeight - 120); window.addEventListener('resize', f); return () => window.removeEventListener('resize', f); }, []);
  React.useEffect(() => { try { window.seedDemoParadasIfEmpty && window.seedDemoParadasIfEmpty(); window.rolloverParadasIfNeeded && window.rolloverParadasIfNeeded(); } catch (e) {} }, []);
  const nombre = (ms.find((m) => m.usuario === courier) || {}).nombre || 'el mensajero';
  const hoy = fechaDDMMYYYY();
  const paradas = window.loadParadas ? window.loadParadas() : [];
  const nEnc = (window.loadEncargos ? window.loadEncargos().filter((e) => e.estado !== 'hecho').length : 0) + paradas.filter((p) => p.tipo === 'recoger' && p.creadaPor === 'admin' && ['solicitud', 'pendiente', 'en_curso'].includes(p.estado)).length;
  const mine = paradas.filter((p) => p.fecha === hoy && p.asignadoA === courier);
  const Modal = window.ConfirmActionModal;
  const Map = typeof MapView !== 'undefined' ? MapView : null;
  const avisar = (titulo, mensaje, extra = {}) => {
    if (!window.addNotif) return;
    const base = { id: 'n-' + Date.now() + '-' + Math.random().toString(36).slice(2, 6), tipo: 'ruta_update', para: 'mensajero', paraUsuario: courier, estado: 'pendiente', titulo, mensaje, actor: 'admin', createdAt: Date.now(), resolucion: null, ...extra };
    if (window.addOrCoalesceNotif) window.addOrCoalesceNotif(base, 'ruta_update:mensajero:' + courier);else window.addNotif(base);
  };
  // Ruta de hoy
  const destinos = (window.groupByDestino ? window.groupByDestino(mine.filter((p) => ['pendiente', 'en_curso', 'completada'].includes(p.estado))) : []);
  const completados = destinos.filter((d) => d.estado === 'completada').sort((a, b) => (a.completadaEn || 0) - (b.completadaEn || 0));
  const activos = destinos.filter((d) => d.estado !== 'completada').sort((a, b) => (a.estado === 'en_curso' ? -1 : b.estado === 'en_curso' ? 1 : a.orden - b.orden));
  const ordenRuta = [...completados, ...activos];
  const inicio = Math.min(...destinos.map((d) => d.iniciadaEn || Infinity));
  const tareasTxt = (d) => d.tareas.map((t) => t.tipo === 'recoger' ? `Recoger${(t.placas || []).length ? ' · ' + t.placas.join(', ') : ''}` : t.tipo === 'entregar' ? `Entregar · ${(t.consecutivos || []).map((c) => { const tk = [...(window.loadPendientesSaved ? window.loadPendientesSaved() : []), ...(window.PENDIENTES_DEMO || [])].find((x) => String(x.codigo) === String(c)); return tk ? `${tk.placa} (${c})` : c; }).concat((t.garantias || []).map((g) => `${g.placa} (↺ ${g.codigo})`)).join(', ')}` : (t.referencia || 'Otro')).join(' · ');
  const reordenar = (fromKey, toKey) => {
    const pend = activos.filter((d) => d.estado === 'pendiente').map((d) => d.key);
    const i = pend.indexOf(fromKey), j = pend.indexOf(toKey);
    if (i < 0 || j < 0 || i === j) return;
    pend.splice(j, 0, pend.splice(i, 1)[0]);
    const base = activos.some((d) => d.estado === 'en_curso') ? 1 : 0;
    pend.forEach((k, n) => { const d = destinos.find((x) => x.key === k); d.tareas.forEach((t) => window.updateParada(t.id, { orden: base + n })); });
    const d = destinos.find((x) => x.key === fromKey);
    avisar('El admin reordenó tu ruta', `Cambió el orden de las paradas de hoy de ${nombre}.`, { kind: 'reorder', detalle: `${d.taller} → posición ${pend.indexOf(fromKey) + 1 + base}` });
    pcAvisar(); toast('Orden actualizado');
  };
  // Por planear
  const recogidas = mine.filter((p) => p.estado === 'solicitud');
  const enRuta = new Set(); mine.filter((p) => p.tipo === 'entregar' && p.estado !== 'cancelada').forEach((p) => (p.consecutivos || []).forEach((c) => enRuta.add(String(c))));
  const entregados = new Set((window.loadEntregados ? window.loadEntregados() : []).map((e) => e.ticketId));
  const anuMap = window.loadAnulacionMap ? window.loadAnulacionMap() : new Map();
  const listas = [...(window.loadPendientesSaved ? window.loadPendientesSaved() : []), ...(window.PENDIENTES_DEMO || [])]
  .filter((t) => !entregados.has(t.id) && !enRuta.has(String(t.codigo)) && !((anuMap.get(t.id) || {}).estadoActual === 'anulado') && !(window.anulacionEnEspera && window.anulacionEnEspera(t.id)));
  // Garantías por entregar (19/11/2026, igual que el celular): salen mientras estén en una parada pendiente o en curso.
  const enRutaGar = new Set(); mine.filter((p) => (p.estado === 'pendiente' || p.estado === 'en_curso') && p.garantias).forEach((p) => p.garantias.forEach((g) => enRutaGar.add(g.garId)));
  const garsB = []; (window.loadEntregados ? window.loadEntregados() : []).forEach((e) => { const g = window.garantiaAbierta ? window.garantiaAbierta(e.ticketId) : null; if (g && !enRutaGar.has(g.id)) garsB.push({ e, g, est: window.garEstado(g) }); });
  // Cada placa (orden o garantía) con su urgencia. Express solo desempata.
  const estT = (t) => window.estadoProcesos ? window.estadoProcesos(t) : { orden: 3, dias: 0 };
  const itemsPlan = [
  ...listas.map((t) => { const e = estT(t); return { k: 'ent:' + t.codigo, t, tk: t, taller: t.taller, sede: t.cliente ? t.cliente.nombre : t.sede, o: e.orden, d: e.dias, x: !!t.express, e }; }),
  ...garsB.map((x) => { const tk = { ...x.e, id: x.e.ticketId, fecha: x.e.fechaRecogido, items: [{ tipo: 'rin', cantidad: (x.g.rines || []).length }] }; return { k: 'gar:' + x.g.id, gar: x, tk, taller: x.e.taller, sede: x.e.sede, o: x.est.orden, d: x.est.dias, x: !!x.e.express, e: x.est }; })].
  sort((a, b) => a.o - b.o || b.d - a.d || (b.x ? 1 : 0) - (a.x ? 1 : 0));
  const kqP = qPlan.trim().toLowerCase();
  const coincideP = (txt) => !kqP || String(txt || '').toLowerCase().includes(kqP);
  const itemQ = (it) => coincideP(`${it.tk.placa} ${it.tk.codigo} ${it.taller} ${it.sede || ''}`);
  const itemEst = (it) => estPlan === 'todas' || (estPlan === 'x' ? it.x : !it.gar && !it.e.pausa && String(it.e.orden) === estPlan);
  const itemsQ = itemsPlan.filter(itemQ);
  const itemsVis = itemsQ.filter(itemEst);
  const recogidasVis = recogidas.filter((p) => (!recPrio || p.prioridad === 'alta') && coincideP(`${p.taller} ${p.sede || ''} ${(p.placas || []).join(' ')} ${p.referencia || ''}`));
  const hayFiltroP = !!kqP || estPlan !== 'todas';
  // 23/11/2026: encargos que pueden ir a la ruta (con taller, o con otro lugar escrito). Hacer sin lugar no.
  const encEnRuta = new Set(paradas.filter((p) => p.tipo === 'encargo' && p.estado !== 'cancelada' && p.encargoId).map((p) => p.encargoId));
  const encPlan = (window.loadEncargos ? window.loadEncargos() : []).filter((e) => e.estado !== 'hecho' && (!e.para || e.para === courier) && !encEnRuta.has(e.id) && (e.lugarTipo === 'taller' ? !!e.taller : !!(e.direccion || '').trim()));
  const encVis = encPlan.filter((e) => coincideP(`${e.que} ${e.taller || ''} ${e.sede || ''} ${e.direccion || ''} ${e.placa || ''}`) && (!encUrg || e.urgente));
  const grupos = {}; itemsVis.forEach((it) => { const k = `${it.taller}|${it.sede}`; (grupos[k] = grupos[k] || { key: 'g:' + k, taller: it.taller, sede: it.sede, its: [] }).its.push(it); });
  const gruposL = Object.values(grupos).map((g) => ({ ...g, peor: Math.min(...g.its.map((i) => i.o)), dmax: Math.max(...g.its.map((i) => i.d)) })).sort((a, b) => a.peor - b.peor || b.dmax - a.dmax);
  const gruposAll = {}; itemsPlan.forEach((it) => { const k = `${it.taller}|${it.sede}`; (gruposAll[k] = gruposAll[k] || { key: 'g:' + k, taller: it.taller, sede: it.sede, its: [] }).its.push(it); });
  const gruposTodos = Object.values(gruposAll);
  const nPlanEnt = itemsPlan.length;
  const encEnGrupo = (e) => e.lugarTipo === 'taller' && grupos[`${e.taller}|${e.sede}`];
  const encSueltos = vista === 'taller' ? encVis.filter((e) => !encEnGrupo(e)) : encVis;
  const toggle = (k) => setSel((s) => { const n = new Set(s); n.has(k) ? n.delete(k) : n.add(k); return n; });
  const toggleGrupo = (g) => setSel((s) => { const n = new Set(s); const todos = g.its.every((i) => n.has(i.k)); g.its.forEach((i) => todos ? n.delete(i.k) : n.add(i.k)); return n; });
  const agregar = () => {
    const now = Date.now(); const selR = recogidas.filter((p) => sel.has('s:' + p.id));
    selR.forEach((p, i) => window.updateParada(p.id, { estado: 'pendiente', orden: now + i }));
    // Una parada por taller con sus órdenes y garantías (una sola visita).
    const selG = gruposTodos.map((g) => ({ ...g, its: g.its.filter((i) => sel.has(i.k)) })).filter((g) => g.its.length);
    selG.forEach((g, i) => {
      const co = window.tallerCoords ? window.tallerCoords(g.taller, g.sede) : {};
      const tks = g.its.filter((x) => x.t).map((x) => x.t), gs = g.its.filter((x) => x.gar).map((x) => x.gar);
      const cli = (tks.find((x) => x.cliente) || {}).cliente; if (cli) co.direccion = cli.direccion;
      window.addParada({ id: 'p-ent-' + now + '-' + i, tipo: 'entregar', taller: g.taller, sede: g.sede, tallerId: co.tallerId, direccion: co.direccion, ciudad: co.ciudad, lat: co.lat, lng: co.lng,
        consecutivos: tks.map((x) => String(x.codigo)), ticketIds: tks.map((x) => x.id), referencia: [...tks.map((x) => '' + x.codigo), ...gs.map((x) => '' + x.e.codigo)].join(', '),
        garantias: gs.map((x) => ({ ticketId: x.e.ticketId, garId: x.g.id, codigo: String(x.e.codigo), placa: x.e.placa, rines: x.g.rines.length })),
        estado: 'pendiente', creadaPor: 'admin', prioridad: 'normal', notas: '', fecha: hoy, asignadoA: courier, orden: now + 100 + i, createdAt: now, updatedAt: now });
    });
    const selE = encPlan.filter((e) => sel.has('enc:' + e.id));
    selE.forEach((e, i) => window.crearParadaEncargo(e, { asignadoA: courier, creadaPor: 'admin', orden: now + 200 + i, fecha: hoy }));
    const n = selR.length + selG.length + selE.length;
    if (window.reabrirJornada) window.reabrirJornada();
    avisar('El admin agregó paradas a tu ruta', `${n} ${n === 1 ? 'parada nueva' : 'paradas nuevas'} en tu ruta de hoy.`, { kind: 'add', detalle: `Agregó ${n} ${n === 1 ? 'parada' : 'paradas'}` });
    setSel(new Set()); setTab('hoy'); pcAvisar(); toast(`Agregadas a la ruta de ${nombre}`);
  };
  const encSel = encPlan.filter((e) => sel.has('enc:' + e.id));
  const nParadas = new Set([...recogidas.filter((p) => sel.has('s:' + p.id)).map((p) => 's' + p.id), ...gruposTodos.filter((g) => g.its.some((i) => sel.has(i.k))).map((g) => g.key.slice(2)), ...encSel.map((e) => e.lugarTipo === 'taller' ? `${e.taller}|${e.sede}` : 'o' + e.id)]).size;
  const nSelRec = recogidas.filter((p) => sel.has('s:' + p.id)).length; const nSelEnt = itemsPlan.filter((i) => sel.has(i.k)).length;
  const nMarcadas = nSelRec + nSelEnt + encSel.length;
  const visibles = new Set([...recogidasVis.map((p) => 's:' + p.id), ...itemsVis.map((i) => i.k), ...encVis.map((e) => 'enc:' + e.id)]);
  const nOcultas = [...sel].filter((k) => !visibles.has(k) && (k.startsWith('s:') ? recogidas.some((p) => 's:' + p.id === k) : k.startsWith('enc:') ? encPlan.some((e) => 'enc:' + e.id === k) : itemsPlan.some((i) => i.k === k))).length;
  const encFila = (e, chica) => { const k = 'enc:' + e.id, on = sel.has(k); const T = window.ENC_TIPO[e.tipo]; return (
    <div key={k} onClick={() => toggle(k)} style={chica ? { display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0 6px 28px', borderBottom: `1px dashed ${TOKENS.border}`, cursor: 'pointer' } : pcItemCard(on, false, { alignItems: 'center' })}>
      {pcCasilla(on, false, chica)}
      <div style={{ flex: 1, minWidth: 0 }}><span style={{ fontSize: 13, fontWeight: 600 }}>{e.que}</span>{e.placa && <span style={{ fontFamily: pcMono, fontWeight: 700, fontSize: 11.5, marginLeft: 6, background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 5, padding: '1px 5px' }}>{e.placa}</span>}
        {!chica && <span style={{ display: 'block', fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>{[window.encDonde(e), window.encParaTxt(e), e.lugarTipo === 'otro' && 'sin punto en el mapa'].filter(Boolean).join(' · ')}</span>}</div>
      {e.urgente && <span style={{ color: TOKENS.primary, fontSize: 12, fontWeight: 700 }}>↑</span>}
      {window.EncEtiquetas && <window.EncEtiquetas tipo={e.tipo} grande />}
    </div>); };
  const pcCasilla = (on, part, chica) => <span style={{ width: chica ? 16 : 18, height: chica ? 16 : 18, borderRadius: 5, boxSizing: 'border-box', border: `2px solid ${on || part ? TOKENS.primary : TOKENS.borderInput}`, background: on ? TOKENS.primary : part ? TOKENS.primaryBg : 'transparent', color: on ? '#fff' : TOKENS.primary, fontSize: 11, fontWeight: 800, display: 'grid', placeItems: 'center', flexShrink: 0 }}>{on ? '✓' : part ? '–' : ''}</span>;
  const pcFilaPlaca = (it) => <span style={{ display: 'inline-flex', alignItems: 'flex-end', gap: 6, flexWrap: 'wrap' }}>{window.PlacaOrdenChica ? <window.PlacaOrdenChica placa={it.tk.placa} codigo={it.tk.codigo} /> : <PcPlaca p={it.tk.placa} />}{window.InsigniasPlaca && <window.InsigniasPlaca ticket={it.tk} alto={22} />}</span>;
  const pcChipPlan = (it) => it.gar ? <PcChip bg="#e6f7fa" fg="#0e7490">↺ {it.e.label}</PcChip> : it.e.pausa ? <PcChipPausa /> : <PcChipEst k={it.e.orden} />;
  // Historial
  const dias = {};
  paradas.filter((p) => p.asignadoA === courier && p.fecha !== hoy && p.estado === 'completada').forEach((p) => { (dias[p.fecha] = dias[p.fecha] || []).push(p); });
  const histL = Object.entries(dias).map(([f, ps]) => {
    const ds = (window.groupByDestino ? window.groupByDestino(ps) : []).sort((a, b) => (a.iniciadaEn || a.completadaEn || 0) - (b.iniciadaEn || b.completadaEn || 0));
    const ini = Math.min(...ds.map((d) => d.iniciadaEn || Infinity)), fin = Math.max(...ds.map((d) => d.completadaEn || 0));
    return { f, iso: pcIso(f), ds, rec: ps.filter((p) => p.tipo === 'recoger').length, ent: ps.filter((p) => p.tipo === 'entregar').length, dur: isFinite(ini) && fin ? fin - ini : 0 };
  }).sort((a, b) => b.iso.localeCompare(a.iso));
  const hSel = histL.find((h) => h.f === histDia) || histL[0];
  const fechaTxt = (f) => { const d = pcFechaDate(f); if (!d) return f; const t = d.toLocaleDateString('es-CO', { weekday: 'long', day: 'numeric', month: 'short' }); return t.charAt(0).toUpperCase() + t.slice(1); };
  // Mapa
  let markers = [];
  const mk = (d, label, color, key) => d.lat != null && d.lng != null ? { lat: d.lat, lng: d.lng, label: hov === key ? '●' : label, color: hov === key ? TOKENS.text : color, popup: `<b>${d.taller}</b>${d.sede ? ' · ' + d.sede : ''}` } : null;
  if (tab === 'hoy' || tab === 'plan') markers = ordenRuta.map((d, i) => mk(d, d.estado === 'completada' ? '✓' : String(i + 1), d.estado === 'completada' ? TOKENS.primary : d.estado === 'en_curso' ? TOKENS.caution : '#8c97ad', d.key));
  if (tab === 'plan') {
    if (subPlan === 'rec') recogidasVis.forEach((p) => { const co = p.lat != null ? p : (window.tallerCoords ? window.tallerCoords(p.taller, p.sede) : {}); markers.push(mk({ ...p, ...co, taller: p.taller, sede: p.sede }, 'R', '#c79a1e', 's:' + p.id)); });
    if (subPlan === 'ent') gruposL.forEach((g) => { const co = window.tallerCoords ? window.tallerCoords(g.taller, g.sede) : {}; markers.push(mk({ ...co, taller: g.taller, sede: g.sede }, 'E', '#c79a1e', g.key)); });
    if (subPlan === 'enc') encVis.forEach((e) => { if (e.lugarTipo !== 'taller') return; const co = window.tallerCoords ? window.tallerCoords(e.taller, e.sede) : {}; markers.push(mk({ ...co, taller: e.taller, sede: e.sede }, '✓', '#c79a1e', 'enc:' + e.id)); });
  }
  if (tab === 'hist' && hSel) markers = hSel.ds.map((d, i) => mk(d, String(i + 1), TOKENS.primary, 'h:' + d.key));
  markers = markers.filter(Boolean);
  const leyenda = [[TOKENS.primary, 'Hecha'], [TOKENS.caution, 'En curso'], ['#8c97ad', 'Pendiente']].concat(tab === 'plan' ? [['#c79a1e', 'Por planear']] : []);
  const hovProps = (k) => ({ onMouseEnter: () => setHov(k), onMouseLeave: () => setHov((h) => h === k ? null : h) });

  // 23/11/2026: placas de una parada en recuadros chicos (más bajos que el taller), con estado y "Ver".
  const tkPorCodigo = (c) => [...(window.loadPendientesSaved ? window.loadPendientesSaved() : []), ...(window.PENDIENTES_DEMO || [])].find((x) => String(x.codigo) === String(c));
  const entPorTicket = (id, c) => (window.loadEntregados ? window.loadEntregados() : []).find((e) => e.ticketId === id || String(e.codigo) === String(c));
  const filaP = (k, cont, chip, btn) => <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '7px 0', borderTop: `1px dashed ${TOKENS.border}` }}><div style={{ flex: 1, minWidth: 0, display: 'flex', alignItems: 'flex-end', gap: 8, flexWrap: 'wrap' }}>{cont}</div>{chip}{btn}</div>;
  const pcPlacasParada = (d) => <div style={{ marginTop: 8 }}>{d.tareas.map((t) => {
    if (t.tipo === 'recoger') return filaP(t.id, <>{(t.placas || []).length ? t.placas.map((pl) => <span key={pl}>{window.PlacaOrdenChica ? <window.PlacaOrdenChica placa={pl} /> : pl}</span>) : <span style={{ fontSize: 12.5, color: TOKENS.textMuted }}>{(t.referencia || 'Recogida').replace(/^Recogida( solicitada)?\s*—\s*/i, '')}</span>}</>, null, <PcBtn style={{ padding: '3px 9px', fontSize: 12 }} onClick={() => setVerSol(t)}>Ver solicitud</PcBtn>);
    if (t.tipo === 'encargo') { const e = (window.loadEncargos ? window.loadEncargos() : []).find((x) => x.id === t.encargoId); const T = window.ENC_TIPO[(e && e.tipo) || t.encTipo] || ['✓', 'Encargo'];
      return filaP(t.id, <span style={{ fontSize: 13 }}><span style={{ marginRight: 6 }}>{window.EncEtiquetas && <window.EncEtiquetas tipo={(e && e.tipo) || t.encTipo} grande />}</span>{(e && e.que) || t.referencia}{e && e.placa && <span style={{ fontFamily: pcMono, fontWeight: 700, fontSize: 11.5, marginLeft: 6 }}>{e.placa}</span>}</span>, e && e.estado === 'hecho' ? <PcChip bg="#1c7c46" fg="#fff">Hecho</PcChip> : <PcChip bg="#fdf0d5" fg="#8a5a00">Pendiente</PcChip>, null); }
    if (t.tipo !== 'entregar') return null;
    return <React.Fragment key={t.id}>
      {(t.consecutivos || []).map((c, j) => { const id = (t.ticketIds || [])[j]; const tk = tkPorCodigo(c); const en = entPorTicket(id, c); const placa = (tk || en || {}).placa || ''; const e = tk && window.estadoProcesos ? window.estadoProcesos(tk) : null; const rid = (tk || {}).id || id || (en || {}).ticketId;
        return filaP(c, window.PlacaOrdenChica ? <window.PlacaOrdenChica placa={placa} codigo={c} /> : `${placa} ${c}`, en ? <PcChip bg="#1c7c46" fg="#fff">Entregado</PcChip> : e ? (e.pausa ? <PcChipPausa /> : <PcChipEst k={e.orden} />) : null, rid ? <PcBtn style={{ padding: '3px 9px', fontSize: 12 }} onClick={() => setVerDet(rid)}>Ver</PcBtn> : null); })}
      {(t.garantias || []).map((g) => filaP('g' + g.garId, window.PlacaOrdenChica ? <window.PlacaOrdenChica placa={g.placa} codigo={g.codigo} /> : g.placa, <PcChip bg="#e6f7fa" fg="#0e7490">↺ Garantía</PcChip>, <PcBtn style={{ padding: '3px 9px', fontSize: 12 }} onClick={() => setVerDet(g.ticketId)}>Ver</PcBtn>))}
    </React.Fragment>; })}</div>;
  let izq;
  if (tab === 'hoy') {
    const hechas = completados.length;
    izq = <>
      <div style={{ ...pcCard, padding: '12px 14px', marginBottom: 12, display: 'flex', alignItems: 'center', gap: 10, fontSize: 13 }}>
        <b>{hechas} de {destinos.length} {destinos.length === 1 ? 'parada' : 'paradas'}</b>
        <span style={{ flex: 1, height: 6, borderRadius: 99, background: TOKENS.surfaceLow, overflow: 'hidden' }}><span style={{ display: 'block', width: (destinos.length ? hechas / destinos.length * 100 : 0) + '%', height: '100%', background: TOKENS.primary }} /></span>
        <span style={{ color: TOKENS.textMuted, fontSize: 12 }}>{isFinite(inicio) ? 'Inició ' + pcHora(inicio) : 'Sin iniciar'}</span>
      </div>
      {!destinos.length && <div style={{ fontSize: 13, color: TOKENS.textMuted, padding: '8px 2px' }}>{nombre} no tiene paradas para hoy. Agrégalas desde Por planear.</div>}
      {ordenRuta.map((d, i) => {
        const st = d.estado === 'completada' ? 'done' : d.estado === 'en_curso' ? 'cur' : 'pend';
        const pend = st === 'pend';
        return (
          <div key={d.key} {...hovProps(d.key)} draggable={pend} onDragStart={() => setDrag(d.key)} onDragOver={(e) => { if (pend && drag) e.preventDefault(); }} onDrop={() => { if (drag) reordenar(drag, d.key); setDrag(null); }}
          style={pcItemCard(false, hov === d.key, { background: st === 'cur' ? TOKENS.cautionBg : TOKENS.surface, borderColor: st === 'cur' ? TOKENS.caution : hov === d.key ? '#9fb3d6' : TOKENS.border, cursor: pend ? 'grab' : 'default', opacity: drag === d.key ? 0.5 : 1 })}>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                {pend && <span title="Arrastra para cambiar el orden" style={{ color: TOKENS.textSubtle, lineHeight: '24px' }}>≡</span>}
                {pcNum(st, st === 'done' ? '✓' : i + 1)}
                <b style={{ fontSize: 14, flex: 1, minWidth: 0 }}>{d.taller}{d.sede ? ' · ' + d.sede : ''}</b>
                {d.prioridad === 'alta' && st !== 'done' && <span style={{ fontSize: 11.5, fontWeight: 700, borderRadius: 999, padding: '3px 9px', background: TOKENS.primaryBg, color: TOKENS.primary, border: `1px solid ${TOKENS.primaryBorder}`, whiteSpace: 'nowrap' }}>↑ Prioridad</span>}
                {[...new Set(d.tareas.map((t) => t.tipo))].filter((t) => t === 'recoger' || t === 'entregar' || t === 'encargo').map((t) => <React.Fragment key={t}>{pcTipoChip(t)}</React.Fragment>)}
                {d.tareas.some((t) => t.tipo === 'entregar') && window.catMensajeroRecoge && !window.catMensajeroRecoge(d.taller, d.sede) && pcChipTransp}
              </div>
              <div style={{ marginLeft: pend ? 46 : 32 }}>
              {st === 'cur' && <span style={{ display: 'flex', alignItems: 'center', gap: 6, color: TOKENS.cautionText, fontWeight: 500, fontSize: 12, marginTop: 5 }}><span style={{ width: 8, height: 8, borderRadius: 99, background: TOKENS.cautionText, animation: 'rdBlink 1.4s infinite' }} />En curso desde {pcHora(d.iniciadaEn)}{d.iniciadaEn && window.LiveTimer ? <> · <window.LiveTimer since={d.iniciadaEn} /></> : null}</span>}
              {st === 'done' && <span style={{ display: 'block', fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>Llegó {pcHora(d.iniciadaEn)} · salió {pcHora(d.completadaEn)}</span>}
              {pcPlacasParada(d)}
              {pend && <span style={{ display: 'flex', gap: 6, marginTop: 10 }}>
                <PcBtn style={{ padding: '5px 10px', fontSize: 12 }} onClick={() => { const nv = d.prioridad === 'alta' ? 'normal' : 'alta'; d.tareas.forEach((t) => window.updateParada(t.id, { prioridad: nv })); avisar('El admin cambió una prioridad', `${d.taller} · ${d.sede} ahora es prioridad ${nv === 'alta' ? 'ALTA' : 'normal'}.`, { kind: 'priority', detalle: `${d.taller}: prioridad ${nv === 'alta' ? 'ALTA' : 'normal'}` }); pcAvisar(); toast(nv === 'alta' ? 'Con prioridad' : 'Prioridad normal'); }}>{d.prioridad === 'alta' ? 'Quitar prioridad' : '↑ Dar prioridad'}</PcBtn>
                <PcBtn tone="r" style={{ padding: '5px 10px', fontSize: 12 }} onClick={() => setConf({ tone: 'danger', t: 'Quitar parada', m: `${d.taller} · ${d.sede} sale de la ruta de hoy y vuelve a Por planear.`, ok: 'Quitar', fn: () => { d.tareas.forEach((t) => window.devolverParadaABandeja(t)); avisar('El admin quitó una parada de tu ruta', `${d.taller} · ${d.sede} volvió a "Por planear".`, { kind: 'remove', detalle: `Quitó ${d.taller} · ${d.sede}` }); pcAvisar(); toast('Parada quitada', true); } })}>Quitar</PcBtn>
              </span>}
              </div>
            </div>
          </div>);
      })}
    </>;
  } else if (tab === 'plan') {
    izq = <>
      {subPlan === 'ent' && <>
      <div style={{ display: 'flex', alignItems: 'center', margin: '2px 2px 8px' }}>
        <span style={{ ...pcLbl, flex: 1 }}>Por entregar · {hayFiltroP ? `${itemsVis.length} de ${nPlanEnt}` : nPlanEnt}</span>
        {window.VistaToggle && <window.VistaToggle vista={vista} onChange={setVista} />}
      </div>
      <div style={{ fontSize: 11.5, color: TOKENS.textSubtle, margin: '-4px 2px 8px' }}>{vista === 'placa' ? 'Las más urgentes primero. Marca cada placa; “Ver” abre la ficha.' : 'La casilla del taller marca todas sus placas; también puedes marcarlas una por una.'}</div>
      {!itemsVis.length && <div style={{ fontSize: 13, color: TOKENS.textMuted, padding: '4px 2px' }}>{itemsPlan.length ? 'Ninguna placa coincide con la búsqueda.' : 'No hay placas listas para entregar.'}</div>}
      {vista === 'placa' ? itemsVis.map((it) => { const on = sel.has(it.k); const gk = 'g:' + it.taller + '|' + it.sede; return (
        <div key={it.k} {...hovProps(gk)} onClick={() => toggle(it.k)} style={pcItemCard(on, hov === gk, { alignItems: 'center' })}>
            {pcCasilla(on)}
            <div style={{ flex: 1, minWidth: 0 }}>{pcFilaPlaca(it)}<span style={{ display: 'block', fontSize: 12, color: TOKENS.textMuted, marginTop: 3 }}>{it.taller}{it.sede ? ' · ' + it.sede : ''} · {pcItemsTxt(it.tk.items)}</span></div>
            {pcChipPlan(it)}
            <PcBtn style={{ padding: '4px 9px', fontSize: 12 }} onClick={(ev) => { ev.stopPropagation(); setVerDet(it.tk.id); }}>Ver</PcBtn>
          </div>); }) :
      gruposL.map((g) => { const nOn = g.its.filter((i) => sel.has(i.k)).length; const todos = nOn === g.its.length; return (
        <div key={g.key} {...hovProps(g.key)} style={pcItemCard(todos, hov === g.key, { flexDirection: 'column', gap: 0, cursor: 'default' })}>
            <div onClick={() => toggleGrupo(g)} style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', width: '100%' }}>
              {pcCasilla(todos, nOn > 0 && !todos)}
              <b style={{ fontSize: 13.5, flex: 1 }}>{g.taller}{g.sede ? ' · ' + g.sede : ''}</b>
              <span style={{ fontSize: 12, color: TOKENS.textMuted }}>{(() => { const tot = (gruposAll[g.key.slice(2)] || g).its.length; return tot !== g.its.length ? `${g.its.length} de ${tot} placas` : `${tot} ${tot === 1 ? 'placa' : 'placas'}`; })()}</span>{pcTipoChip('entregar')}{window.catMensajeroRecoge && !window.catMensajeroRecoge(g.taller, g.sede) && pcChipTransp}
            </div>
            <div style={{ width: '100%', marginTop: 8, borderTop: `1px solid ${TOKENS.border}` }}>
              {g.its.map((it) => { const on = sel.has(it.k); return (
              <div key={it.k} onClick={() => toggle(it.k)} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0 6px 28px', borderBottom: `1px dashed ${TOKENS.border}`, cursor: 'pointer' }}>
                  {pcCasilla(on, false, true)}
                  <div style={{ flex: 1, minWidth: 0 }}>{pcFilaPlaca(it)}</div>
                  {pcChipPlan(it)}
                  <PcBtn style={{ padding: '3px 8px', fontSize: 11.5 }} onClick={(ev) => { ev.stopPropagation(); setVerDet(it.tk.id); }}>Ver</PcBtn>
                </div>); })}
              {encVis.filter((e) => e.lugarTipo === 'taller' && `${e.taller}|${e.sede}` === g.key.slice(2)).map((e) => encFila(e, true))}
            </div>
          </div>); })}
      </>}
      {subPlan === 'rec' && <>
      <div style={{ display: 'flex', alignItems: 'center', margin: '2px 2px 8px' }}><span style={{ ...pcLbl, flex: 1 }}>Por recoger · {hayFiltroP && kqP ? `${recogidasVis.length} de ${recogidas.length}` : 'solicitudes'}</span></div>
      {!recogidasVis.length && <div style={{ fontSize: 13, color: TOKENS.textMuted, padding: '4px 2px 10px' }}>{recogidas.length ? 'Ninguna solicitud coincide.' : 'Sin solicitudes.'}</div>}
      {recogidasVis.map((p) => { const k = 's:' + p.id, on = sel.has(k); return (
        <div key={p.id} {...hovProps(k)} onClick={() => toggle(k)} style={pcItemCard(on, hov === k)}>
            <span style={{ width: 18, height: 18, borderRadius: 5, border: `2px solid ${on ? TOKENS.primary : TOKENS.borderInput}`, background: on ? TOKENS.primary : 'transparent', color: '#fff', fontSize: 11, fontWeight: 800, display: 'grid', placeItems: 'center', flexShrink: 0, marginTop: 1 }}>{on ? '✓' : ''}</span>
            <div style={{ flex: 1, minWidth: 0 }}><b style={{ fontSize: 13.5 }}>{p.taller}{p.sede ? ' · ' + p.sede : ''}</b><span style={{ display: 'block', fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>{(p.placas || []).length ? `${p.placas.join(', ')} · ` : ''}{p.referencia ? p.referencia.replace(/^Recogida solicitada\s*[—-]\s*/i, '') + ' · ' : ''}{window.relTime ? window.relTime(p.createdAt) : ''}{p.arrastrada ? ' · de días anteriores' : ''}</span></div>
            {p.prioridad === 'alta' && pcTag('↑ Prioridad')}{pcTipoChip('recoger')}
          </div>); })}
      </>}
      {subPlan === 'enc' && <>
        <div style={{ ...pcLbl, margin: '2px 2px 8px' }}>Por encargar · {encVis.length}{encVis.length !== encPlan.length ? ` de ${encPlan.length}` : ''}</div>
        <div style={{ fontSize: 11.5, color: TOKENS.textSubtle, margin: '-4px 2px 8px' }}>Encargos con taller o con lugar escrito. Los de un taller con placas por entregar también salen dentro de ese taller.</div>
        {!encVis.length && <div style={{ fontSize: 13, color: TOKENS.textMuted, padding: '4px 2px' }}>{encPlan.length ? 'Ningún encargo coincide.' : 'No hay encargos para meter a la ruta.'}</div>}
        {encVis.map((e) => encFila(e, false))}
      </>}
      <div style={{ position: 'sticky', bottom: -16, margin: '12px -16px -16px', padding: '12px 16px', background: TOKENS.surface, borderTop: `1px solid ${TOKENS.border}`, display: 'flex', alignItems: 'center', gap: 10 }}>
        <span style={{ flex: 1, fontSize: 12.5, color: TOKENS.textMuted }}>{nParadas ? <><b style={{ color: TOKENS.text }}>{[nSelEnt && `${nSelEnt} ${nSelEnt === 1 ? 'entrega' : 'entregas'}`, nSelRec && `${nSelRec} ${nSelRec === 1 ? 'recogida' : 'recogidas'}`, encSel.length && `${encSel.length} ${encSel.length === 1 ? 'encargo' : 'encargos'}`].filter(Boolean).join(' · ')}</b> · {nParadas} {nParadas === 1 ? 'parada' : 'paradas'}{nOcultas ? ` · ${nOcultas} no se ${nOcultas === 1 ? 've' : 'ven'} por el filtro` : ''}</> : 'Marca lo que quieres agregar a la ruta de hoy.'}</span>
        <PcBtn tone="p" disabled={!nParadas} onClick={() => setConf({ tone: 'primary', t: 'Agregar a la ruta', m: `Se agregan ${nParadas} ${nParadas === 1 ? 'parada' : 'paradas'} a la ruta de hoy de ${nombre}.`, ok: 'Agregar', fn: agregar })}>＋ Agregar</PcBtn>
      </div>
    </>;
  } else {
    izq = <>
      {!histL.length && <div style={{ fontSize: 13, color: TOKENS.textMuted, padding: '8px 2px' }}>Aún no hay rutas de días anteriores. Aquí aparecen cuando {nombre} complete paradas.</div>}
      {histL.map((h) => { const on = hSel && hSel.f === h.f; return (
        <div key={h.f} onClick={() => setHistDia(h.f)} style={pcItemCard(on, false, { alignItems: 'center' })}>
            <div style={{ flex: 1 }}><b style={{ fontSize: 13.5 }}>{fechaTxt(h.f)}</b><span style={{ display: 'block', fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>{h.ds.length} {h.ds.length === 1 ? 'parada' : 'paradas'} · {h.rec} {h.rec === 1 ? 'recogida' : 'recogidas'} · {h.ent} {h.ent === 1 ? 'entrega' : 'entregas'}</span></div>
            <b style={{ fontSize: 13 }}>{pcDur(h.dur)}</b>
          </div>); })}
      {hSel && <>
        <div style={{ ...pcLbl, margin: '16px 2px 4px' }}>Paradas del {fechaTxt(hSel.f).toLowerCase()}</div>
        {hSel.ds.map((d, i) =>
        <div key={d.key} {...hovProps('h:' + d.key)} style={{ display: 'grid', gridTemplateColumns: '24px 1fr auto', gap: 10, padding: '10px 6px', borderTop: `1px solid ${TOKENS.border}`, fontSize: 13, alignItems: 'flex-start', background: hov === 'h:' + d.key ? TOKENS.primaryBg : 'transparent', borderRadius: 8 }}>
            {pcNum('done', i + 1)}
            <div><b>{d.taller}{d.sede ? ' · ' + d.sede : ''}</b><div style={{ fontSize: 12, color: TOKENS.textMuted }}>{tareasTxt(d)} · llegó {pcHora(d.iniciadaEn)} · salió {pcHora(d.completadaEn)}</div></div>
            {pcTag(`${pcDur(d.completadaEn && d.iniciadaEn ? d.completadaEn - d.iniciadaEn : 0)} en sitio`)}
          </div>)}
      </>}
    </>;
  }
  const cabeza = <>
    {ms.length > 1 && <div style={{ marginBottom: 10 }}><select value={courier} onChange={(e) => { setCourier(e.target.value); setSel(new Set()); }} style={{ ...pcInp, width: '100%' }}>{ms.map((m) => <option key={m.usuario} value={m.usuario}>Ruta de {m.nombre}</option>)}</select></div>}
    <PcTabs value={tab} onChange={(v) => { setTab(v); setHov(null); }} options={[['plan', 'Por planear', recogidas.length + nPlanEnt + encPlan.length], ['hoy', 'Ruta de hoy', destinos.length], ['hist', 'Historial', null], ['enc', 'Tareas', nEnc || null]]} />
    {tab === 'plan' && <>
      <div style={{ position: 'relative', marginTop: 10 }}>
        <input value={qPlan} onChange={(e) => setQPlan(e.target.value)} placeholder="Buscar placa, orden, taller o sede" style={{ width: '100%', boxSizing: 'border-box', border: `1px solid ${TOKENS.borderInput}`, borderRadius: 10, padding: '9px 32px 9px 12px', fontFamily: 'inherit', fontSize: 13, background: TOKENS.surfaceLow, color: TOKENS.text, outline: 'none' }} />
        {qPlan && <button type="button" aria-label="Borrar búsqueda" onClick={() => setQPlan('')} style={{ position: 'absolute', right: 6, top: 6, width: 24, height: 24, border: 0, background: 'transparent', color: TOKENS.textSubtle, cursor: 'pointer', fontSize: 14 }}>✕</button>}
      </div>
      <div style={{ display: 'flex', gap: 3, marginTop: 10, background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 10, padding: 3 }}>
        {[['ent', 'Por entregar', itemsVis.length], ['rec', 'Por recoger', recogidasVis.length], ['enc', 'Por encargar', encVis.length]].map(([k, l, n]) => { const on = subPlan === k; return (
          <button key={k} type="button" onClick={() => setSubPlan(k)} style={{ flex: 1, border: 0, borderRadius: 8, padding: '6px 8px', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 700, cursor: 'pointer', whiteSpace: 'nowrap', background: on ? TOKENS.surface : 'transparent', color: on ? TOKENS.primary : TOKENS.textMuted, boxShadow: on ? '0 1px 3px rgba(22,35,63,.12)' : 'none' }}>{l} <span style={{ fontSize: 11, fontWeight: 600, opacity: .75 }}>{n}</span></button>); })}
      </div>
      {subPlan === 'rec' && <div style={{ display: 'flex', gap: 6, marginTop: 8 }}><button type="button" onClick={() => setRecPrio(!recPrio)} style={{ border: `1px solid ${recPrio ? TOKENS.primary : TOKENS.borderInput}`, background: recPrio ? TOKENS.primary : TOKENS.surface, color: recPrio ? '#fff' : TOKENS.text, borderRadius: 99, padding: '4px 10px', fontFamily: 'inherit', fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>↑ Prioridad <span style={{ opacity: .7, fontWeight: 500 }}>{recogidas.filter((p) => p.prioridad === 'alta').length}</span></button></div>}
      {subPlan === 'enc' && <div style={{ display: 'flex', gap: 6, marginTop: 8 }}><button type="button" onClick={() => setEncUrg(!encUrg)} style={{ border: `1px solid ${encUrg ? TOKENS.primary : TOKENS.borderInput}`, background: encUrg ? TOKENS.primary : TOKENS.surface, color: encUrg ? '#fff' : TOKENS.text, borderRadius: 99, padding: '4px 10px', fontFamily: 'inherit', fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>↑ Prioridad <span style={{ opacity: .7, fontWeight: 500 }}>{encPlan.filter((e) => e.urgente).length}</span></button></div>}
      {subPlan === 'ent' && <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 8 }}>
        {[['todas', 'Todas', null], ['0', PC_EST[0][0], PC_EST[0][3]], ['1', PC_EST[1][0], PC_EST[1][3]], ['2', PC_EST[2][0], PC_EST[2][3]], ['3', PC_EST[3][0], PC_EST[3][3]], ['x', '⚡ Express', null]].map(([k, l, dot]) => { const on = estPlan === k; const n = k === 'todas' ? itemsQ.length : itemsQ.filter((it) => k === 'x' ? it.x : !it.gar && !it.e.pausa && String(it.e.orden) === k).length; return (
          <button key={k} type="button" onClick={() => setEstPlan(on && k !== 'todas' ? 'todas' : k)} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, border: `1px solid ${on ? (k === 'x' ? '#e879b0' : TOKENS.primary) : TOKENS.borderInput}`, background: on ? (k === 'x' ? '#fce7f3' : TOKENS.primary) : TOKENS.surface, color: on ? (k === 'x' ? '#be185d' : '#fff') : k === 'x' ? '#be185d' : TOKENS.text, borderRadius: 99, padding: '4px 10px', fontFamily: 'inherit', fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>
            {dot && <span style={{ width: 7, height: 7, borderRadius: 99, background: on ? '#fff' : dot }} />}{l} <span style={{ opacity: .7, fontWeight: 500 }}>{n}</span></button>); })}
      </div>}
    </>}
  </>;
  const der =
  <div style={{ position: 'relative', height: alto - 32 }}>
      {Map && markers.length ? <Map markers={markers} height={alto - 32} fitBounds /> : <div style={{ height: '100%', borderRadius: 14, background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, display: 'grid', placeItems: 'center', color: TOKENS.textMuted, fontSize: 13 }}>Sin ubicaciones para mostrar.</div>}
      <div style={{ position: 'absolute', left: 12, bottom: 12, zIndex: 500, background: 'rgba(255,255,255,.94)', border: `1px solid ${TOKENS.border}`, borderRadius: 10, padding: '7px 10px', fontSize: 11.5, color: TOKENS.textMuted, display: 'flex', gap: 12 }}>
        {leyenda.map(([c, l]) => <span key={l} style={{ display: 'flex', alignItems: 'center', gap: 5 }}><span style={{ width: 10, height: 10, borderRadius: 99, background: c }} />{l}</span>)}
      </div>
      {ms.length <= 1 && <div style={{ position: 'absolute', right: 12, top: 12, zIndex: 500, background: 'rgba(255,255,255,.94)', border: `1px solid ${TOKENS.border}`, borderRadius: 999, padding: '5px 11px', fontSize: 12, color: TOKENS.textMuted }}>Ruta de <b style={{ color: TOKENS.text }}>{nombre}</b> · en vivo</div>}
    </div>;
  const modales = <>
      {nuevoEnc && <PcAsignarEncargo inicial={{ para: courier }} onClose={() => setNuevoEnc(false)} onGuardado={(e, r) => { setNuevoEnc(false); pcAvisar(); toast(e ? `Tarea creada · ${e.que}` : `Suministro agregado · ${r.placa}`, 'g'); }} />}
      {nueva && window.NuevaSolicitudModal && <window.NuevaSolicitudModal role="admin" asignadoA={courier} onDismiss={() => setNueva(false)} onCreate={(p) => {
        window.addParada(p);
        if (window.addNotif) window.addNotif({ id: 'n-' + Date.now(), tipo: 'autoasignacion', para: 'mensajero', paraUsuario: courier, estado: 'pendiente', taller: p.taller, sede: p.sede, accion: p.tipo, referencia: p.referencia, paradaId: p.id, actor: 'admin', createdAt: Date.now(), resolucion: null });
        setNueva(false); setTab('plan'); pcAvisar(); toast('Solicitud agregada a Por planear');
      }} />}
  </>;
  if (tab === 'enc') return <div style={{ display: 'flex', flexDirection: 'column', gap: 12, height: '100%' }}>
    <div style={{ maxWidth: 620 }}><PcTabs value={tab} onChange={(v) => { setTab(v); setHov(null); }} options={[['plan', 'Por planear', recogidas.length + nPlanEnt + encPlan.length], ['hoy', 'Ruta de hoy', destinos.length], ['hist', 'Historial', null], ['enc', 'Tareas', nEnc || null]]} /></div>
    <PcEncargosTab toast={toast} />
    {modales}
  </div>;
  return (
    <>
      {pcDosColumnas(560, cabeza, izq, der)}
      {modales}
      {conf && Modal && <Modal tone={conf.tone} icon={conf.tone === 'danger' ? I.alert(24, TOKENS.danger) : I.check(24, TOKENS.primary)} title={conf.t} message={conf.m} confirmLabel={conf.ok} onDismiss={() => setConf(null)} onConfirm={() => { const fn = conf.fn; setConf(null); fn(); }} />}
      {verDet && (() => { const r = pcRegistros().find((x) => x.id === verDet); return r ? <PcDetalle r={r} toast={toast} soloVer onClose={() => setVerDet(null)} /> : null; })()}
      {verSol && <PcDrawer ancho={460} fondo="#eef1f6" onClose={() => setVerSol(null)} titulo={<div><b style={{ fontSize: 16 }}>Solicitud de recogida</b><div style={{ fontSize: 12.5, color: TOKENS.textMuted, marginTop: 2 }}>{verSol.taller}{verSol.sede ? ' · ' + verSol.sede : ''}</div></div>} pie={<><span style={{ flex: 1 }} /><PcBtn onClick={() => setVerSol(null)}>Cerrar</PcBtn></>}>
        <div style={{ background: TOKENS.surface, border: '1px solid #dfe5ee', borderRadius: 14, padding: 14 }}>
          {(verSol.placas || []).length > 0 && <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 12 }}>{verSol.placas.map((pl) => <span key={pl}>{window.PlacaOrdenChica ? <window.PlacaOrdenChica placa={pl} /> : pl}</span>)}</div>}
          <div style={{ border: `1px solid ${TOKENS.border}`, borderRadius: 12, overflow: 'hidden' }}>
            {[['Taller', [verSol.taller, verSol.sede].filter(Boolean).join(' · ')], ['Dirección', verSol.direccion], ['Qué recoger', (verSol.referencia || '').replace(/^Recogida( solicitada)?\s*—\s*/i, '')], ['Cliente', verSol.cliente ? [verSol.cliente.nombre, verSol.cliente.telefono].filter(Boolean).join(' · ') : ''], ['Contacto', [verSol.contacto, verSol.telefono].filter(Boolean).join(' · ')], ['Notas', verSol.notas], ['Prioridad', verSol.prioridad === 'alta' ? '↑ Alta' : 'Normal'], ['Pedida', [verSol.createdAt && window.relTime ? window.relTime(verSol.createdAt) : '', verSol.creadaPor === 'admin' ? 'por la oficina' : verSol.creadaPor === 'publico' ? 'por el taller' : ''].filter(Boolean).join(' · ')]].filter(([, v]) => v).map(([k2, v], i) =>
              <div key={k2} style={{ display: 'grid', gridTemplateColumns: '120px 1fr', borderTop: i ? `1px solid ${TOKENS.border}` : 'none' }}><span style={{ background: TOKENS.surfaceLow, padding: '8px 12px', fontSize: 12, color: TOKENS.textMuted, fontWeight: 700 }}>{k2}</span><span style={{ padding: '8px 12px', fontWeight: 600, fontSize: 13.5 }}>{v}</span></div>)}
          </div>
        </div>
      </PcDrawer>}
    </>);
}

// ─── Catálogos en el PC (13/11/2026): lista a la izquierda, el seleccionado a la derecha ──
function PcCatalogos({ inicial, toast }) {
  const [cat, update] = useCatalogo();
  const [tab, setTab] = React.useState('t');
  const [q, setQ] = React.useState('');
  const [rev, setRev] = React.useState(inicial === 'revisar');
  const [ti, setTi] = React.useState(null);
  const [ai, setAi] = React.useState(null);
  const [ri, setRi] = React.useState(null);
  const [edit, setEdit] = React.useState(null); // id de sede o 'nueva'
  const [form, setForm] = React.useState(null);
  const [aform, setAform] = React.useState(null);
  const [pickQ, setPickQ] = React.useState('');
  const [pedir, setPedir] = React.useState(null);
  const [conf, setConf] = React.useState(null);
  const [sub, setSub] = React.useState('serv');
  const [ci, setCi] = React.useState('Cali');
  const [fT, setFT] = React.useState('todos'); // todos | ub | dir | off · 27/11/2026
  const [unir, setUnir] = React.useState(null);
  const [unirS, setUnirS] = React.useState(null); // { src: sede, destId } // { destId, mapa } · 26/11/2026
  const [impRes, setImpRes] = React.useState(null); // resultado de subir la plantilla de ubicaciones
  const fileRef = React.useRef(null);
  const Modal = window.ConfirmActionModal;
  const k = catNorm(q);
  const ask = (tone, t, m, ok, fn) => setConf({ tone, t, m, ok, fn });
  const ordenar = (c) => c.talleres.sort((x, y) => x.nombre.localeCompare(y.nombre, 'es'));
  const quitarRev = (c, id) => { c.revisar = c.revisar.filter((z) => z.id !== id); };
  const sumarAlias = (c, tn, sn, llega) => { const s = c.talleres.find((z) => z.nombre === tn)?.sedes.find((z) => z.nombre === sn); if (s && !s.alias.includes(llega)) s.alias.push(llega); };
  const inp = { ...pcInp, width: '100%', background: TOKENS.surfaceLow };
  const chips = (list, onX) => <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5, marginTop: 6 }}>{list.map((x, i) => <span key={i} style={{ fontSize: 11, fontWeight: 600, background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, color: TOKENS.textMuted, borderRadius: 7, padding: '3px 7px' }}>{x}{onX && <button type="button" onClick={() => onX(i)} style={{ border: 0, background: 'none', color: TOKENS.textMuted, cursor: 'pointer', padding: '0 0 0 4px', fontSize: 11 }}>✕</button>}</span>)}</div>;
  const vacio = (txt) => <div style={{ height: '100%', minHeight: 300, display: 'grid', placeItems: 'center', color: TOKENS.textMuted, fontSize: 13.5, textAlign: 'center' }}>{txt}</div>;
  const nuevaRev = rev ? cat.revisar.find((r) => r.id === ri) || cat.revisar[0] : null;
  const t = cat.talleres.find((x) => x.id === ti);
  const a = cat.aseguradoras.find((x) => x.id === ai);
  const abrirForm = (s, extra) => { setEdit(s ? s.id : 'nueva'); setForm(s ? { nombre: s.nombre, ciudad: s.ciudad || 'Cali', zona: s.zona || 'Norte', dir: s.dir || '', ubic: s.ubic, lat: s.lat, lng: s.lng, alias: [...s.alias], enlace: '' } : { nombre: '', ciudad: 'Cali', zona: 'Norte', dir: '', ubic: null, lat: null, lng: null, alias: [], enlace: '', ...extra }); };

  // Plantilla de ubicaciones (25/11/2026): se descarga con todas las sedes, se llena y se sube.
  const UB_COLS = ['ID (no cambiar)', 'Taller', 'Sede', 'Ciudad', 'Dirección', 'Coordenadas (lat, lng)', 'Enlace de Google Maps'];
  // 27/11/2026: solo talleres activos (los inactivos no cuentan ni salen en la plantilla) y sin Cliente particular.
  const sedesTodas = []; cat.talleres.forEach((x) => { if (x.on === false || esParticular(x.nombre)) return; x.sedes.forEach((s2) => sedesTodas.push({ x, s: s2 })); });
  const conUbic = sedesTodas.filter(({ s: s2 }) => s2.lat != null && s2.lng != null).length;
  const descargarPlantilla = () => {
    const rows = [{ bold: true, cells: UB_COLS }];
    sedesTodas.slice().sort((a1, b1) => (a1.s.lat != null) - (b1.s.lat != null) || a1.x.nombre.localeCompare(b1.x.nombre, 'es')).forEach(({ x, s: s2 }) => rows.push({ cells: [s2.id, x.nombre, s2.nombre, s2.ciudad || 'Cali', s2.dir || '', s2.lat != null ? `${s2.lat}, ${s2.lng}` : '', s2.ubic && !/maps\.google\.com\/\?q=/.test(s2.ubic) ? s2.ubic : ''] }));
    const ins = ['Cómo llenar la plantilla de ubicaciones', '', '1. Busca cada taller en Google Maps (en el computador).', '2. Clic derecho sobre el punto exacto del taller: arriba del menú salen las coordenadas (ej: 3.4516, -76.5320). Clic sobre ellas y se copian.', '3. Pégalas en la columna "Coordenadas (lat, lng)" de esa sede.', '4. También puedes llenar o corregir la Dirección.', '5. No cambies la columna ID. Las sedes que dejes vacías quedan como están.', '   Para agregar un taller o una sede que no está: escribe una fila nueva al final con el ID vacío, el Taller, la Sede y la Ciudad (y si quieres dirección y coordenadas).', '6. Guarda el archivo y súbelo en Catálogos › Talleres › Subir plantilla.', '', 'Nota: los enlaces cortos de "Compartir" (maps.app.goo.gl) no traen las coordenadas; por eso es mejor el clic derecho.'].map((t, i) => ({ bold: i === 0, cells: [t] }));
    pcDescargar(pcLibro([{ nombre: 'Sedes', rows, anchos: [12, 28, 18, 12, 34, 24, 36] }, { nombre: 'Instrucciones', rows: ins, anchos: [110] }]), 'Rodando_ubicaciones_sedes.xlsx').then((ok) => ok && toast('Plantilla descargada'));
  };
  const subirPlantilla = async (file) => {
    try {
      const filas = await pcLeerXlsx(file); if (!filas.length) throw new Error('El archivo está vacío.');
      const h = (filas[0] || []).map((x) => catNorm(x));
      const ix = (t) => h.findIndex((x) => x.startsWith(catNorm(t)));
      const iId = ix('ID'), iT = ix('Taller'), iS = ix('Sede'), iD = ix('Dirección'), iC = ix('Coordenadas'), iE = ix('Enlace'), iCi = ix('Ciudad');
      const comp = (x) => catNorm(x).replace(/[^a-z0-9]/g, '');
      const ciuIni = catCiudades();
      if (iT < 0 || iS < 0 || (iC < 0 && iE < 0)) throw new Error('No es la plantilla de ubicaciones: faltan las columnas Taller, Sede y Coordenadas.');
      const res = { coords: 0, dir: 0, sinCoord: [], malas: [], noEsta: [], nuevosT: [], nuevasS: [], inactivos: [] };
      update((c) => {
        filas.slice(1).forEach((f) => {
          const id = iId >= 0 ? String(f[iId] || '').trim() : ''; const tn = String(f[iT] || '').trim(), sn = String(f[iS] || '').trim();
          if (!id && !tn) return;
          let s2 = null, tx0 = null; c.talleres.forEach((x) => x.sedes.forEach((z) => { if (!s2 && ((id && z.id === id) || (!id && catNorm(x.nombre) === catNorm(tn) && catNorm(z.nombre) === catNorm(sn)))) { s2 = z; tx0 = x; } }));
          // Talleres inactivos: no se tocan (ni sus sedes ni sedes nuevas)
          if (!tx0 && !id) tx0 = c.talleres.find((x) => comp(x.nombre) === comp(tn)) || null;
          if (tx0 && tx0.on === false) { if (!res.inactivos.includes(tx0.nombre)) res.inactivos.push(tx0.nombre); return; }
          if (!s2 && id) { res.noEsta.push(`${tn} · ${sn}`); return; }
          if (!s2) { // 26/11/2026: fila nueva (ID vacío) → se crea la sede y, si hace falta, el taller
            if (!tn) return;
            const ciT = iCi >= 0 ? String(f[iCi] || '').trim() : '';
            let ciu = ciuIni.find((z) => catNorm(z.n) === catNorm(ciT || 'Cali'));
            if (!ciu) { ciu = { n: ciT.replace(/\b\w/g, (m) => m.toUpperCase()), cob: false, men: false }; ciuIni.push(ciu); c.ciudades = ciuIni.map((z) => ({ ...z })); }
            let tx = c.talleres.find((x) => comp(x.nombre) === comp(tn));
            if (!tx) { tx = { id: catId('t'), nombre: tn, on: true, sedes: [] }; c.talleres.push(tx); res.nuevosT.push(tn); }
            const nom = sn || (ciu.n === 'Cali' ? 'Principal' : ciu.n);
            s2 = tx.sedes.find((z) => comp(z.nombre) === comp(nom));
            if (!s2) { s2 = { id: catId('s'), nombre: nom, ciudad: ciu.n, zona: null, dir: '', ubic: null, lat: null, lng: null, alias: [tn.toUpperCase()] }; tx.sedes.push(s2); res.nuevasS.push(`${tx.nombre} · ${nom}`); }
          }
          const ct = iC >= 0 ? String(f[iC] || '').trim() : '', en = iE >= 0 ? String(f[iE] || '').trim() : '', di = iD >= 0 ? String(f[iD] || '').trim() : '';
          if (di && di !== (s2.dir || '')) { s2.dir = di; res.dir++; }
          let co = ct ? catCoordsDeTexto(ct) : null;
          if (!co && ct) res.malas.push(`${tn} · ${sn}`);
          if (!co && en) { co = catCoordsDeEnlace(en); if (!co && /^https?:\/\//.test(en)) { if (s2.lat == null) { s2.ubic = en; res.sinCoord.push(`${tn} · ${sn}`); } } }
          if (co && (co.lat !== s2.lat || co.lng !== s2.lng)) { s2.lat = co.lat; s2.lng = co.lng; s2.ubic = en && /^https?:\/\//.test(en) ? en : `https://maps.google.com/?q=${co.lat},${co.lng}`; res.coords++; }
        });
        c.talleres.sort((x, y) => x.nombre.localeCompare(y.nombre, 'es'));
      });
      setImpRes(res);
    } catch (err) { toast(err.message || 'No se pudo leer el archivo', true); }
  };

  // Ciudades (25/11/2026)
  const ciuL = catCiudades();
  const tallCiu = (n) => { const out = []; cat.talleres.forEach((x) => x.on && x.sedes.forEach((s2) => { if (catNorm(s2.ciudad || 'Cali') === catNorm(n)) out.push({ x, s: s2 }); })); return out; };
  const agregarCiudad = (n, despues) => { const lista = catCiudades(); const ya = lista.find((z) => catNorm(z.n) === catNorm(n)); if (!ya) { lista.push({ n, cob: false, men: false }); update((c) => { c.ciudades = lista; }); } if (despues) despues(ya ? ya.n : n); };
  const pedirCiudad = (despues) => setPedir({ t: 'Agregar ciudad', l: 'Ciudad', v: '', sug: true, fn: (n) => { agregarCiudad(n, despues); toast('Ciudad agregada'); } });
  const cambiarCiudad = (n, p) => { const lista = catCiudades().map((z) => catNorm(z.n) === catNorm(n) ? { ...z, ...p } : z); update((c) => { c.ciudades = lista; }); };
  const swCiu = (on, fn) => <button type="button" onClick={fn} aria-pressed={on} style={{ position: 'relative', width: 40, height: 23, borderRadius: 99, border: 0, background: on ? TOKENS.primary : TOKENS.borderInput, cursor: 'pointer', flexShrink: 0 }}><span style={{ position: 'absolute', top: 3, left: on ? 20 : 3, width: 17, height: 17, borderRadius: 99, background: '#fff', transition: 'left .15s' }} /></button>;
  const chipCiu = (txt, on) => <span style={{ fontSize: 11, fontWeight: 600, borderRadius: 999, padding: '2px 8px', whiteSpace: 'nowrap', background: on ? TOKENS.primaryBg : TOKENS.surfaceLow, color: on ? TOKENS.primary : TOKENS.textSubtle, border: `1px solid ${on ? TOKENS.primaryBorder : TOKENS.border}` }}>{txt}</span>;

  // Izquierda
  let izq;
  if (rev) {
    izq = <>
      <PcBtn style={{ padding: '5px 10px', fontSize: 12, marginBottom: 10 }} onClick={() => setRev(false)}>‹ Volver a la lista</PcBtn>
      <div style={{ fontSize: 12.5, color: TOKENS.textMuted, marginBottom: 10, lineHeight: 1.45 }}>Al confirmar, el nombre queda guardado en "Así llega en las órdenes" de la sede.</div>
      {!cat.revisar.length && <div style={{ fontSize: 13, color: TOKENS.textMuted }}>✓ No hay nada por revisar.</div>}
      {cat.revisar.map((r) => { const on = nuevaRev && nuevaRev.id === r.id; return (
        <div key={r.id} onClick={() => { setRi(r.id); setPickQ(''); }} style={pcItemCard(on, false)}>
            <div style={{ flex: 1, minWidth: 0 }}>
              <span style={pcLbl}>{r.motivo === 'mens' ? `Escrito por ${r.porNombre || 'el mensajero'}` : 'Llega como'}</span>
              <b style={{ display: 'block', fontFamily: pcMono, fontSize: 12.5, marginTop: 3, wordBreak: 'break-word' }}>{r.llega}</b>
              <span style={{ display: 'block', fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>{r.motivo === 'mens' ? 'Taller nuevo' : r.motivo === 'sinsede' ? `${r.taller} · falta sede` : `→ ${r.taller} · ${r.sede}`}</span>
            </div>
            {r.motivo === 'sinsede' && <span style={{ fontSize: 11, fontWeight: 500, borderRadius: 999, padding: '2px 8px', background: '#fff2cc', color: '#7f6000', whiteSpace: 'nowrap' }}>Falta sede</span>}
          </div>); })}
    </>;
  } else if (tab === 'c') {
    const L = ciuL.filter((x) => !k || catNorm(x.n).includes(k));
    izq = <>
      <button type="button" onClick={() => pedirCiudad((n) => setCi(n))} style={{ width: '100%', border: `1.5px dashed ${TOKENS.borderInput}`, background: TOKENS.surface, color: TOKENS.primary, borderRadius: 12, padding: '10px 12px', fontFamily: 'inherit', fontWeight: 700, fontSize: 13, cursor: 'pointer' }}>＋ Agregar ciudad</button>
      <div style={{ ...pcLbl, margin: '14px 2px 8px' }}>Ciudades · {L.length}</div>
      {L.map((x) => <div key={x.n} onClick={() => setCi(x.n)} style={pcItemCard(catNorm(ci) === catNorm(x.n), false)}><div style={{ flex: 1, minWidth: 0 }}><b style={{ fontSize: 13.5 }}>{x.n}</b><span style={{ display: 'block', fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>{tallCiu(x.n).length} {tallCiu(x.n).length === 1 ? 'sede' : 'sedes'}</span></div><div style={{ display: 'flex', gap: 4 }}>{chipCiu(x.cob ? 'Cobertura' : 'Sin cobertura', x.cob)}{x.men && chipCiu('Mensajero', true)}</div></div>)}
    </>;
  } else if (tab === 't') {
    const L = cat.talleres.filter((x) => !k || catNorm(x.nombre).includes(k) || x.sedes.some((s) => catNorm(s.nombre).includes(k) || s.alias.some((y) => catNorm(y).includes(k))));
    const Lf = fT === 'ub' ? L.filter(catFaltaUbic) : fT === 'dir' ? L.filter(catFaltaDir) : fT === 'off' ? L.filter((x) => !x.on) : L;
    const on = Lf.filter((x) => x.on), off = Lf.filter((x) => !x.on);
    const fila = (x) => <div key={x.id} onClick={() => { setTi(x.id); setEdit(null); }} style={pcItemCard(ti === x.id, false, { opacity: x.on ? 1 : 0.6 })}><div style={{ flex: 1, minWidth: 0 }}><b style={{ fontSize: 13.5 }}>{x.nombre}</b><span style={{ display: 'block', fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>{catSubTaller(x)}</span></div>{!x.on ? pcTag('Inactivo') : <div style={{ display: 'flex', flexDirection: 'column', gap: 4, alignItems: 'flex-end' }}>{catTagsTaller(x, fT !== 'ub').map((z) => <CatTagFalta key={z} txt={z} />)}</div>}</div>;
    izq = <>
      {cat.revisar.length > 0 && !k && <div onClick={() => { setRev(true); setRi(null); }} style={{ background: '#fff2cc', border: '1px solid #ecd98f', color: '#7f6000', borderRadius: 12, padding: '10px 12px', display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', marginBottom: 10 }}><div style={{ flex: 1, fontSize: 12.5, lineHeight: 1.4 }}><b style={{ display: 'block', fontSize: 13.5 }}>{cat.revisar.length} {cat.revisar.length === 1 ? 'nombre por revisar' : 'nombres por revisar'}</b>Llegaron en órdenes o los escribió el mensajero.</div><b>Revisar ›</b></div>}
      <button type="button" onClick={() => setPedir({ t: 'Agregar taller', l: 'Nombre del taller', v: '', fn: (n) => ask('primary', 'Agregar taller', `Se agrega ${n} al catálogo. Luego le agregas sus sedes.`, 'Guardar', () => { const id = catId('t'); update((c) => { c.talleres.push({ id, nombre: n, on: true, sedes: [] }); ordenar(c); }); setTi(id); abrirForm(null); toast('Taller agregado'); }) })} style={{ display: 'block', width: '100%', border: `1px dashed ${TOKENS.borderInput}`, background: TOKENS.surface, borderRadius: 12, padding: 10, fontFamily: 'inherit', fontSize: 13, fontWeight: 800, color: TOKENS.primary, cursor: 'pointer' }}>＋ Agregar taller</button>
      {!k && <div style={{ marginTop: 10, border: `1px solid ${TOKENS.border}`, background: TOKENS.surface, borderRadius: 12, padding: '10px 12px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><span style={{ flex: 1, fontSize: 12.5, color: TOKENS.textMuted }}><b style={{ color: TOKENS.text }}>{conUbic} de {sedesTodas.length}</b> sedes con ubicación</span>{conUbic < sedesTodas.length && <button type="button" onClick={() => setFT('ub')} style={{ border: 0, background: 'none', color: TOKENS.primary, fontWeight: 700, fontSize: 12.5, cursor: 'pointer', fontFamily: 'inherit', padding: 0 }}>Ver las que faltan ›</button>}</div>
        <div style={{ height: 6, borderRadius: 99, background: TOKENS.surfaceLow, overflow: 'hidden', margin: '7px 0 9px' }}><div style={{ height: '100%', width: (sedesTodas.length ? conUbic / sedesTodas.length * 100 : 0) + '%', background: TOKENS.primary }} /></div>
        <div style={{ display: 'flex', gap: 6 }}><PcBtn style={{ flex: 1, padding: '6px 8px', fontSize: 12 }} onClick={descargarPlantilla}>⇩ Plantilla de ubicaciones</PcBtn><PcBtn style={{ flex: 1, padding: '6px 8px', fontSize: 12 }} onClick={() => fileRef.current && fileRef.current.click()}>⇧ Subir plantilla</PcBtn></div>
        <input ref={fileRef} type="file" accept=".xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" style={{ display: 'none' }} onChange={(e) => { const fl = e.target.files && e.target.files[0]; e.target.value = ''; if (fl) subirPlantilla(fl); }} />
      </div>}
      {fT !== 'off' && <><div style={{ ...pcLbl, margin: '14px 2px 8px' }}>{fT === 'ub' ? 'Con sedes sin ubicación' : fT === 'dir' ? 'Con sedes sin dirección' : 'Talleres activos'} · {on.length}</div>
      {on.map(fila)}
      {(fT === 'ub' || fT === 'dir') && !on.length && <div style={{ fontSize: 13, color: TOKENS.textMuted, textAlign: 'center', padding: 18, border: `1px dashed ${TOKENS.border}`, borderRadius: 12 }}>✓ Ningún taller pendiente.</div>}</>}
      {!L.length && <div style={{ fontSize: 13, color: TOKENS.textMuted }}>Ningún taller coincide.</div>}
      {off.length > 0 && (fT === 'todos' || fT === 'off') && <><div style={{ ...pcLbl, margin: '14px 2px 8px' }}>Inactivos · {off.length}</div>{off.map(fila)}</>}
    </>;
  } else {
    const L = cat.aseguradoras.filter((x) => !k || catNorm(x.nombre).includes(k) || x.alias.some((y) => catNorm(y).includes(k))).slice().sort((x, y) => (y.on - x.on) || (y.c - x.c));
    izq = <>
      <button type="button" onClick={() => setPedir({ t: 'Agregar aseguradora', l: 'Nombre corto', v: '', fn: (n) => ask('primary', 'Agregar aseguradora', `Se agrega ${n}.`, 'Guardar', () => { const id = catId('a'); update((c) => c.aseguradoras.push({ id, nombre: n, alias: [n.toUpperCase()], c: 0, on: true })); setAi(id); setAform(null); toast('Aseguradora agregada'); }) })} style={{ display: 'block', width: '100%', border: `1px dashed ${TOKENS.borderInput}`, background: TOKENS.surface, borderRadius: 12, padding: 10, fontFamily: 'inherit', fontSize: 13, fontWeight: 800, color: TOKENS.primary, cursor: 'pointer' }}>＋ Agregar aseguradora</button>
      <div style={{ ...pcLbl, margin: '14px 2px 8px' }}>Aseguradoras · {L.length}</div>
      {L.map((x) => <div key={x.id} onClick={() => { setAi(x.id); setAform(null); }} style={pcItemCard(ai === x.id, false, { opacity: x.on ? 1 : 0.6 })}><div style={{ flex: 1 }}><b style={{ fontSize: 13.5 }}>{x.nombre}</b><span style={{ display: 'block', fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>{x.c.toLocaleString('es-CO')} registros desde 2024{x.alias.length > 1 ? ` · ${x.alias.length} nombres` : ''}</span></div>{!x.on && pcTag('Inactiva')}</div>)}
    </>;
  }

  // Derecha
  let der;
  if (rev) {
    const r = nuevaRev;
    if (!r) der = vacio('✓ No hay nada por revisar.');else
    {
      const tx = cat.talleres.find((z) => z.nombre === r.taller);
      const pk = catNorm(pickQ || (r.taller || '').split(' ')[0]);
      const res = []; cat.talleres.forEach((x) => { if (!x.on) return; x.sedes.forEach((s) => { if (catNorm(x.nombre + ' ' + s.nombre).includes(pk)) res.push({ x, s }); }); });
      der =
      <div style={{ ...pcCard, padding: 18, maxWidth: 700 }}>
          <div style={pcLbl}>{r.motivo === 'mens' ? `Escrito por ${r.porNombre || 'el mensajero'}${r.placa ? ' · recogida de ' + r.placa : ''}` : 'Llega como'}</div>
          <div style={{ fontFamily: pcMono, fontSize: 16, fontWeight: 700, marginTop: 6, wordBreak: 'break-word' }}>{r.llega}</div>
          {r.motivo === 'hoja' && <><div style={{ marginTop: 14, fontSize: 14 }}>Se asigna a <b>{r.taller} · {r.sede}</b></div>
            <div style={{ marginTop: 12 }}><PcBtn tone="p" onClick={() => ask('primary', 'Confirmar', `${r.llega} se guarda como ${r.taller} · ${r.sede}.`, 'Confirmar', () => { update((c) => { sumarAlias(c, r.taller, r.sede, r.llega); quitarRev(c, r.id); }); setRi(null); toast('Guardado'); })}>Confirmar</PcBtn></div></>}
          {r.motivo === 'mens' && <div style={{ marginTop: 14 }}><PcBtn tone="p" onClick={() => ask('primary', 'Crear taller', `Se agrega ${r.taller}${r.sede && r.sede !== 'Sin sede' ? ' · ' + r.sede : ''} al catálogo. Luego le completas zona y ubicación.`, 'Guardar', () => { const id = catId('t'); update((c) => { c.talleres.push({ id, nombre: r.taller, on: true, sedes: [{ id: catId('s'), nombre: r.sede && r.sede !== 'Sin sede' ? r.sede : 'Principal', ciudad: 'Cali', zona: null, dir: '', ubic: null, lat: null, lng: null, alias: [r.llega] }] }); ordenar(c); quitarRev(c, r.id); }); setRev(false); setTab('t'); setTi(id); toast('Taller creado'); })}>Crear taller "{r.taller}"</PcBtn></div>}
          {r.motivo === 'sinsede' && tx && <div style={{ marginTop: 14 }}><PcBtn tone="p" onClick={() => { setRev(false); setTab('t'); setTi(tx.id); abrirForm(null, { alias: [r.llega], rv: r.id }); }}>Crear sede en {tx.nombre}</PcBtn></div>}
          <div style={{ ...pcLbl, marginTop: 20 }}>{r.motivo === 'hoja' ? '¿O es otro? Asígnalo a' : 'O asígnalo a una sede que ya existe'}</div>
          <input value={pickQ} onChange={(e) => setPickQ(e.target.value)} placeholder="Buscar taller o sede" style={{ ...inp, marginTop: 8 }} />
          <div style={{ marginTop: 8, maxHeight: 320, overflow: 'auto' }}>
            {res.slice(0, 30).map(({ x, s }) => <div key={s.id} onClick={() => ask('primary', 'Asignar', `${r.llega} se guarda como ${x.nombre} · ${s.nombre}.`, 'Guardar', () => { update((c) => { sumarAlias(c, x.nombre, s.nombre, r.llega); quitarRev(c, r.id); }); setRi(null); setPickQ(''); toast('Guardado'); })} style={pcItemCard(false, false, { marginBottom: 6, alignItems: 'center' })}><div style={{ flex: 1 }}><b style={{ fontSize: 13.5 }}>{x.nombre} · {s.nombre}</b><span style={{ display: 'block', fontSize: 12, color: TOKENS.textMuted }}>{catSedeSub(s)}</span></div><span style={{ color: TOKENS.primary, fontWeight: 800, fontSize: 12.5 }}>Asignar ›</span></div>)}
            {!res.length && <div style={{ fontSize: 13, color: TOKENS.textMuted }}>Nada coincide.</div>}
          </div>
          <div style={{ borderTop: `1px solid ${TOKENS.border}`, marginTop: 16, paddingTop: 12, display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{ flex: 1, fontSize: 12.5, color: TOKENS.textMuted }}>¿No es un taller o está mal escrito sin arreglo?</span>
            <PcBtn tone="r" onClick={() => ask('danger', 'Descartar', 'Se quita de Por revisar y no se agrega al catálogo. Los registros que lo usan no cambian. Si vuelve a llegar en una orden o recogida nueva, aparece otra vez.', 'Descartar', () => { update((c) => quitarRev(c, r.id)); setRi(null); setPickQ(''); toast('Descartado'); })}>Descartar</PcBtn>
          </div>
        </div>;
    }
  } else if (tab === 't') {
    if (!t) der = vacio('Escoge un taller de la lista para ver sus sedes.');else
    {
      const f = form, setF = (p) => setForm((x) => ({ ...x, ...p }));
      const estoyAqui = () => { if (!navigator.geolocation) { toast('Este equipo no comparte la ubicación', true); return; } navigator.geolocation.getCurrentPosition((p) => { const lat = +p.coords.latitude.toFixed(6), lng = +p.coords.longitude.toFixed(6); setF({ lat, lng, ubic: `https://maps.google.com/?q=${lat},${lng}`, enlace: '' }); }, () => toast('No se pudo tomar la ubicación', true), { enableHighAccuracy: true, timeout: 12000 }); };
      const usarEnlace = () => { const l = (f.enlace || '').trim(); if (!/^https?:\/\//.test(l)) { toast('Pega un enlace que empiece por https://', true); return; } const co = catCoordsDeEnlace(l); setF({ ubic: l, lat: co ? co.lat : null, lng: co ? co.lng : null, enlace: '' }); };
      const formSede = (s) =>
      <div key={s ? s.id : 'nueva'} style={{ ...pcCard, padding: 14, border: `1px solid ${TOKENS.primary}`, gridColumn: '1 / -1' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <PcCampo label="Nombre de la sede"><input autoFocus value={f.nombre} onChange={(e) => setF({ nombre: e.target.value })} placeholder="Ej: Norte, Kia, Calle 26" style={inp} /></PcCampo>
            <PcCampo label="Dirección"><input value={f.dir} onChange={(e) => setF({ dir: e.target.value })} placeholder="Ej: Av. 3N #44-90" style={inp} /></PcCampo>
            <PcCampo label="Ciudad"><div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', alignItems: 'center' }}><PcPills small value={f.ciudad} onChange={(v) => setF({ ciudad: v })} options={catCiudades().map((x) => x.n)} /><button type="button" onClick={() => pedirCiudad((n) => setF({ ciudad: n }))} style={{ border: `1px dashed ${TOKENS.borderInput}`, background: TOKENS.surface, color: TOKENS.primary, borderRadius: 9, padding: '6px 10px', fontFamily: 'inherit', fontSize: 12, fontWeight: 700, cursor: 'pointer' }}>＋ Otra ciudad</button></div></PcCampo>
            {f.ciudad === 'Cali' ? <PcCampo label="Zona"><PcPills small value={f.zona} onChange={(v) => setF({ zona: v })} options={['Norte', 'Sur']} /></PcCampo> : <div />}
            <PcCampo label="Ubicación" full>
              {f.ubic ? <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><span style={{ flex: 1, fontSize: 13, fontWeight: 700 }}>📍 Ubicación guardada · <a href={f.ubic} target="_blank" rel="noopener noreferrer" style={{ color: TOKENS.primary }}>Abrir en Maps ›</a></span><PcBtn style={{ padding: '5px 10px', fontSize: 12 }} onClick={() => setF({ ubic: null, lat: null, lng: null })}>Cambiar</PcBtn></div> :
              <div style={{ display: 'flex', gap: 8 }}><input value={f.enlace} onChange={(e) => setF({ enlace: e.target.value })} placeholder="Pega el enlace de Google Maps" style={{ ...inp, flex: 1 }} /><PcBtn onClick={usarEnlace} disabled={!f.enlace.trim()}>Usar enlace</PcBtn><PcBtn onClick={estoyAqui}>📍 Estoy aquí</PcBtn></div>}
            </PcCampo>
            {f.alias.length > 0 && <PcCampo label="Así llega en las órdenes" full>{chips(f.alias, (i) => setF({ alias: f.alias.filter((_, j) => j !== i) }))}</PcCampo>}
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
            <PcBtn onClick={() => { setEdit(null); setForm(null); }}>Cancelar</PcBtn>
            <PcBtn tone="p" disabled={!f.nombre.trim()} onClick={() => ask('primary', 'Guardar sede', `${t.nombre} · ${f.nombre.trim()} (${f.ciudad === 'Cali' ? f.zona : f.ciudad})`, 'Guardar', () => {
              const o = { id: s ? s.id : catId('s'), nombre: f.nombre.trim(), ciudad: f.ciudad, zona: f.ciudad === 'Cali' ? f.zona : null, dir: f.dir.trim(), ubic: f.ubic, lat: f.lat, lng: f.lng, alias: f.alias };
              update((c) => { const x = c.talleres.find((z) => z.id === t.id); const i = x.sedes.findIndex((z) => z.id === o.id); if (i >= 0) x.sedes[i] = o;else x.sedes.push(o); if (f.rv) quitarRev(c, f.rv); });
              setEdit(null); setForm(null); toast('Sede guardada');
            })}>Guardar</PcBtn>
            <span style={{ flex: 1 }} />
            {s && <PcBtn tone="r" onClick={() => ask('danger', 'Quitar sede', `Se quita ${s.nombre} de ${t.nombre}. Los registros viejos la conservan.`, 'Quitar', () => { update((c) => { const x = c.talleres.find((z) => z.id === t.id); x.sedes = x.sedes.filter((z) => z.id !== s.id); }); setEdit(null); setForm(null); toast('Sede quitada', true); })}>Quitar sede</PcBtn>}
          </div>
        </div>;
      der =
      <div style={{ maxWidth: 820 }}>
          {!t.on && <div style={{ background: '#fff2cc', border: '1px solid #ecd98f', color: '#7f6000', borderRadius: 12, padding: '10px 12px', fontSize: 12.5, marginBottom: 12 }}><b>Taller inactivo.</b> No le aparece al mensajero; los registros viejos lo conservan.</div>}
          <div style={{ ...pcCard, padding: 16, display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
            <div style={{ flex: 1 }}><div style={pcLbl}>Taller</div><div style={{ fontSize: 20, fontWeight: 800, marginTop: 2 }}>{t.nombre}</div></div>
            <PcBtn style={{ padding: '5px 10px', fontSize: 12 }} onClick={() => setPedir({ t: 'Nombre del taller', l: 'Nombre', v: t.nombre, fn: (n) => { if (n !== t.nombre) ask('primary', 'Guardar cambio', `El taller pasa a llamarse ${n}.`, 'Guardar', () => { update((c) => { c.talleres.find((z) => z.id === t.id).nombre = n; ordenar(c); }); toast('Cambios guardados'); }); } })}>✎ Editar nombre</PcBtn>
          </div>
          <div style={{ ...pcLbl, margin: '0 2px 8px' }}>Sedes · {t.sedes.length}</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, alignItems: 'start' }}>
            {t.sedes.map((s) => edit === s.id && form ? formSede(s) :
            <div key={s.id} style={{ ...pcCard, padding: 14, ...(t.on && (catSinUbic(s) || catSinDir(s)) ? { borderColor: CAT_FALTA.bd } : {}) }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><b style={{ flex: 1, fontSize: 15 }}>{s.nombre}</b>{t.sedes.length > 1 && <PcBtn style={{ padding: '4px 9px', fontSize: 11.5 }} onClick={() => setUnirS({ src: s, destId: t.sedes.find((z) => z.id !== s.id).id })}>⇄ Unir</PcBtn>}<PcBtn style={{ padding: '4px 9px', fontSize: 11.5 }} onClick={() => abrirForm(s)}>✎ Editar</PcBtn></div>
                <div style={{ display: 'grid', gridTemplateColumns: 'auto 1fr', gap: '6px 14px', fontSize: 13, marginTop: 8 }}>
                  <span style={{ color: TOKENS.textMuted }}>{s.ciudad === 'Cali' ? 'Zona' : 'Ciudad'}</span><b style={{ fontWeight: 600 }}>{s.ciudad === 'Cali' ? s.zona || '—' : s.ciudad}</b>
                  <span style={{ color: TOKENS.textMuted }}>Dirección</span><CatValorSede s={s} activo={t.on} k="dir" />
                  <span style={{ color: TOKENS.textMuted }}>Ubicación</span><CatValorSede s={s} activo={t.on} k="ub" />
                </div>
                {s.alias.length > 0 && <><div style={{ ...pcLbl, marginTop: 10 }}>Así llega en las órdenes</div>{chips(s.alias)}</>}
              </div>)}
            {edit === 'nueva' && form && formSede(null)}
          </div>
          {!t.sedes.length && edit !== 'nueva' && <div style={{ fontSize: 13, color: TOKENS.textMuted, padding: '6px 2px' }}>Este taller aún no tiene sedes.</div>}
          {edit !== 'nueva' && <button type="button" onClick={() => abrirForm(null)} style={{ display: 'block', width: '100%', border: `1px dashed ${TOKENS.borderInput}`, background: TOKENS.surface, borderRadius: 12, padding: 10, fontFamily: 'inherit', fontSize: 13, fontWeight: 800, color: TOKENS.primary, cursor: 'pointer', marginTop: 10 }}>＋ Agregar sede</button>}
          {(cat.unidos || []).filter((u) => u.destId === t.id).length > 0 && <div style={{ ...pcCard, padding: 14, marginTop: 14 }}>
            <div style={pcLbl}>Unidos a este taller</div>
            {(cat.unidos || []).filter((u) => u.destId === t.id).map((u) => <div key={u.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0', borderBottom: `1px solid ${TOKENS.border}`, fontSize: 13 }}>
              <span style={{ flex: 1 }}><b>{u.tipo === 'sede' ? `Sede ${u.src.nombre}` : u.src.nombre}</b> <span style={{ color: TOKENS.textMuted }}>· {u.pares.map((p2) => `${p2.de.s || 'sin sede'} → ${p2.a.s}`).join(' · ')} · {new Date(u.fecha).toLocaleDateString('es-CO')}</span></span>
              <PcBtn style={{ padding: '4px 10px', fontSize: 12 }} onClick={() => ask('primary', 'Deshacer unión', u.tipo === 'sede' ? `La sede ${u.src.nombre} vuelve a existir y sus registros vuelven a mostrarse con esa sede.` : `${u.src.nombre} vuelve a ser un taller aparte y sus registros vuelven a mostrarse con ese nombre.`, 'Deshacer', () => { if (window.catDeshacerUnion(u.id)) toast('Unión deshecha'); })}>Deshacer</PcBtn>
            </div>)}
          </div>}
          <div style={{ marginTop: 20, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            <PcBtn onClick={() => setUnir({ destId: '', mapa: {} })}>⇄ Unir con otro taller…</PcBtn>
            {t.on ?
            <PcBtn tone="r" onClick={() => ask('danger', 'Desactivar taller', `${t.nombre} deja de aparecerle al mensajero. Los registros viejos lo conservan y puedes reactivarlo cuando quieras.`, 'Desactivar', () => { update((c) => { c.talleres.find((z) => z.id === t.id).on = false; }); toast('Taller desactivado', true); })}>Desactivar taller</PcBtn> :
            <PcBtn tone="p" onClick={() => ask('primary', 'Reactivar taller', `${t.nombre} vuelve a aparecerle al mensajero.`, 'Reactivar', () => { update((c) => { c.talleres.find((z) => z.id === t.id).on = true; }); toast('Taller reactivado'); })}>Reactivar taller</PcBtn>}</div>
        </div>;
    }
  } else {
    if (!a) der = vacio('Escoge una aseguradora de la lista.');else
    {
      const f = aform && aform.id === a.id ? aform : { id: a.id, nombre: a.nombre, alias: [...a.alias], nuevo: '' };
      const setF = (p) => setAform({ ...f, ...p });
      der =
      <div style={{ ...pcCard, padding: 18, maxWidth: 700 }}>
          {!a.on && <div style={{ background: '#fff2cc', border: '1px solid #ecd98f', color: '#7f6000', borderRadius: 12, padding: '10px 12px', fontSize: 12.5, marginBottom: 12 }}><b>Aseguradora inactiva.</b> No aparece al registrar.</div>}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <PcCampo label="Nombre corto"><input value={f.nombre} onChange={(e) => setF({ nombre: e.target.value })} style={inp} /></PcCampo>
            <PcCampo label="Registros desde 2024"><div style={{ fontSize: 20, fontWeight: 800, paddingTop: 6 }}>{a.c.toLocaleString('es-CO')}</div></PcCampo>
            <PcCampo label="Así llega en las órdenes" full nota={a.alias.some((x) => /liberty/i.test(x)) ? 'Liberty ahora es HDI: sus registros viejos se ven como HDI.' : null}>
              {chips(f.alias, f.alias.length > 1 ? (i) => setF({ alias: f.alias.filter((_, j) => j !== i) }) : null)}
              <div style={{ display: 'flex', gap: 8, marginTop: 8 }}><input value={f.nuevo} onChange={(e) => setF({ nuevo: e.target.value })} placeholder="Agregar otro nombre" style={{ ...inp, flex: 1 }} /><PcBtn onClick={() => { const x = f.nuevo.trim(); if (x) setF({ alias: [...f.alias, x.toUpperCase()], nuevo: '' }); }}>＋</PcBtn></div>
            </PcCampo>
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 18 }}>
            <PcBtn tone="p" disabled={!f.nombre.trim()} onClick={() => ask('primary', 'Guardar aseguradora', `${f.nombre.trim()} · ${f.alias.length} ${f.alias.length === 1 ? 'nombre' : 'nombres'} como llega.`, 'Guardar', () => { update((c) => { const x = c.aseguradoras.find((z) => z.id === a.id); x.nombre = f.nombre.trim(); x.alias = f.alias; }); setAform(null); toast('Cambios guardados'); })}>Guardar</PcBtn>
            <span style={{ flex: 1 }} />
            {a.on ? <PcBtn tone="r" onClick={() => ask('danger', 'Desactivar aseguradora', `${a.nombre} deja de aparecer al registrar. Los registros viejos la conservan.`, 'Desactivar', () => { update((c) => { c.aseguradoras.find((z) => z.id === a.id).on = false; }); toast('Aseguradora desactivada', true); })}>Desactivar aseguradora</PcBtn> :
            <PcBtn tone="p" onClick={() => ask('primary', 'Reactivar aseguradora', `${a.nombre} vuelve a aparecer al registrar.`, 'Reactivar', () => { update((c) => { c.aseguradoras.find((z) => z.id === a.id).on = true; }); toast('Aseguradora reactivada'); })}>Reactivar aseguradora</PcBtn>}
          </div>
        </div>;
    }
  }
  if (!rev && tab === 'c') {
    const x = ciuL.find((z) => catNorm(z.n) === catNorm(ci)) || ciuL[0];
    const ts = x ? tallCiu(x.n) : [];
    der = !x ? vacio('Escoge una ciudad.') :
    <div style={{ ...pcCard, padding: 18, maxWidth: 720 }}>
        <b style={{ fontSize: 18 }}>{x.n}</b>
        <div style={{ display: 'grid', gap: 10, marginTop: 14 }}>
          {[['cob', 'Cobertura', 'Aquí se cotiza y se repara el rin (subastas y Orbika).'], ['men', 'El mensajero recoge', 'César va en persona a los talleres de esta ciudad. Si no, los rines llegan por transportadora o los trae el taller, y al entregar se despachan por transportadora (César los lleva).']].map(([kk, t2, d2]) =>
          <div key={kk} style={{ display: 'flex', gap: 12, alignItems: 'flex-start', border: `1px solid ${TOKENS.border}`, borderRadius: 12, padding: '12px 14px' }}>
              {swCiu(!!x[kk], () => ask('primary', `${t2} · ${x.n}`, x[kk] ? `Se quita "${t2.toLowerCase()}" en ${x.n}.` : `Se activa "${t2.toLowerCase()}" en ${x.n}.`, 'Guardar', () => { cambiarCiudad(x.n, { [kk]: !x[kk] }); toast('Ciudad actualizada'); }))}
              <div><b style={{ fontSize: 13.5 }}>{t2} · {x[kk] ? 'Sí' : 'No'}</b><div style={{ fontSize: 12.5, color: TOKENS.textMuted, marginTop: 2, lineHeight: 1.45 }}>{d2}</div></div>
            </div>)}
        </div>
        <div style={{ ...pcLbl, margin: '18px 0 8px' }}>Sedes en {x.n} · {ts.length}</div>
        {ts.length ? <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>{ts.map(({ x: tt, s: ss }) => <button key={ss.id} type="button" onClick={() => { setTab('t'); setTi(tt.id); setEdit(null); }} style={{ border: `1px solid ${TOKENS.border}`, background: TOKENS.surfaceLow, borderRadius: 9, padding: '5px 10px', fontFamily: 'inherit', fontSize: 12.5, cursor: 'pointer', color: TOKENS.text }}>{tt.nombre} · {ss.nombre}</button>)}</div> : <div style={{ fontSize: 13, color: TOKENS.textMuted }}>Ninguna sede tiene esta ciudad todavía. Se la pones al editar la sede del taller.</div>}
        {x.n === 'Cali' && <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 12 }}>En Cali las sedes también llevan zona (Norte / Sur).</div>}
      </div>;
  }
  if (!rev && tab === 's') { izq = <PcCatServIzq sub={sub} setSub={setSub} />; der = <PcCatServDer key={sub} sub={sub} toast={toast} />; }
  const cabeza = rev ? <div style={pcLbl}>Por revisar · {cat.revisar.length}</div> : <>
    <PcTabs value={tab} onChange={(v) => { setTab(v); setQ(''); }} options={[['t', 'Talleres', null], ['a', 'Aseguradoras', null], ['c', 'Ciudades', null], ['s', 'Servicios', null]]} />
    {tab !== 's' && <input value={q} onChange={(e) => setQ(e.target.value)} placeholder={tab === 't' ? 'Buscar taller, sede o como llega' : tab === 'c' ? 'Buscar ciudad' : 'Buscar aseguradora'} style={{ ...pcInp, width: '100%', marginTop: 10 }} />}
    {tab === 't' && (() => { const act = cat.talleres.filter((x) => x.on && !esParticular(x.nombre)); const n = { todos: act.length, ub: act.filter(catFaltaUbic).length, dir: act.filter(catFaltaDir).length, off: cat.talleres.filter((x) => !x.on).length };
      return <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 10 }}>{[['todos', 'Todos'], ['ub', 'Sin ubicación'], ['dir', 'Sin dirección'], ['off', 'Inactivos']].map(([k2, l2]) => <button key={k2} type="button" onClick={() => setFT(k2)} style={{ border: `1px solid ${fT === k2 ? TOKENS.primary : TOKENS.borderInput}`, background: fT === k2 ? TOKENS.primary : TOKENS.surface, color: fT === k2 ? '#fff' : TOKENS.text, borderRadius: 99, padding: '5px 11px', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 700, cursor: 'pointer' }}>{l2} <span style={{ opacity: 0.7 }}>{n[k2]}</span></button>)}</div>; })()}
  </>;
  return (
    <>
      {pcDosColumnas(420, cabeza, izq, der)}
      {pedir &&
      <div onClick={() => setPedir(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(11,28,48,0.5)', zIndex: 1000, display: 'grid', placeItems: 'center' }}>
          <div onClick={(e) => e.stopPropagation()} style={{ background: TOKENS.surface, borderRadius: 16, padding: 20, width: 380 }}>
            <b style={{ fontSize: 17 }}>{pedir.t}</b>
            <div style={{ marginTop: 12 }}><PcCampo label={pedir.l}><input autoFocus list={pedir.sug ? 'pc-ciudades-co' : undefined} value={pedir.v} onChange={(e) => setPedir({ ...pedir, v: e.target.value })} style={{ ...pcInp, width: '100%' }} />{pedir.sug && <datalist id="pc-ciudades-co">{CAT_CIUDADES_CO.filter((n) => !ciuL.some((z) => catNorm(z.n) === catNorm(n))).map((n) => <option key={n} value={n} />)}</datalist>}</PcCampo></div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 16 }}><PcBtn onClick={() => setPedir(null)}>Cancelar</PcBtn><PcBtn tone="p" disabled={!pedir.v.trim()} onClick={() => { const n = pedir.v.trim(), fn = pedir.fn; setPedir(null); fn(n); }}>Seguir</PcBtn></div>
          </div>
        </div>}
      {unirS && t && (() => {
        const ds = t.sedes.find((z) => z.id === unirS.destId);
        const Sel = window.Select;
        return <div onClick={() => setUnirS(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(11,28,48,0.5)', zIndex: 1000, display: 'grid', placeItems: 'center' }}>
          <div onClick={(e) => e.stopPropagation()} style={{ background: TOKENS.surface, borderRadius: 16, padding: 20, width: 440 }}>
            <b style={{ fontSize: 17 }}>Unir la sede {unirS.src.nombre}</b>
            <div style={{ fontSize: 12.5, color: TOKENS.textMuted, marginTop: 4, lineHeight: 1.45 }}>Para cuando una sede no existe y quedó por error (por ejemplo, Renovautos solo tiene sede Sur).</div>
            <div style={{ marginTop: 14 }}><PcCampo label={`${t.nombre} · ${unirS.src.nombre} es en realidad`}>{Sel && <Sel value={unirS.destId} options={t.sedes.filter((z) => z.id !== unirS.src.id).map((z) => ({ value: z.id, label: `${t.nombre} · ${z.nombre}` }))} onChange={(v) => setUnirS({ ...unirS, destId: v })} />}</PcCampo></div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 18 }}>
              <PcBtn onClick={() => setUnirS(null)}>Cancelar</PcBtn>
              <PcBtn tone="p" disabled={!ds} onClick={() => { const src = unirS.src; setUnirS(null);
                ask('primary', 'Unir sedes', `${t.nombre} · ${src.nombre} se une a ${t.nombre} · ${ds.nombre}. Sus nombres en las órdenes pasan a ${ds.nombre}, la sede ${src.nombre} sale del catálogo y sus registros se muestran como ${ds.nombre}. Se puede deshacer en esta misma ficha.`, 'Unir', () => { if (window.catUnirSede(t.id, src.id, ds.id)) toast(`Sede ${src.nombre} unida con ${ds.nombre}`); }); }}>Seguir</PcBtn>
            </div>
          </div>
        </div>;
      })()}
      {unir && t && (() => {
        const dest = cat.talleres.find((x) => x.id === unir.destId);
        const opts = cat.talleres.filter((x) => x.id !== t.id && x.on).map((x) => ({ value: x.id, label: x.nombre }));
        const sedeDe = (ss) => dest ? (dest.sedes.find((z) => z.id === unir.mapa[ss.id]) || dest.sedes.find((z) => catNorm(z.nombre) === catNorm(ss.nombre)) || dest.sedes[0]) : null;
        const Sel = window.Select;
        const listo = dest && dest.sedes.length;
        const txt = dest ? `${t.nombre} se une a ${dest.nombre}: ${(t.sedes.length ? t.sedes : [{ nombre: 'sin sede' }]).map((ss) => `${ss.nombre} → ${(sedeDe(ss) || {}).nombre}`).join(', ')}. Los nombres con que llega en las órdenes pasan a ${dest.nombre}, ${t.nombre} sale de la lista y sus registros se muestran como ${dest.nombre}. Se puede deshacer desde la ficha de ${dest.nombre}.` : '';
        return <div onClick={() => setUnir(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(11,28,48,0.5)', zIndex: 1000, display: 'grid', placeItems: 'center' }}>
          <div onClick={(e) => e.stopPropagation()} style={{ background: TOKENS.surface, borderRadius: 16, padding: 20, width: 480 }}>
            <b style={{ fontSize: 17 }}>Unir {t.nombre} con otro taller</b>
            <div style={{ fontSize: 12.5, color: TOKENS.textMuted, marginTop: 4, lineHeight: 1.45 }}>Para cuando un taller está repetido con otro nombre (por ejemplo, Honda es en realidad Fanalca Autoceiba).</div>
            <div style={{ marginTop: 14 }}><PcCampo label="Es en realidad">{Sel && <Sel value={unir.destId} options={opts} placeholder="Seleccionar taller" searchable onChange={(v) => setUnir({ destId: v, mapa: {} })} />}</PcCampo></div>
            {dest && !dest.sedes.length && <div style={{ fontSize: 12.5, color: TOKENS.dangerText, marginTop: 8 }}>{dest.nombre} no tiene sedes. Agrégale una sede primero.</div>}
            {listo && t.sedes.map((ss) => <div key={ss.id} style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, alignItems: 'center', marginTop: 10 }}>
              <span style={{ fontSize: 13 }}>{t.nombre} · <b>{ss.nombre}</b> pasa a</span>
              {Sel && <Sel value={(sedeDe(ss) || {}).id} options={dest.sedes.map((z) => ({ value: z.id, label: `${dest.nombre} · ${z.nombre}` }))} onChange={(v) => setUnir({ ...unir, mapa: { ...unir.mapa, [ss.id]: v } })} />}
            </div>)}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 18 }}>
              <PcBtn onClick={() => setUnir(null)}>Cancelar</PcBtn>
              <PcBtn tone="p" disabled={!listo} onClick={() => { const mapa = {}; t.sedes.forEach((ss) => { mapa[ss.id] = (sedeDe(ss) || {}).id; }); const dId = dest.id, nom = dest.nombre; setUnir(null);
                ask('primary', 'Unir talleres', txt, 'Unir', () => { if (window.catUnirTaller(t.id, dId, mapa)) { setTi(dId); setEdit(null); toast(`Unido con ${nom}`); } }); }}>Seguir</PcBtn>
            </div>
          </div>
        </div>;
      })()}
      {impRes &&
      <div onClick={() => setImpRes(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(11,28,48,0.5)', zIndex: 1000, display: 'grid', placeItems: 'center' }}>
          <div onClick={(e) => e.stopPropagation()} style={{ background: TOKENS.surface, borderRadius: 16, padding: 20, width: 440, maxHeight: '80vh', overflow: 'auto' }}>
            <b style={{ fontSize: 17 }}>Plantilla cargada</b>
            <div style={{ display: 'grid', gap: 6, marginTop: 12, fontSize: 13.5 }}>
              <div>✓ <b>{impRes.coords}</b> {impRes.coords === 1 ? 'sede quedó' : 'sedes quedaron'} con ubicación</div>
              {impRes.dir > 0 && <div>✓ <b>{impRes.dir}</b> {impRes.dir === 1 ? 'dirección actualizada' : 'direcciones actualizadas'}</div>}
              {impRes.nuevosT.length > 0 && <div>✓ <b>{impRes.nuevosT.length}</b> {impRes.nuevosT.length === 1 ? 'taller nuevo' : 'talleres nuevos'}: <span style={{ color: TOKENS.textMuted }}>{impRes.nuevosT.join(', ')}</span></div>}
              {impRes.inactivos.length > 0 && <div style={{ color: TOKENS.textMuted }}>· {impRes.inactivos.length} {impRes.inactivos.length === 1 ? 'taller inactivo no se tocó' : 'talleres inactivos no se tocaron'}: {impRes.inactivos.join(', ')}. Si vas a usar alguno, reactívalo primero.</div>}
              {impRes.nuevasS.length > 0 && <div>✓ <b>{impRes.nuevasS.length}</b> {impRes.nuevasS.length === 1 ? 'sede nueva' : 'sedes nuevas'}: <span style={{ color: TOKENS.textMuted }}>{impRes.nuevasS.slice(0, 12).join(' · ')}{impRes.nuevasS.length > 12 ? ' …' : ''}</span></div>}
              {[['malas', 'Coordenadas que no se entendieron o no caen en Colombia'], ['sinCoord', 'Enlaces sin coordenadas (enlaces cortos de "Compartir"): se guardó el enlace; usa el clic derecho en Maps para las coordenadas'], ['noEsta', 'Filas con un ID que no existe en el catálogo (no se cambió nada)']].filter(([kk]) => impRes[kk].length).map(([kk, t2]) => <div key={kk} style={{ marginTop: 6 }}><div style={{ color: '#8a5a00', fontWeight: 700 }}>{impRes[kk].length} · {t2}</div><div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>{impRes[kk].slice(0, 12).join(' · ')}{impRes[kk].length > 12 ? ' …' : ''}</div></div>)}
            </div>
            <PcBtn tone="p" style={{ width: '100%', marginTop: 16 }} onClick={() => setImpRes(null)}>Listo</PcBtn>
          </div>
        </div>}
      {conf && Modal && <Modal tone={conf.tone} icon={conf.tone === 'danger' ? I.alert(24, TOKENS.danger) : I.check(24, TOKENS.primary)} title={conf.t} message={conf.m} confirmLabel={conf.ok} onDismiss={() => setConf(null)} onConfirm={() => { const fn = conf.fn; setConf(null); fn(); }} />}
    </>);
}

// ─── Panel ───────────────────────────────────────────────────────────────
// ─── Mi perfil en el PC (17/11/2026): dos columnas. Izquierda: tarjeta con foto y datos. Derecha: preferencias, operación, pruebas y soporte.
function PcPerfil({ ir, onLogout, toast }) {
  const [perfil, setPerfil] = React.useState(loadPerfil);
  const [prefs, setPrefs] = React.useState(loadPrefs);
  const [borrador, setBorrador] = React.useState(null);
  const [confirmar, setConfirmar] = React.useState(null);
  const [expand, setExpand] = React.useState(null);
  const [demoMsg, setDemoMsg] = React.useState('');
  const Modal = window.ConfirmActionModal;
  const yo = (window.usuarioActual && window.usuarioActual()) || {};
  const setPref = (patch) => { const n = { ...prefs, ...patch }; setPrefs(n); savePrefs(n); };
  const campo = (k) => (v) => setBorrador((b) => ({ ...b, [k]: v }));
  const guardar = () => { const p = { ...borrador, nombre: (borrador.nombre || '').trim() || perfil.nombre }; savePerfil(p); setPerfil(p); setBorrador(null); setConfirmar(null); toast && toast('Datos guardados'); };
  const card = { background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 16, padding: 20 };
  const h4 = (t) => <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: '0.07em', textTransform: 'uppercase', color: TOKENS.textMuted, marginBottom: 6 }}>{t}</div>;
  const ico = (i) => <span style={{ width: 34, height: 34, borderRadius: 10, background: TOKENS.surfaceLow, display: 'grid', placeItems: 'center', flex: 'none' }}>{i}</span>;
  const fila = (i, t, sub, der, primera) => <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 0', borderTop: primera ? 'none' : `1px solid ${TOKENS.border}` }}>{ico(i)}<div style={{ flex: 1, minWidth: 0 }}><b style={{ display: 'block', fontSize: 13.5 }}>{t}</b><span style={{ fontSize: 12, color: TOKENS.textMuted }}>{sub}</span></div>{der}</div>;
  const link = (t, on) => <button type="button" onClick={on} style={{ border: 0, background: 'none', color: TOKENS.primary, fontFamily: 'inherit', fontSize: 13, fontWeight: 700, cursor: 'pointer', padding: 0, whiteSpace: 'nowrap' }}>{t}</button>;
  const pill = (v, l) => <button key={v} type="button" onClick={() => setPref({ mapa: v })} style={{ border: 0, borderRadius: 999, padding: '6px 14px', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 700, cursor: 'pointer', background: prefs.mapa === v ? '#fff' : 'transparent', color: prefs.mapa === v ? TOKENS.primary : TOKENS.textMuted, boxShadow: prefs.mapa === v ? '0 1px 3px rgba(22,35,63,.15)' : 'none' }}>{l}</button>;
  const dato = (k, v) => <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, padding: '9px 0', borderTop: `1px solid ${TOKENS.border}`, fontSize: 13 }}><span style={{ color: TOKENS.textMuted }}>{k}</span><b style={{ fontWeight: 600, textAlign: 'right' }}>{v || '—'}</b></div>;
  const cat = window.loadCatalogo ? window.loadCatalogo() : { talleres: [], aseguradoras: [], revisar: [] };
  const nDias = window.loadDiasEspeciales ? window.loadDiasEspeciales().length : 0;
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '320px minmax(0, 1fr)', gap: 18, alignItems: 'start', maxWidth: 1100 }}>
      <div style={card}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', gap: 4, marginBottom: 14 }}>
          <ProfileAvatar size={88} editable />
          <b style={{ fontSize: 17, marginTop: 8 }}>{perfil.nombre}</b>
          <span style={{ fontSize: 12.5, color: TOKENS.textMuted }}>Administrador{yo.usuario ? ' · usuario ' + yo.usuario : ''}</span>
          <span style={{ fontSize: 11.5, color: TOKENS.textSubtle }}>Toca la foto para cambiarla</span>
        </div>
        {!borrador ? <>
          {dato('Teléfono', perfil.telefono)}
          {dato('Identificación', perfil.identificacion)}
          <PcBtn onClick={() => setBorrador({ ...perfil })} style={{ width: '100%', marginTop: 14 }}>Editar datos</PcBtn>
        </> :
        <div style={{ display: 'grid', gap: 12, borderTop: `1px solid ${TOKENS.border}`, paddingTop: 14 }}>
          <div><FieldLabel upper>Nombre</FieldLabel><TextInput value={borrador.nombre} onChange={campo('nombre')} placeholder="Nombre completo" /></div>
          <div><FieldLabel upper>Teléfono</FieldLabel><TextInput value={borrador.telefono} onChange={campo('telefono')} type="tel" placeholder="+57 300 000 0000" /></div>
          <div><FieldLabel upper>Identificación</FieldLabel><TextInput value={borrador.identificacion} onChange={campo('identificacion')} placeholder="C.C. 0000000" /></div>
          <div style={{ display: 'flex', gap: 8 }}><PcBtn onClick={() => setBorrador(null)} style={{ flex: 1 }}>Cancelar</PcBtn><PcBtn tone="p" onClick={() => setConfirmar('guardar')} style={{ flex: 1 }}>Guardar</PcBtn></div>
        </div>}
        <PcBtn tone="r" onClick={() => setConfirmar('salir')} style={{ width: '100%', marginTop: 12 }}>Cerrar sesión</PcBtn>
      </div>
      <div style={{ display: 'grid', gap: 18, minWidth: 0 }}>
        <div style={card}>
          {h4('Preferencias')}
          {fila(I.route(17, TOKENS.textMuted), 'App de mapas', 'Para abrir la navegación de cada parada',
            <div style={{ display: 'inline-flex', background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 999, padding: 3, gap: 2 }}>{pill('google', 'Google Maps')}{pill('waze', 'Waze')}</div>, true)}
          {fila(I.user(17, TOKENS.textMuted), 'WhatsApp de despacho', 'Lo usan los mensajeros para contactarte y al compartir paradas',
            <div style={{ width: 220 }}><TextInput value={prefs.waNumero} onChange={(v) => setPref({ waNumero: v })} type="tel" placeholder="+57 300 000 0000" /></div>)}
        </div>
        <div style={card}>
          {h4('Operación · afecta el cálculo de plazos de toda la flota')}
          {fila(I.cal(17, TOKENS.textMuted), 'Días no laborables', `Excepciones del calendario hábil · ${nDias} ${nDias === 1 ? 'día' : 'días'}`, link(expand === 'dias' ? 'Cerrar' : 'Editar', () => setExpand(expand === 'dias' ? null : 'dias')), true)}
          {expand === 'dias' && <div style={{ border: `1px solid ${TOKENS.border}`, borderRadius: 12, marginBottom: 8, overflow: 'hidden' }}><DiasNoLaborablesEditor onChange={() => setExpand('dias')} /></div>}
          {fila(I.clock(17, TOKENS.textMuted), 'Parámetros de plazo', 'Hora de corte y días hábiles', link(expand === 'sla' ? 'Cerrar' : 'Editar', () => setExpand(expand === 'sla' ? null : 'sla')))}
          {expand === 'sla' && <div style={{ border: `1px solid ${TOKENS.border}`, borderRadius: 12, marginBottom: 8, overflow: 'hidden' }}><SlaParamsEditor /></div>}
          {fila(I.pkg(17, TOKENS.textMuted), 'Catálogos', `${cat.talleres.filter((t) => t.on).length} talleres · ${cat.aseguradoras.filter((a) => a.on).length} aseguradoras` + (cat.revisar.length ? ` · ${cat.revisar.length} por revisar` : ''), link('Ir a Catálogos ›', () => ir('catalogos')))}
        </div>
        <div style={card}>
          {h4('Pruebas y soporte')}
          {window.simularAvanceRuta && fila(I.truck(17, TOKENS.textMuted), 'Simular avance de la ruta', demoMsg || 'Mientras no hay un celular real conectado', link('Simular', () => setDemoMsg(window.simularAvanceRuta())), true)}
          {window.borrarDatosPrueba && fila(I.trash(17, TOKENS.danger), 'Borrar datos de prueba', window.sinDatosEjemplo && window.sinDatosEjemplo() ? <>Este equipo está sin datos de ejemplo · <a onClick={() => setConfirmar('ejemplo')} style={{ color: TOKENS.primary, fontWeight: 600, cursor: 'pointer' }}>Volver a los de ejemplo</a></> : 'Placas, entregas, rutas, servicios y avisos de este equipo', <button type="button" onClick={() => setConfirmar('borrar')} style={{ background: TOKENS.surface, border: `1.5px solid ${TOKENS.borderInput}`, color: TOKENS.danger, borderRadius: 10, fontFamily: 'inherit', fontWeight: 700, fontSize: 12.5, cursor: 'pointer', padding: '6px 11px', display: 'inline-flex', alignItems: 'center', gap: 6 }}>{I.trash(14, TOKENS.danger)} Borrar</button>)}
          {fila(I.doc(17, TOKENS.textMuted), 'Acerca de Rodando', 'Control de mensajería de Salvallantas', <span style={{ fontSize: 12, fontWeight: 600, color: TOKENS.textSubtle }}>v1.0</span>, !window.simularAvanceRuta)}
        </div>
      </div>
      {confirmar === 'guardar' && Modal &&
      <Modal icon={I.save(24, TOKENS.primary)} tone="primary" title="¿Guardar tus datos?" message="Se actualizarán tu nombre, teléfono e identificación."
        cancelLabel="Revisar" confirmLabel="Guardar" onConfirm={guardar} onDismiss={() => setConfirmar(null)} />}
      {confirmar === 'borrar' && Modal &&
      <Modal icon={I.trash(22, TOKENS.danger)} tone="danger" title="Borrar datos de prueba" message="Se borran de este equipo las placas, entregas, rutas, servicios, garantías, avisos y solicitudes. Usuarios, catálogos, plazos y tu perfil se quedan. No se puede deshacer."
        confirmLabel="Borrar" onConfirm={() => { setConfirmar(null); window.borrarDatosPrueba(); }} onDismiss={() => setConfirmar(null)} />}
      {confirmar === 'ejemplo' && Modal &&
      <Modal icon={I.check(24, TOKENS.primary)} tone="primary" title="Volver a los datos de ejemplo" message="Se borra lo que haya en este equipo y vuelven las placas y rutas de ejemplo."
        confirmLabel="Volver" onConfirm={() => { setConfirmar(null); window.volverDatosEjemplo(); }} onDismiss={() => setConfirmar(null)} />}
      {confirmar === 'salir' && Modal &&
      <Modal icon={I.logout(24, TOKENS.danger)} tone="danger" title="¿Cerrar sesión?" message="Para volver a entrar necesitarás tu usuario y contraseña."
        confirmLabel="Cerrar sesión" onConfirm={() => { setConfirmar(null); onLogout && onLogout(); }} onDismiss={() => setConfirmar(null)} />}
    </div>);
}

const PC_SECCIONES = [['inicio', 'Inicio', 'home'], ['registros', 'Registros', 'doc'], ['seguimiento', 'Novedades', 'clock'], ['rutas', 'Rutas', 'pin'], ['informes', 'Informes', 'chart'], ['catalogos', 'Catálogos', 'pkg'], ['usuarios', 'Usuarios', 'user']];
function PanelPC({ onLogout, onEditTicket, embed, onVistaCelular }) {
  useRefrescoPC();
  const [sec, setSec] = React.useState('inicio');
  // Barra lateral contraíble (17/11/2026): se recuerda en este equipo.
  const [mini, setMini] = React.useState(() => { try { return localStorage.getItem('rodando.pcMenuMini') === '1'; } catch (e) { return false; } });
  const cambiarMini = () => setMini((m) => { const n = !m; try { localStorage.setItem('rodando.pcMenuMini', n ? '1' : '0'); } catch (e) {} return n; });
  const anchoMenu = mini ? 68 : 232;
  window.rdAnchoMenu = anchoMenu;
  const [catInicial, setCatInicial] = React.useState('lista');
  const [filtro, setFiltro] = React.useState({ tab: 'todos' });
  const [pop, setPop] = React.useState(null);
  const [toastMsg, setToastMsg] = React.useState(null);
  const toast = (msg, rojo) => { setToastMsg({ msg, rojo }); clearTimeout(toast.t); toast.t = setTimeout(() => setToastMsg(null), 2400); };
  const [segKey, setSegKey] = React.useState(0);
  React.useEffect(() => { const f = (e) => { setSegKey((k) => k + 1); ir(e.detail); }; window.addEventListener('pc-ir', f); return () => window.removeEventListener('pc-ir', f); }, []);
  const ir = (s, f, menu) => {
    setPop(null);
    if (s === 'catalogos-revisar') { setCatInicial('revisar'); setSec('catalogos'); return; }
    if (s === 'catalogos') setCatInicial('lista');
    // 21/11/2026: desde el menú, Registros conserva sus filtros (memoria por sección).
    if (s === 'registros' && !menu) setFiltro({ tab: 'todos', ...(f || {}) });
    setSec(s);
    const b = document.getElementById('pc-body'); if (b) b.scrollTop = 0;
  };
  // Las pantallas del celular navegan con sus propios nombres.
  const navCel = (id) => ({ dashboard: 'inicio', consultar: 'registros', entregar: 'registros', recoger: 'registros', rutas: 'rutas', notificaciones: 'notificaciones', ajustes: 'perfil' })[id] && ir(({ dashboard: 'inicio', consultar: 'registros', entregar: 'registros', recoger: 'registros', rutas: 'rutas', notificaciones: 'notificaciones', ajustes: 'perfil' })[id]);
  React.useEffect(() => { const f = (e) => { if (pop && !e.target.closest('[data-pc-pop]')) setPop(null); }; document.addEventListener('mousedown', f); return () => document.removeEventListener('mousedown', f); }, [pop]);
  const regs = pcRegistros();
  const yo = (window.usuarioActual && window.usuarioActual()) || {};
  const foto = window.useAvatar ? window.useAvatar() : '';
  const ms = window.mensajerosApp ? window.mensajerosApp() : [];
  const notasPend = window.loadEncargos ? window.loadEncargos().filter((e) => e.estado !== 'hecho').length : 0;
  const nAvisos = pcAvisosAdmin().reduce((a, x) => a + (x.id === 'tal' ? (window.catPendientesMensajero ? window.catPendientesMensajero().length : 1) : 1), 0);
  const nRevisar = window.loadCatalogo ? window.loadCatalogo().revisar.length : 0;
  const nSeg = typeof servPendientes === 'function' ? servPendientes(regs).length : 0;
  const titulos = { inicio: 'Inicio', registros: 'Registros', seguimiento: 'Novedades', rutas: 'Rutas', informes: 'Informes', catalogos: 'Catálogos', usuarios: 'Usuarios', notificaciones: 'Notificaciones', perfil: 'Mi perfil' };
  const hoyLargo = (() => { const t = new Date().toLocaleDateString('es-CO', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' }); return t.charAt(0).toUpperCase() + t.slice(1); })();
  const iconoBtn = (id, icon, n, color, label) =>
  <button type="button" data-pc-pop onClick={() => setPop(pop === id ? null : id)} aria-label={label} title={label} style={{ position: 'relative', width: 40, height: 40, borderRadius: 10, border: 0, cursor: 'pointer', display: 'grid', placeItems: 'center', background: pop === id ? TOKENS.primaryBg : 'transparent' }}>
      {icon}
      {n > 0 && <span style={{ position: 'absolute', top: 1, right: -3, minWidth: 15, height: 15, padding: '0 3px', borderRadius: 99, background: color, color: '#fff', fontSize: 9.5, fontWeight: 800, lineHeight: '15px', textAlign: 'center', border: `2px solid ${TOKENS.bg}`, boxSizing: 'content-box', pointerEvents: 'none' }}>{n}</span>}
    </button>;
  const libreta = <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={TOKENS.text} strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"><rect x="5" y="3.5" width="14" height="17" rx="2.2" /><path d="M9 8.5h6M9 12h6M9 15.5h3.5" /></svg>;
  let cuerpo;
  if (embed) cuerpo = <PcColumna>{embed}</PcColumna>;else
  if (sec === 'inicio') cuerpo = <PcInicio regs={regs} ir={ir} />;else
  if (sec === 'registros') cuerpo = <PcRegistros regs={regs} filtro={filtro} setFiltro={setFiltro} onEditTicket={onEditTicket} toast={toast} />;else
  if (sec === 'seguimiento') cuerpo = <PcSeguimiento key={segKey} regs={regs} toast={toast} ir={ir} />;else
  if (sec === 'informes') cuerpo = <PcInformes regs={regs} toast={toast} />;else
  if (sec === 'usuarios') cuerpo = <PcUsuarios toast={toast} />;else
  if (sec === 'rutas') cuerpo = <PcRutas toast={toast} />;else
  if (sec === 'catalogos') cuerpo = <PcCatalogos key={catInicial} inicial={catInicial} toast={toast} />;else
  if (sec === 'notificaciones') cuerpo = <PcColumna><NotificacionesScreen role="admin" onBack={() => ir('inicio')} onNav={navCel} /></PcColumna>;else
  if (sec === 'perfil') cuerpo = <PcPerfil ir={ir} onLogout={onLogout} toast={toast} />;
  return (
    <div style={{ display: 'grid', gridTemplateColumns: `${anchoMenu}px 1fr`, height: '100vh', background: TOKENS.bg, fontFamily: 'Inter, -apple-system, system-ui, sans-serif', color: TOKENS.text }}>
      <style>{`@keyframes pcSlide{from{transform:translateX(40px);opacity:.3}to{transform:none;opacity:1}}@keyframes pcFade{from{opacity:0}to{opacity:1}}.pc-fila:hover td{background:#f7f9fd}.pc-nav:hover{background:${TOKENS.surfaceLow}}.pc-link-anular:hover,.pc-sol-aut:hover{text-decoration:underline}input::placeholder{color:#b7c0d1;font-weight:400}`}</style>
      <aside style={{ background: TOKENS.surface, borderRight: `1px solid ${TOKENS.border}`, display: 'flex', flexDirection: 'column', padding: mini ? '16px 8px' : '16px 10px', minHeight: 0, overflow: 'hidden' }}>
        <div style={{ display: 'flex', flexDirection: mini ? 'column' : 'row', alignItems: 'center', gap: mini ? 12 : 9, padding: mini ? '4px 0 14px' : '4px 8px 14px', marginBottom: 12, borderBottom: `1px solid ${TOKENS.border}`, fontWeight: 800, fontSize: 17, color: RODANDO_ROJO, whiteSpace: 'nowrap' }}>
          <RodandoTile size={30} radius={9} />{!mini && <span style={{ flex: 1 }}>Rodando</span>}
          <button type="button" onClick={cambiarMini} title={mini ? 'Expandir menú' : 'Contraer menú'} aria-label={mini ? 'Expandir menú' : 'Contraer menú'} className="pc-nav" style={{ width: 28, height: 28, borderRadius: 8, border: `1px solid ${TOKENS.border}`, background: TOKENS.surface, display: 'grid', placeItems: 'center', cursor: 'pointer', flex: 'none', padding: 0 }}><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke={TOKENS.textMuted} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d={mini ? 'M10 6l6 6-6 6M4 6l6 6-6 6' : 'M14 6l-6 6 6 6M20 6l-6 6 6 6'} /></svg></button>
        </div>
        {PC_SECCIONES.map(([id, l, ic]) => {
          const on = !embed && sec === id;
          return (
            <button key={id} type="button" title={mini ? l : undefined} className={on ? '' : 'pc-nav'} onClick={() => { if (embed && onVistaCelular) onVistaCelular('salir-embed'); ir(id, null, true); }} style={{ position: 'relative', border: 0, width: '100%', textAlign: 'left', display: 'flex', alignItems: 'center', justifyContent: mini ? 'center' : 'flex-start', gap: 10, padding: mini ? '11px 0' : '10px', whiteSpace: 'nowrap', borderRadius: 10, fontFamily: 'inherit', fontSize: 14, fontWeight: on ? 800 : 600, color: on ? TOKENS.primary : TOKENS.textMuted, background: on ? TOKENS.primaryBg : 'transparent', cursor: 'pointer', marginBottom: 2 }}>
              {I[ic] ? I[ic](18, on ? TOKENS.primary : TOKENS.textMuted) : null}{!mini && l}
              {mini && ((id === 'seguimiento' && nSeg > 0) || (id === 'catalogos' && nRevisar > 0)) && <span style={{ position: 'absolute', top: 6, left: 'calc(50% + 5px)', width: 8, height: 8, borderRadius: 99, background: id === 'seguimiento' ? PAUSA_COLOR.solid : '#d8b100', border: '2px solid #fff' }} />}
              {!mini && id === 'seguimiento' && nSeg > 0 && <span style={{ marginLeft: 'auto', fontSize: 11, fontWeight: 500, background: PAUSA_COLOR.bg, color: PAUSA_COLOR.fg, borderRadius: 999, padding: '1px 7px' }}>{nSeg}</span>}
              {!mini && id === 'catalogos' && nRevisar > 0 && <span style={{ marginLeft: 'auto', fontSize: 11, fontWeight: 500, background: '#fff2cc', color: '#7f6000', borderRadius: 999, padding: '1px 7px' }}>{nRevisar}</span>}
            </button>);
        })}
        <div style={{ marginTop: 'auto', borderTop: `1px solid ${TOKENS.border}`, paddingTop: 10 }}>
          <button type="button" title={mini ? 'Mi perfil' : undefined} onClick={() => ir('perfil')} style={{ display: 'flex', alignItems: 'center', justifyContent: mini ? 'center' : 'flex-start', gap: 9, width: '100%', border: 0, background: sec === 'perfil' ? TOKENS.primaryBg : 'transparent', borderRadius: 10, padding: mini ? '8px 0' : 8, whiteSpace: 'nowrap', cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left' }}>
            {foto ? <img src={foto} alt="" style={{ width: 32, height: 32, borderRadius: 99, objectFit: 'cover', flexShrink: 0 }} /> :
            <span style={{ width: 32, height: 32, borderRadius: 99, background: TOKENS.primaryBg, color: TOKENS.primary, display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 12 }}>{window.deriveInitials ? window.deriveInitials(yo.nombre || '') : 'AD'}</span>}
            {!mini && <span><b style={{ display: 'block', fontSize: 13, color: TOKENS.text }}>{yo.nombre || 'Administrador'}</b><span style={{ fontSize: 11.5, color: TOKENS.textMuted }}>Mi perfil</span></span>}
          </button>
          {onVistaCelular && !mini && <button type="button" onClick={() => onVistaCelular(true)} style={{ border: 0, background: 'none', fontFamily: 'inherit', fontSize: 12, fontWeight: 700, color: TOKENS.primary, cursor: 'pointer', padding: '8px 8px 0' }}>Ver como celular</button>}
        </div>
      </aside>
      <main style={{ display: 'flex', flexDirection: 'column', minWidth: 0, minHeight: 0, position: 'relative' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '12px 24px', borderBottom: `1px solid ${TOKENS.border}`, background: TOKENS.bg }}>
          <h2 style={{ margin: 0, fontSize: 20, color: TOKENS.primary, flex: 1 }}>{embed ? 'Registro' : titulos[sec]}</h2>
          {!embed && sec === 'registros' && <><PcBtn onClick={() => window.dispatchEvent(new CustomEvent('pc-registrar', { detail: 'enc' }))}>＋ Nueva tarea</PcBtn><PcBtn onClick={() => window.dispatchEvent(new CustomEvent('pc-registrar', { detail: 'ent' }))}>Registrar entrega</PcBtn><PcBtn tone="p" style={{ marginRight: 8 }} onClick={() => window.dispatchEvent(new CustomEvent('pc-registrar', { detail: 'rec' }))}>＋ Registrar recogida</PcBtn></>}
          {!embed && sec === 'rutas' && <PcBtn tone="p" style={{ marginRight: 8 }} onClick={() => window.dispatchEvent(new CustomEvent('pc-rutas', { detail: 'enc' }))}>＋ Nueva tarea</PcBtn>}
          <span style={{ fontSize: 12.5, color: TOKENS.textMuted, marginRight: 6 }}>{hoyLargo}</span>
          <span data-pc-pop>{iconoBtn('notas', libreta, notasPend, TOKENS.primary, 'Tareas')}</span>
          <span data-pc-pop>{iconoBtn('avisos', I.bell(21, TOKENS.text), nAvisos, TOKENS.danger, 'Notificaciones')}</span>
        </div>
        {pop === 'notas' && <div data-pc-pop><PcNotas toast={toast} onClose={() => setPop(null)} /></div>}
        {pop === 'avisos' && <div data-pc-pop><PcAvisos ir={(s) => { if (embed && onVistaCelular) onVistaCelular('salir-embed'); ir(s); }} onClose={() => setPop(null)} /></div>}
        <div id="pc-body" style={{ flex: 1, overflow: 'auto', padding: '18px 24px 28px', minHeight: 0 }}>{cuerpo}</div>
        {toastMsg && <div style={{ position: 'fixed', left: `calc(50% + ${anchoMenu / 2}px)`, bottom: 24, transform: 'translateX(-50%)', background: toastMsg.rojo === 'y' ? '#fff2cc' : toastMsg.rojo === 'g' ? TOKENS.success : toastMsg.rojo === 'm' ? TOKENS.anulado : toastMsg.rojo ? TOKENS.dangerText : TOKENS.primary, color: toastMsg.rojo === 'y' ? '#7f6000' : '#fff', border: toastMsg.rojo === 'y' ? '1px solid #ecd98f' : 'none', borderRadius: 12, padding: '11px 16px', fontSize: 13, fontWeight: 700, zIndex: 1300, boxShadow: '0 8px 20px rgba(11,28,48,.25)' }}>{toastMsg.msg}</div>}
      </main>
    </div>);
}

// ─── Secciones del PC en el celular (27/11/2026, solo admin): Informes, Novedades y Usuarios ───
function MovilAdminSeccion({ sec, onBack }) {
  useRefrescoPC();
  const [aviso, setAviso] = React.useState(null);
  const toast = (msg, rojo) => { setAviso({ msg, rojo }); clearTimeout(toast.t); toast.t = setTimeout(() => setAviso(null), 2400); };
  const regs = pcRegistros();
  const titulo = { informes: 'Informes', seguimiento: 'Novedades', usuarios: 'Usuarios' }[sec] || 'Panel';
  const Header = window.AppHeader;
  const cuerpo = sec === 'informes' ? <PcInformes regs={regs} toast={toast} /> : sec === 'seguimiento' && typeof PcSeguimiento === 'function' ? <PcSeguimiento regs={regs} toast={toast} ir={() => {}} /> : sec === 'usuarios' ? <PcUsuarios toast={toast} /> : null;
  return (
    <div style={{ minHeight: '100vh', background: TOKENS.bg, fontFamily: 'Inter, -apple-system, system-ui, sans-serif', color: TOKENS.text }}>
      {Header ? <Header title={titulo} onBack={onBack} right={null} bell={false} /> : <div style={{ padding: 14 }}><button type="button" onClick={onBack}>‹ Volver</button></div>}
      <PcCelCtx.Provider value={true}><div style={{ padding: '14px 14px 40px', overflowX: 'hidden' }}>{cuerpo}</div></PcCelCtx.Provider>
      {aviso && <div style={{ position: 'fixed', bottom: 20, ...PC_CEL_FIJO, maxWidth: 408, zIndex: 2000, background: aviso.rojo ? TOKENS.danger : TOKENS.primary, color: '#fff', borderRadius: 12, padding: '12px 14px', fontSize: 13.5, fontWeight: 600, textAlign: 'center', boxShadow: '0 10px 30px rgba(11,28,48,.25)' }}>{aviso.msg}</div>}
    </div>);
}
Object.assign(window, { PanelPC, usePantallaAncha, pcRegistros, pcLibro, MovilAdminSeccion, PcCelCtx, PC_CEL_FIJO });
