// ─── Servicios y cobro · pausas por rin · seguimiento · express (16/11/2026) ───
// Playground "Servicios, express y seguimiento". Cada rin lleva su servicio (RP / RM, + soldadura),
// un solo precio sin IVA y, si hace falta, una solicitud de autorización que lo pone en pausa.
// La placa queda en pausa (no cuenta días hábiles) mientras algún rin espere; se entrega cuando se
// resuelve el último. Seguimiento lleva la bitácora (con anulación con motivo, como el HISTORIAL
// del Sheets Control Subastas).
const LS_SERV = 'rodando.servicios.v1';
const LS_CATSERV = 'rodando.catServicios.v1';
const CATSERV_DEF = {
  rp: 180000, rm: 180000, sold: 80000, alerta: 5, slaExpress: 2, slaGarantia: 2,
  garantia: ['Pintura (color o acabado)', 'Golpe sin corregir', 'Maquinado', 'Balanceo / vibración', 'Otro'],
  pausa: ['Soldadura', 'Pintura especial (combinar color)', 'Otro'],
  resp: ['Correo enviado', 'Llamada', 'Respuesta de la aseguradora', 'Recordatorio enviado', 'Otro'],
  anula: ['Se registró por error', 'Quedó duplicado', 'Información equivocada', 'Otro']
};
// Etiqueta neutra de servicio (estilo Business Suite, 19/11/2026).
const SERV_CHIP = { background: '#eef1f6', color: '#3c4a66', border: '1px solid #d5deeb' };
function ServChips({ sv }) {
  return <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, flexWrap: 'nowrap' }}>
    {(sv.grupos || []).map(([c, n]) => <span key={c} style={{ ...SERV_CHIP, fontSize: 12, fontWeight: 500, borderRadius: 6, padding: '2px 7px', whiteSpace: 'nowrap' }}>{n > 1 ? `${n} ${c}` : c}</span>)}
    {sv.sin > 0 && <span style={{ fontSize: 12, color: TOKENS.textSubtle, marginLeft: 2, whiteSpace: 'nowrap' }}>+{sv.sin} sin servicio</span>}
  </span>;
}
const SERV_NOMBRE = { RP: 'Rectificado + pintura', RM: 'Rectificado + maquinado + pintura' };
// Pausa (17/11/2026): una sola familia ámbar en toda la app — fondo, texto, borde y sólido (círculos y puntos).
const PAUSA_COLOR = { bg: '#fdf0d5', fg: '#8a5a00', bd: '#f1d49b', solid: '#c99a2e' }; // 27/11/2026: ámbar (opción A del semáforo)
function loadCatServicios() {
  try { return { ...CATSERV_DEF, ...JSON.parse(localStorage.getItem(LS_CATSERV) || '{}') }; } catch (e) { return { ...CATSERV_DEF }; }
}
function saveCatServicios(c) { window.safeSetItem(LS_CATSERV, JSON.stringify(c)); window.dispatchEvent(new Event('rodando-servicios')); }
function loadServicios() { try { return JSON.parse(localStorage.getItem(LS_SERV) || '{}'); } catch (e) { return {}; } }
function saveServicios(m) { window.safeSetItem(LS_SERV, JSON.stringify(m)); window.dispatchEvent(new Event('rodando-servicios')); }
function servAhora() {
  const d = new Date();
  return { iso: `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`, fecha: `${String(d.getDate()).padStart(2, '0')}/${String(d.getMonth() + 1).padStart(2, '0')}/${d.getFullYear()}`, hora: `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}` };
}
const servYo = () => { const u = window.usuarioActual ? window.usuarioActual() : null; return (u && u.nombre) || 'Admin'; };
// Un renglón por rin físico (un ítem de 4 rines = Rin 1..4).
function servRinesDeItems(items) {
  const out = [];
  (items || []).filter((it) => it && it.tipo === 'rin').forEach((it) => {
    const n = Math.max(1, Number(it.cantidad) || 1);
    const d = [it.tamano && it.tamano + '"', it.material, it.huecos].filter(Boolean).join(' · ');
    for (let i = 0; i < n; i++) out.push({ d });
  });
  return out;
}
// Servicio guardado de un ticket, con tantos rines como trae la placa.
function servDe(t) {
  const s = loadServicios()[t.id] || {};
  const base = servRinesDeItems(t.items);
  const rines = base.map((b, i) => ({ tipo: '', sol: false, precio: 0, aut: null, ...((s.rines || [])[i] || {}), d: b.d }));
  return { siniestro: s.siniestro || '', rines, guardado: !!s.rines };
}
function servGuardar(id, data) {
  const m = loadServicios();
  m[id] = { siniestro: data.siniestro || '', rines: data.rines.map(({ d, ...r }) => r), actualizado: Date.now() };
  saveServicios(m);
}
const servCodigo = (r) => r && r.tipo ? r.tipo + (r.sol ? 'S' : '') : '';
const servValor = (r) => !r || !r.tipo || r.sinReparar || (r.aut && r.aut.estado === 'no') ? 0 : Number(r.precio) || 0;
function servSugerido(r, cat) { const c = cat || loadCatServicios(); return (r.tipo === 'RP' ? c.rp : c.rm) + (r.sol ? c.sold : 0); }
function servResumen(t) {
  const s = servDe(t);
  const cods = {}; s.rines.forEach((r) => { const c = servCodigo(r); if (c) cods[c] = (cods[c] || 0) + 1; });
  // 19/11/2026: agrupados por código, el de más rines primero ("3 RP · RPS").
  const grupos = Object.entries(cods).sort((a, b) => b[1] - a[1]);
  return { grupos, sin: s.rines.filter((r) => !r.tipo).length, txt: grupos.map(([c, n]) => n > 1 ? `${n} ${c}` : c).join(' · '), total: s.rines.reduce((a, r) => a + servValor(r), 0), siniestro: s.siniestro, rines: s.rines, con: s.rines.some((r) => r.tipo), n: s.rines.length };
}
function ticketEnPausa(id) { const s = loadServicios()[id]; return !!(s && (s.rines || []).some((r) => r && r.aut && r.aut.estado === 'espera')); }
// Días hábiles en pausa (unión de las pausas de todos los rines; cuenta cada día hábil una sola vez).
function diasPausaTicket(id) {
  const s = loadServicios()[id]; if (!s) return 0;
  const hoy = servAhora().iso; const dias = new Set();
  (s.rines || []).flatMap((r) => r ? [...(r.pausas || []), r.aut] : []).forEach((a) => {
    if (!a || !a.desdeIso) return;
    const fin = a.hastaIso || hoy;
    const [y, m, d] = a.desdeIso.split('-').map(Number); const cur = new Date(y, m - 1, d);
    for (let k = 0; k < 400; k++) { cur.setDate(cur.getDate() + 1); const iso = `${cur.getFullYear()}-${String(cur.getMonth() + 1).padStart(2, '0')}-${String(cur.getDate()).padStart(2, '0')}`; if (iso > fin) break; if (!window.isBusinessDay || window.isBusinessDay(new Date(cur))) dias.add(iso); }
  });
  return dias.size;
}
// Al resolverse la última pausa, el plazo empieza de cero desde ese momento (16/11/2026):
// recogida el 1, autorizada el 15 → se cuenta desde el 15 (entrega en teoría el 18).
function reinicioPlazo(id) {
  const s = loadServicios()[id]; if (!s) return null;
  const rs = (s.rines || []).filter((r) => r && r.aut);
  if (!rs.length || rs.some((r) => r.aut.estado === 'espera')) return null;
  const ult = rs.filter((r) => r.aut.hastaIso).sort((a, b) => (b.aut.hastaIso + (b.aut.hastaHora || '')).localeCompare(a.aut.hastaIso + (a.aut.hastaHora || '')))[0];
  return ult ? { fecha: ult.aut.hasta, hora: ult.aut.hastaHora || '08:00', iso: ult.aut.hastaIso } : null;
}
function servDiasEsperando(aut) {
  if (!aut || !aut.desdeIso) return 0;
  const hoy = aut.hastaIso || servAhora().iso; const [y, m, d] = aut.desdeIso.split('-').map(Number); const cur = new Date(y, m - 1, d); let n = 0;
  for (let k = 0; k < 400; k++) { cur.setDate(cur.getDate() + 1); const iso = `${cur.getFullYear()}-${String(cur.getMonth() + 1).padStart(2, '0')}-${String(cur.getDate()).padStart(2, '0')}`; if (iso > hoy) break; if (!window.isBusinessDay || window.isBusinessDay(new Date(cur))) n++; }
  return n;
}
// Cambia un rin y guarda (para acciones de Seguimiento).
function servActualizarRin(t, i, fn) { const s = servDe(t); fn(s.rines[i], s); servGuardar(t.id, s); }
// Todos los rines esperando autorización (para Seguimiento y el menú).
function servPendientes(regs) {
  const out = [];
  (regs || []).filter((r) => r._estado === 'pend').forEach((r) => {
    const s = loadServicios()[r.id]; if (!s) return;
    (s.rines || []).forEach((x, i) => { if (x && x.aut && x.aut.estado === 'espera') out.push({ r, i, rin: x, dias: servDiasEsperando(x.aut) }); });
  });
  return out.sort((a, b) => b.dias - a.dias);
}

const PcPausaIco = ({ s = 8 }) => <i style={{ display: 'inline-block', width: s, height: s + 1, borderLeft: `${Math.max(2, Math.round(s / 3))}px solid currentColor`, borderRight: `${Math.max(2, Math.round(s / 3))}px solid currentColor`, boxSizing: 'border-box', verticalAlign: -1 }} />;
const PcChipPausa = ({ txt = 'En pausa' }) => <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11.5, fontWeight: 500, borderRadius: 999, padding: '3px 9px', whiteSpace: 'nowrap', background: PAUSA_COLOR.bg, color: PAUSA_COLOR.fg, border: `1px solid ${PAUSA_COLOR.bd}` }}><PcPausaIco />{txt}</span>;
const PcChipExpress = ({ solo }) => <span title="Express" style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 11.5, fontWeight: 500, borderRadius: 999, padding: '2px 8px', whiteSpace: 'nowrap', background: '#fce7f3', color: '#be185d', border: '1px solid #f5bfdc' }}>⚡{solo ? '' : ' Express'}</span>;
const pcPesos = (n) => '$ ' + (Number(n) || 0).toLocaleString('es-CO');
// Precio en tarjetas (17/11/2026, opción B): cifra en peso semi con el signo $ apagado y números de ancho fijo.
const PcPrecio = ({ n, size = 14, w = 600, style }) => <span style={{ fontSize: size, fontWeight: w, color: TOKENS.text, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap', ...style }}><span style={{ color: TOKENS.textSubtle, fontWeight: 500, marginRight: 3 }}>$</span>{(Number(n) || 0).toLocaleString('es-CO')}</span>;
const servNum = (v) => Number(String(v).replace(/\D/g, '')) || 0;
function PcPesoInput({ value, onChange, width = 130 }) {
  const [txt, setTxt] = React.useState((Number(value) || 0).toLocaleString('es-CO'));
  React.useEffect(() => { setTxt((Number(value) || 0).toLocaleString('es-CO')); }, [value]);
  return <div style={{ position: 'relative', width }}><span style={{ position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)', color: TOKENS.textMuted, fontSize: 13 }}>$</span>
    <input value={txt} onChange={(e) => setTxt(e.target.value.replace(/[^\d.]/g, ''))} onBlur={() => onChange(servNum(txt))} style={{ ...pcInp, width: '100%', paddingLeft: 22, textAlign: 'right', fontWeight: 700 }} /></div>;
}
// Diálogo simple con lista + texto (solicitar autorización, seguimiento, anulación).
function PcDialogo({ tono, icono, titulo, msg, campos, confirmar, onOk, onCancel, ticket }) {
  const [v, setV] = React.useState(() => Object.fromEntries(campos.map((c) => [c.k, c.def != null ? c.def : c.ops ? c.ops[0] : ''])));
  const [err, setErr] = React.useState(false);
  const c = { a: [PAUSA_COLOR.bg, PAUSA_COLOR.fg, PAUSA_COLOR.solid, '#fff'], y: ['#fff2cc', '#7f6000', '#f2c037', '#3d2e00'], p: [TOKENS.primaryBg, TOKENS.primary, TOKENS.primary, '#fff'], g: [TOKENS.successBg, TOKENS.success, TOKENS.success, '#fff'], r: [TOKENS.dangerBg, TOKENS.dangerText, TOKENS.danger, '#fff'], m: [TOKENS.anuladoBg, TOKENS.anulado, TOKENS.anulado, '#fff'] }[tono];
  const ok = () => { const falta = campos.find((x) => x.req && !String(v[x.k] || '').trim()); if (falta) { setErr(true); return; } onOk(v); };
  return ReactDOM.createPortal(
    <div onClick={onCancel} style={{ position: 'fixed', inset: 0, background: 'rgba(11,28,48,.45)', zIndex: 1200, display: 'grid', placeItems: 'center' }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: TOKENS.surface, borderRadius: 18, padding: 22, width: 400 }}>
        <div style={{ width: 52, height: 52, borderRadius: 99, margin: '0 auto 10px', display: 'grid', placeItems: 'center', background: c[0], color: c[1], fontSize: 22 }}>{icono}</div>
        <div style={{ textAlign: 'center', fontWeight: 800, fontSize: 17 }}>{titulo}</div>
        {ticket && window.CabeceraPlaca && <div style={{ display: 'flex', justifyContent: 'center', margin: '10px 0 4px' }}><window.CabeceraPlaca ticket={ticket} /></div>}
        
        <div style={{ textAlign: 'center', fontSize: 13, color: TOKENS.textMuted, margin: '6px 0 14px', lineHeight: 1.45 }}>{msg}</div>
        {campos.map((f) =>
        <div key={f.k} style={{ marginBottom: 10 }}>
            <div style={{ ...pcLbl, marginBottom: 6 }}>{f.l}</div>
            {f.ops ? <select value={v[f.k]} onChange={(e) => setV({ ...v, [f.k]: e.target.value })} style={{ ...pcInp, width: '100%' }}>{f.ops.map((o) => <option key={o}>{o}</option>)}</select> :
          f.peso ? <PcPesoInput value={v[f.k]} width="100%" onChange={(n) => setV((x) => ({ ...x, [f.k]: n }))} /> :
          <input autoFocus={!!f.req} value={v[f.k]} placeholder={f.ph || (f.req ? '' : 'Opcional')} onChange={(e) => { setErr(false); setV({ ...v, [f.k]: e.target.value }); }} style={{ ...pcInp, width: '100%', ...(err && f.req && !String(v[f.k] || '').trim() ? PC_ROJO : {}) }} />}
            {err && f.req && !String(v[f.k] || '').trim() && <PcErr on>Escribe el detalle.</PcErr>}
          </div>)}
        <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
          <PcBtn style={{ flex: 1, padding: '11px 14px' }} onClick={onCancel}>Cancelar</PcBtn>
          <PcBtn style={{ flex: 1, padding: '11px 14px', background: c[2], color: c[3], border: 'none' }} onClick={ok}>{confirmar}</PcBtn>
        </div>
      </div>
    </div>, document.body);
}

// ─── Suministros (23/11/2026) ────────────────────────────────────────────
// Lo que la empresa pone al entregar una placa (ej. una llanta nueva para el rin). Va con el registro;
// no crea otro. Se guarda por ticket y, al entregar, se copia al registro de entrega.
const LS_SUM = 'rodando.suministros.v1';
const SUM_TIPO = { llanta: ['llanta', 'llantas', 'Llanta'], rin: ['rin', 'rines', 'Rin'], valvula: ['válvula', 'válvulas', 'Válvula'] };
function loadSuministrosMap() { try { return JSON.parse(localStorage.getItem(LS_SUM)) || {}; } catch (e) { return {}; } }
function suministrosDe(id) { return (loadSuministrosMap()[id] || []); }
function guardarSuministros(id, list) {
  const m = loadSuministrosMap(); if (list && list.length) m[id] = list; else delete m[id];
  try { localStorage.setItem(LS_SUM, JSON.stringify(m)); } catch (e) {}
  try { window.dispatchEvent(new Event('rodando-suministros')); } catch (e) {}
}
function agregarSuministro(id, x) { const now = servAhora(); guardarSuministros(id, [...suministrosDe(id), { id: 'su-' + Date.now(), tipo: x.tipo, cantidad: Math.max(1, Number(x.cantidad) || 1), detalle: String(x.detalle || '').trim(), fecha: now.fecha, por: servYo() }]); }
function quitarSuministro(id, sid) { guardarSuministros(id, suministrosDe(id).filter((x) => x.id !== sid)); }
const sumTxt = (x) => { const n = Number(x.cantidad) || 1; const t = SUM_TIPO[x.tipo] || SUM_TIPO.llanta; return `${n} ${t[n === 1 ? 0 : 1]} ${n === 1 ? (x.tipo === 'rin' ? 'nuevo' : 'nueva') : (x.tipo === 'rin' ? 'nuevos' : 'nuevas')}${x.detalle ? ' · ' + x.detalle : ''}`; };
const sumLista = (L) => (L || []).map(sumTxt).join(' + ');
// Suministros de un registro: los de la entrega si ya se entregó; si no, los pendientes del ticket.
const suministrosDeReg = (r) => (r && r._ent && r._ent.suministros) || suministrosDe(r && (r._ent ? r._ent.ticketId || r.id : r.id));

function PcSuministroDlg({ r, onCancel, onOk, msg }) {
  const [v, setV] = React.useState({ tipo: 'llanta', cantidad: 1, detalle: '' });
  const Step = window.PcStepper, Seg = window.PcSeg || PcSeg;
  const dia = r && r._est && r._est.etiqueta;
  return ReactDOM.createPortal(
    <div onClick={onCancel} style={{ position: 'fixed', inset: 0, background: 'rgba(11,28,48,.45)', zIndex: 1250, display: 'grid', placeItems: 'center' }}>
      <div onClick={(e) => e.stopPropagation()} 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: '#e6f7fa', color: '#0e7490', fontSize: 22 }}>＋</div>
        <div style={{ textAlign: 'center', fontWeight: 800, fontSize: 17 }}>Agregar suministro</div>
        {r && window.CabeceraPlaca && <div style={{ display: 'flex', justifyContent: 'center', margin: '10px 0 4px' }}><window.CabeceraPlaca ticket={r} /></div>}
        <div style={{ textAlign: 'center', fontSize: 12.5, color: TOKENS.textMuted, margin: '4px 0 12px' }}>{[r && r.taller, r && r.sede, dia].filter(Boolean).join(' · ')}</div>
        <div style={{ ...pcLbl, marginBottom: 6 }}>Qué se suministra</div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <Seg value={v.tipo} onChange={(t) => setV({ ...v, tipo: t })} options={[['llanta', 'Llanta'], ['rin', 'Rin'], ['valvula', 'Válvula']]} />
          {Step && <Step value={v.cantidad} onChange={(n) => setV({ ...v, cantidad: n })} />}
        </div>
        <input autoFocus value={v.detalle} onChange={(e) => setV({ ...v, detalle: e.target.value })} placeholder={v.tipo === 'llanta' ? 'Marca y medida · ej. Michelin 205/55 R16' : 'Detalle (opcional)'} style={{ ...pcInp, width: '100%', boxSizing: 'border-box', marginTop: 10 }} />
        <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 10, textAlign: 'center' }}>{msg || 'Sale con la entrega de esta placa; no crea otro registro.'}</div>
        <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
          <PcBtn style={{ flex: 1, padding: '11px 14px' }} onClick={onCancel}>Cancelar</PcBtn>
          <PcBtn tone="p" style={{ flex: 1, padding: '11px 14px' }} onClick={() => onOk(v)}>Agregar suministro</PcBtn>
        </div>
      </div>
    </div>, document.body);
}
// Tarjeta "Suministros" de la ficha del PC.
function PcSuministrosFicha({ r, toast }) {
  const [, setN] = React.useState(0); const [dlg, setDlg] = React.useState(false);
  React.useEffect(() => { const f = () => setN((n) => n + 1); window.addEventListener('rodando-suministros', f); return () => window.removeEventListener('rodando-suministros', f); }, []);
  const L = suministrosDeReg(r); const edita = r._estado === 'pend' && !r._gar;
  if (!L.length && !edita) return null;
  return <div style={{ background: TOKENS.surface, border: '1px solid #dfe5ee', borderRadius: 14, padding: 14, marginTop: 12 }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: L.length ? 10 : 4 }}><b style={{ fontSize: 14, fontWeight: 700, flex: 1 }}>Suministros</b>{edita && <PcBtn style={{ padding: '7px 12px', fontSize: 12.5 }} onClick={() => setDlg(true)}>＋ Agregar suministro</PcBtn>}</div>
    {L.map((x) => <div key={x.id} style={{ display: 'flex', alignItems: 'center', gap: 8, background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 10, padding: '8px 10px', marginTop: 6, fontSize: 13 }}>
      <span style={{ background: '#0e7490', color: '#fff', fontSize: 10, fontWeight: 800, letterSpacing: '.04em', borderRadius: 99, padding: '2px 8px' }}>SUMINISTRO</span>
      <span style={{ flex: 1, minWidth: 0 }}><b style={{ fontWeight: 600 }}>{sumTxt(x)}</b> <span style={{ color: TOKENS.textSubtle, fontSize: 12 }}>· {x.por} {x.fecha}</span></span>
      {edita && <button type="button" title="Quitar" onClick={() => { quitarSuministro(r.id, x.id); toast && toast('Suministro quitado'); }} style={{ width: 28, height: 28, borderRadius: 8, border: `1.5px solid ${TOKENS.borderInput}`, background: TOKENS.surface, color: TOKENS.danger, cursor: 'pointer' }}>✕</button>}
    </div>)}
    {!L.length && <div style={{ fontSize: 12.5, color: TOKENS.textMuted }}>Lo que se entrega además de lo recogido (ej. una llanta nueva). Sale con la entrega de la placa.</div>}
    {dlg && <PcSuministroDlg r={r} onCancel={() => setDlg(false)} onOk={(v) => { setDlg(false); agregarSuministro(r.id, v); pcAvisar(); toast && toast(`Suministro agregado · ${r.placa}`, 'g'); }} />}
  </div>;
}

// Solicitar autorización (19/11/2026): una sola acción para la placa; en la ventana se marcan los
// rines (varios a la vez). Sin servicio o ya en pausa no se pueden marcar.
function PcSolicitarAut({ r, s, cat, onOk, onCancel }) {
  const libre = (x) => x.tipo && !(x.aut && x.aut.estado === 'espera');
  const [sel, setSel] = React.useState(() => { const L = s.rines.map((x, i) => libre(x) ? i : -1).filter((i) => i >= 0); return L.length === 1 ? L : []; });
  const conSol = sel.some((i) => s.rines[i].sol);
  const ops = conSol ? cat.pausa : cat.pausa.filter((m) => m !== 'Soldadura');
  const [motivo, setMotivo] = React.useState(ops[0]);
  const [det, setDet] = React.useState('');
  React.useEffect(() => { if (!ops.includes(motivo)) setMotivo(ops[0]); }, [conSol]);
  const Cab = window.CabeceraPlaca;
  const ok = sel.length > 0 && motivo;
  return ReactDOM.createPortal(
    <div onClick={onCancel} style={{ position: 'fixed', inset: 0, background: 'rgba(11,28,48,.45)', zIndex: 1200, display: 'grid', placeItems: 'center', padding: 16 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: TOKENS.surface, borderRadius: 18, padding: 22, width: 440, maxWidth: '100%', maxHeight: '90vh', overflow: 'auto' }}>
        <div style={{ fontWeight: 800, fontSize: 17 }}>Solicitar autorización</div>
        <div style={{ margin: '10px 0 4px' }}>{Cab ? <Cab ticket={{ ...r, express: false, id: null }} /> : <b>{r.placa} · {r.codigo}</b>}</div>
        <div style={{ fontSize: 12.5, color: TOKENS.textMuted, lineHeight: 1.45, margin: '8px 0 12px' }}>Los rines que marques quedan en pausa hasta que la aseguradora responda. La placa no cuenta días hábiles mientras espera.</div>
        <div style={{ ...pcLbl, marginBottom: 6 }}>¿Qué rines?</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          {s.rines.map((x, i) => {
            const on = sel.includes(i); const pausa = x.aut && x.aut.estado === 'espera'; const ok2 = libre(x);
            return (
              <button key={i} type="button" disabled={!ok2} onClick={() => setSel((L) => on ? L.filter((z) => z !== i) : [...L, i].sort())} style={{
                position: 'relative', textAlign: 'left', fontFamily: 'inherit', cursor: ok2 ? 'pointer' : 'not-allowed', borderRadius: 11, lineHeight: 1.35,
                border: on ? `2px solid ${TOKENS.primary}` : `1px solid ${TOKENS.borderInput}`, background: on ? TOKENS.primaryBg : ok2 ? TOKENS.surface : TOKENS.surfaceLow,
                padding: on ? '9px 10px' : '10px 11px', color: ok2 ? TOKENS.text : TOKENS.textSubtle
              }}>
                <b style={{ display: 'block', fontSize: 14 }}>Rin {i + 1}{servCodigo(x) ? ` · ${servCodigo(x)}` : ''}</b>
                <span style={{ fontSize: 12, color: TOKENS.textMuted }}>{pausa ? <PcChipPausa /> : !x.tipo ? 'Sin servicio' : (x.d || 'Rin')}</span>
                {on && <span style={{ position: 'absolute', top: 8, right: 9, width: 18, height: 18, borderRadius: 9, background: TOKENS.primary, display: 'grid', placeItems: 'center' }}>{I.check(11, '#fff')}</span>}
              </button>);
          })}
        </div>
        <div style={{ ...pcLbl, margin: '14px 0 6px' }}>Motivo</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          {ops.map((m) => <button key={m} type="button" onClick={() => setMotivo(m)} style={{ border: `1px solid ${motivo === m ? TOKENS.primary : TOKENS.borderInput}`, background: motivo === m ? TOKENS.primary : TOKENS.surface, color: motivo === m ? '#fff' : TOKENS.text, borderRadius: 999, padding: '7px 12px', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>{m}</button>)}
        </div>
        <div style={{ ...pcLbl, margin: '14px 0 6px' }}>Detalle</div>
        <input value={det} placeholder="Opcional" onChange={(e) => setDet(e.target.value)} style={{ ...pcInp, width: '100%' }} />
        <div style={{ display: 'flex', gap: 8, marginTop: 18 }}>
          <PcBtn style={{ flex: 1, padding: '11px 14px' }} onClick={onCancel}>Cancelar</PcBtn>
          <PcBtn style={{ flex: 1, padding: '11px 14px', background: ok ? TOKENS.primary : '#e9edf3', color: ok ? '#fff' : '#9aa4b5', border: 'none', cursor: ok ? 'pointer' : 'not-allowed' }} onClick={() => ok && onOk(sel, { motivo, det })}>{sel.length > 1 ? `Solicitar para ${sel.length} rines` : 'Solicitar autorización'}</PcBtn>
        </div>
      </div>
    </div>, document.body);
}

// ─── Sección "Servicios y cobro" de la ficha ─────────────────────────────
// 16/11/2026: en lectura por defecto, con "Editar servicios". Al editar, la ficha cambia su barra de
// abajo a Cancelar · Guardar servicios (Entregar desaparece) — la ficha lee el estado por `ctrl`.
// Si la placa aún no tiene servicios, abre directo en edición.
function PcServiciosFicha({ r, toast, ctrl, onEditando, plano }) {
  const cat = loadCatServicios();
  const [s, setS] = React.useState(() => servDe(r));
  const [edit, setEdit] = React.useState(() => { const x = servDe(r); return !x.guardado && r._estado === 'pend' && x.rines.length > 0; });
  const [dlg, setDlg] = React.useState(null);
  const [conf, setConf] = React.useState(false);
  const snap = React.useRef(null);
  React.useEffect(() => { const x = servDe(r); setS(x); setEdit(!x.guardado && r._estado === 'pend' && x.rines.length > 0); }, [r.id]);
  React.useEffect(() => { onEditando && onEditando(edit); }, [edit]);
  // 23/11/2026: si otro lado cambia los servicios (p. ej. "Rin que no se repara"), se vuelve a leer al instante.
  const editRef = React.useRef(edit); editRef.current = edit;
  React.useEffect(() => { const h = () => { if (!editRef.current) setS(servDe(r)); }; window.addEventListener('rodando-servicios', h); return () => window.removeEventListener('rodando-servicios', h); }, [r.id]);
  const [srDlg, setSrDlg] = React.useState(false);
  const pend = r._estado === 'pend' && !r._gar;
  const setR = (i, p) => setS((x) => ({ ...x, rines: x.rines.map((rr, j) => {
    if (j !== i) return rr;
    const tocado = rr.tipo && rr.precio !== servSugerido(rr, cat);
    const n = { ...rr, ...p };
    if (!tocado || 'tipo' in p) n.precio = servSugerido(n, cat);
    return n;
  }) }));
  const copiar = () => { const a = s.rines[0]; setS((x) => ({ ...x, rines: x.rines.map((rr, j) => j === 0 ? rr : { ...rr, tipo: a.tipo, sol: a.sol, precio: a.precio }) })); toast && toast('Rin 1 copiado a los demás'); };
  const listos = s.rines.length > 0 && s.rines.every((x) => x.tipo);
  const total = s.rines.reduce((a, x) => a + servValor(x), 0);
  const guardar = () => { servGuardar(r.id, s); const nuevo = !s.guardado; setS((x) => ({ ...x, guardado: true })); setEdit(false); pcAvisar(); toast && toast(nuevo ? 'Servicios guardados' : 'Cambios guardados', nuevo ? undefined : 'y'); };
  const solicitar = (idx, v) => {
    const now = servAhora();
    const base = edit ? s : servDe(r); // 19/11/2026: también mientras se escriben los servicios
    const rines = base.rines.map((rr, j) => idx.includes(j) ? { ...rr, pausas: rr.aut && rr.aut.estado !== 'espera' ? [...(rr.pausas || []), rr.aut] : (rr.pausas || []), aut: { motivo: v.motivo, det: v.det, desdeIso: now.iso, desde: now.fecha, hora: now.hora, por: servYo(), estado: 'espera', valor: rr.precio, ev: [] } } : rr);
    const ns = { ...base, rines, guardado: true }; servGuardar(r.id, ns); setS(ns); setEdit(false); snap.current = null; pcAvisar();
    toast && toast(`${idx.length === 1 ? `Rin ${idx[0] + 1}` : `${idx.length} rines`} en pausa · pasa a Novedades`, 'y');
  };
  // La ficha usa esto para su barra de abajo.
  if (ctrl) ctrl.current = { edit, listo: listos,
    cancelar: () => { setS(snap.current ? JSON.parse(snap.current) : servDe(r)); snap.current = null; setEdit(false); },
    guardar: () => { if (!listos) { const i = s.rines.findIndex((x) => !x.tipo); toast && toast(`Falta escoger RP o RM en el rin ${i + 1}`, true); return; } setConf(true); } };
  if (!s.rines.length) return <div style={{ fontSize: 12.5, color: TOKENS.textMuted }}>Esta placa no trae rines: no lleva servicios.</div>;
  const chip = (on, txt, onClick, title) => <button type="button" title={title} onClick={onClick} style={{ border: `1px solid ${on ? TOKENS.primary : TOKENS.borderInput}`, background: on ? TOKENS.primary : TOKENS.surface, color: on ? '#fff' : TOKENS.text, borderRadius: 9, padding: '6px 11px', fontFamily: 'inherit', fontSize: 13, fontWeight: 800, cursor: 'pointer' }}>{txt}</button>;
  // 19/11/2026: etiqueta neutra (estilo Business Suite); el azul queda solo para la opción elegida.
  const cod = (x) => <span style={{ fontWeight: 700, fontSize: 12, borderRadius: 6, padding: '3px 8px', minWidth: 44, boxSizing: 'border-box', textAlign: 'center', flexShrink: 0, ...(servCodigo(x) ? SERV_CHIP : { background: TOKENS.surfaceLow, color: TOKENS.textSubtle, border: `1px dashed ${TOKENS.borderInput}` }) }}>{servCodigo(x) || '—'}</span>;
  const seg = (i, x) => <div style={{ display: 'inline-flex', background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 999, padding: 2, gap: 2 }}>
    {['RP', 'RM'].map((t) => { const on = x.tipo === t; return <button key={t} type="button" title={SERV_NOMBRE[t]} aria-pressed={on} onClick={() => setR(i, { tipo: t })} style={{ border: 0, borderRadius: 999, padding: '5px 16px', fontFamily: 'inherit', fontSize: 13, fontWeight: 800, cursor: 'pointer', background: on ? '#fff' : 'transparent', color: on ? TOKENS.primary : TOKENS.textMuted, boxShadow: on ? '0 1px 3px rgba(22,35,63,.15)' : 'none' }}>{t}</button>; })}
  </div>;
  const casilla = (i, x) => <button type="button" aria-pressed={!!x.sol} onClick={() => setR(i, { sol: !x.sol })} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, background: 'none', border: 0, padding: 0, fontFamily: 'inherit', fontSize: 13, fontWeight: 600, color: TOKENS.text, cursor: 'pointer' }}>
    <span style={{ width: 20, height: 20, borderRadius: 6, boxSizing: 'border-box', display: 'grid', placeItems: 'center', border: `2px solid ${x.sol ? TOKENS.primary : TOKENS.borderInput}`, background: x.sol ? TOKENS.primary : TOKENS.surface }}>{x.sol && I.check(13, '#fff')}</span>Soldadura</button>;
  const estadoChip = (x) => x.sinReparar ? (/autoriz/i.test(x.sinReparar.motivo || '') ? <PcChip bg="#efe9f7" fg="#6c4aa6">No autorizado</PcChip> : <PcChip bg="#fbe3e1" fg="#9c443c">No reparable</PcChip>) : x.aut && x.aut.estado === 'espera' ? <PcChipPausa /> : x.aut && x.aut.estado === 'no' ? <PcChip bg="#efe9f7" fg="#6c4aa6">No autorizado</PcChip> : x.aut && x.aut.estado === 'si' ? <PcChip bg={TOKENS.successBg} fg={TOKENS.successText}>Autorizado</PcChip> : null;
  // ── Lectura ──
  if (!edit) return (
    <div style={plano ? {} : { border: `1px solid ${TOKENS.border}`, background: TOKENS.surface, borderRadius: 14, padding: '14px 16px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
        <span style={{ ...pcLbl, flex: 1 }}>Siniestro: <span style={{ fontFamily: pcMono, textTransform: 'none', letterSpacing: 0, color: TOKENS.text }}>{s.siniestro || '—'}</span></span>
        {!r._gar && <PcBtn style={{ padding: '6px 11px', fontSize: 12.5 }} onClick={() => { snap.current = JSON.stringify(s); setEdit(true); }}>{I.pencil(14, TOKENS.primary)} Editar servicios</PcBtn>}
      </div>
      {s.rines.map((x, i) =>
      <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0', borderTop: i ? `1px dashed ${TOKENS.border}` : 'none' }}>
          {cod(x)}
          <div style={{ flex: 1, minWidth: 0 }}><b style={{ fontSize: 13.5 }}>Rin {i + 1}</b>{x.d && <div style={{ fontSize: 12, color: TOKENS.textMuted }}>{x.d}</div>}</div>
          {estadoChip(x)}
          <span style={{ minWidth: 92, textAlign: 'right' }}>{x.tipo ? <PcPrecio n={servValor(x)} /> : <span style={{ color: TOKENS.textSubtle }}>—</span>}</span>
        </div>)}
      {pend && <div style={{ padding: '10px 0 2px', borderTop: `1px dashed ${TOKENS.border}` }}>{pend && s.rines.some((x) => !(x.aut && x.aut.estado === 'espera')) && (s.rines.some((x) => x.tipo && !(x.aut && x.aut.estado === 'espera')) ?
      <button type="button" onClick={() => setDlg(true)} style={{ background: 'none', border: 0, padding: 0, color: TOKENS.primary, fontFamily: 'inherit', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>Solicitar autorización</button> :
      <span title="Elige primero el servicio (RP o RM)" style={{ fontSize: 13, fontWeight: 600, color: TOKENS.textSubtle }}>Solicitar autorización</span>)}
        {s.rines.length > 0 && <div style={{ marginTop: 8 }}><button type="button" onClick={() => setSrDlg(true)} style={{ background: 'none', border: 0, padding: 0, color: TOKENS.primary, fontFamily: 'inherit', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>⊘ Rin que no se repara</button></div>}</div>}
      <div style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center', gap: 14, margin: plano ? (r._gar ? '6px -14px 0' : '6px -14px -14px') : r._gar ? '6px -16px 0' : '6px -16px -14px', padding: plano ? '11px 14px' : '11px 16px', borderTop: `1px solid ${TOKENS.border}`, background: '#f6f8fc', borderRadius: r._gar ? 0 : '0 0 14px 14px' }}><span style={pcLbl}>Total sin IVA</span><PcPrecio n={total} size={16} /></div>
      {r._gar && <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 6 }}>La garantía no se cobra: se conserva lo de la primera entrega.</div>}
      {dlg && <PcSolicitarAut r={r} s={s} cat={cat} onCancel={() => setDlg(null)} onOk={(idx, v) => { setDlg(null); solicitar(idx, v); }} />}
      {srDlg && <SinRepararDlg r={r} onCancel={() => setSrDlg(false)} onOk={(L) => { servFijarSinReparar(r, L); setSrDlg(false); setS(servDe(r)); pcAvisar(); toast && toast(L.length ? `${L.length === 1 ? 'Rin ' + (L[0].i + 1) + ' marcado' : L.length + ' rines marcados'} · ${r.placa} · queda en $0` : `Marca quitada · ${r.placa}`); }} />}
    </div>);
  // ── Edición ──
  return (
    <div style={{ border: `1px solid ${TOKENS.primaryBorder}`, background: '#f8faff', borderRadius: 14, padding: 18 }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 12, alignItems: 'end' }}>
        <div><div style={{ ...pcLbl, marginBottom: 6 }}>N.º de siniestro</div><input value={s.siniestro} placeholder="Opcional" onChange={(e) => setS({ ...s, siniestro: e.target.value })} style={{ ...pcInp, width: '100%', fontFamily: pcMono, fontWeight: 700 }} /></div>
        {s.rines.length > 1 && <PcBtn style={{ padding: '7px 12px', fontSize: 12.5 }} disabled={!s.rines[0].tipo} onClick={copiar}>Copiar Rin 1 a los demás</PcBtn>}
      </div>
      {s.rines.map((x, i) =>
      <div key={i} style={{ background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 14, padding: '14px 16px', marginTop: 12 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            {cod(x)}
            <div style={{ flex: 1, minWidth: 0 }}><b style={{ fontSize: 13.5 }}>Rin {i + 1}</b>{x.d && <div style={{ fontSize: 12, color: TOKENS.textMuted }}>{x.d}</div>}</div>
            {estadoChip(x)}
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'auto auto 1fr', gap: '12px 18px', alignItems: 'center', marginTop: 14 }}>
            {seg(i, x)}
            {casilla(i, x)}
            <div style={{ display: 'flex', justifyContent: 'flex-end' }}>{x.tipo ? <PcPesoInput value={x.precio} onChange={(n) => setS((y) => ({ ...y, rines: y.rines.map((rr, j) => j === i ? { ...rr, precio: n } : rr) }))} /> : <span style={{ fontSize: 12, color: TOKENS.textSubtle }}>Escoge RP o RM</span>}</div>
          </div>
        </div>)}
      {pend && <div style={{ marginTop: 14 }}>{pend && s.rines.some((x) => !(x.aut && x.aut.estado === 'espera')) && (s.rines.some((x) => x.tipo && !(x.aut && x.aut.estado === 'espera')) ?
      <button type="button" onClick={() => setDlg(true)} style={{ background: 'none', border: 0, padding: 0, color: TOKENS.primary, fontFamily: 'inherit', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>Solicitar autorización</button> :
      <span title="Elige primero el servicio (RP o RM)" style={{ fontSize: 13, fontWeight: 600, color: TOKENS.textSubtle }}>Solicitar autorización</span>)}</div>}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 16, paddingTop: 14, borderTop: `1px solid ${TOKENS.border}` }}>
        <span style={{ flex: 1, fontSize: 12.5, color: TOKENS.textMuted }}>{s.rines.filter((x) => x.tipo).length} de {s.rines.length} {s.rines.length === 1 ? 'rin' : 'rines'} con servicio · valores sin IVA</span>
        <span style={pcLbl}>Total</span><PcPrecio n={total} size={16} />
      </div>
      {dlg && <PcSolicitarAut r={r} s={s} cat={cat} onCancel={() => setDlg(null)} onOk={(idx, v) => { setDlg(null); solicitar(idx, v); }} />}
      {conf && window.ConfirmActionModal && <window.ConfirmActionModal tone="primary" icon={s.guardado ? I.pencil(22, TOKENS.primary) : I.check(24, TOKENS.primary)} title={s.guardado ? 'Guardar cambios' : 'Guardar servicios'} confirmLabel={s.guardado ? 'Guardar cambios' : 'Guardar'}
      ticket={r} message={`${s.rines.map(servCodigo).join(' · ')} · ${pcPesos(total)} sin IVA`} onDismiss={() => setConf(false)} onConfirm={() => { setConf(false); guardar(); }} />}
    </div>);
}

// ─── Deshacer entrega (16/11/2026) ───────────────────────────────────────
// Para una entrega registrada por error: la placa vuelve a Por entregar con su plazo original y
// la entrega queda en el historial, tachada, con motivo, nota, quién y cuándo.
const LS_DESHECHAS = 'rodando.entregasDeshechas';
const MOTIVOS_DESHACER = ['Se entregó por error', 'Era otra placa', 'Otro'];
function loadDeshechas() { try { return JSON.parse(localStorage.getItem(LS_DESHECHAS) || '{}'); } catch (e) { return {}; } }
function deshechasDe(id) { return loadDeshechas()[id] || []; }
function deshacerEntrega(ticketId, { motivo, nota }) {
  const ent = window.loadEntregados ? window.loadEntregados() : [];
  const e = ent.find((x) => x.ticketId === ticketId); if (!e) return false;
  window.safeSetItem('rodando.entregados', JSON.stringify(ent.filter((x) => x.ticketId !== ticketId)));
  const esDemo = (window.PENDIENTES_DEMO || []).some((t) => t.id === ticketId);
  if (!esDemo) {
    const lista = window.loadPendientesSaved ? window.loadPendientesSaved() : [];
    if (!lista.some((t) => t.id === ticketId)) {
      lista.unshift({ id: ticketId, codigo: e.codigo, placa: e.placa, idType: e.idType, fecha: e.fechaRecogido, horaRecogida: e.horaRecogida, taller: e.taller, sede: e.sede, aseguradora: e.aseguradora,
        items: e.items || [], fotosPlaca: e.fotosPlaca || [], recogidoPor: e.recogidoPor, recogidoPorNombre: e.recogidoPorNombre, comoLlego: e.comoLlego, transportadoraLlegada: e.transportadoraLlegada, guiaLlegada: e.guiaLlegada,
        digitadoPor: e.digitadoPor, digitadoPorNombre: e.digitadoPorNombre, express: !!e.express, diasPendiente: 0, createdAt: Date.now(), userSaved: true });
      window.safeSetItem('rodando.pendientes', JSON.stringify(lista));
    }
  }
  const m = loadDeshechas(); const now = servAhora();
  (m[ticketId] = m[ticketId] || []).push({ entrega: { ...e, fotos: [], guiaFotos: [], foto: null, guiaFoto: null, fotosPlaca: [], items: [] }, motivo, nota, por: servYo(), fecha: now.fecha, hora: now.hora });
  window.safeSetItem(LS_DESHECHAS, JSON.stringify(m));
  window.dispatchEvent(new Event('rodando-servicios'));
  return true;
}

// ─── Garantía (16/11/2026) ───────────────────────────────────────────────
// El taller devuelve rines ya entregados (al entregar o días después). La primera entrega y su
// cumplimiento se respetan; lo devuelto abre un proceso nuevo con su propio plazo (1–2 días hábiles,
// en Catálogos). No se cobra ni genera factura: se imprime un ticket para el taller.
const LS_GAR = 'rodando.garantias.v1';
const GAR_COLOR = { bg: '#e6f7fa', fg: '#0e7490', bd: '#b3e3ec' };
function loadGarantias() { try { return JSON.parse(localStorage.getItem(LS_GAR) || '{}'); } catch (e) { return {}; } }
function saveGarantias(m) { window.safeSetItem(LS_GAR, JSON.stringify(m)); window.dispatchEvent(new Event('rodando-servicios')); }
function garantiasDe(id) { return loadGarantias()[id] || []; }
function garantiaAbierta(id) { return garantiasDe(id).find((g) => g.estado === 'abierta') || null; }
function crearGarantia(ticketId, { rines, motivo, desc, fotos }) {
  const m = loadGarantias(); const now = servAhora(); const u = window.usuarioActual ? window.usuarioActual() : {};
  const g = { id: 'g' + Date.now(), rines, motivo, desc, fotos: fotos || [], iso: now.iso, fecha: now.fecha, hora: now.hora, por: (u && u.usuario) || '', porNombre: servYo(), estado: 'abierta' };
  (m[ticketId] = m[ticketId] || []).push(g); saveGarantias(m); return g;
}
function entregarGarantia(ticketId, garId, { fotos } = {}) {
  const m = loadGarantias(); const g = (m[ticketId] || []).find((x) => x.id === garId); if (!g) return;
  const now = servAhora(); g.estado = 'entregada'; g.entrega = { fecha: now.fecha, hora: now.hora, iso: now.iso, porNombre: servYo(), fotos: fotos || [] }; saveGarantias(m);
}
function garDiasDesde(g, hasta) {
  try { return window.businessDaysElapsed(window.effectiveStart(g.fecha, g.hora), hasta || new Date()); } catch (e) { return 0; }
}
function garEstado(g) {
  const S = loadCatServicios().slaGarantia || 2; const d = garDiasDesde(g);
  if (d < S) return { label: 'En plazo', orden: 3, dias: d };
  if (d === S) return { label: 'Vence hoy', orden: 2, dias: d };
  if (d === S + 1) return { label: 'Retrasado', orden: 1, dias: d };
  return { label: 'Vencido', orden: 0, dias: d };
}
const PcChipGarantia = ({ txt = 'Garantía' }) => <span title="Devuelto por garantía" style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 11.5, fontWeight: 500, borderRadius: 999, padding: '2px 8px', whiteSpace: 'nowrap', background: GAR_COLOR.bg, color: GAR_COLOR.fg, border: `1px solid ${GAR_COLOR.bd}` }}>↺ {txt}</span>;
function garFechaEstimada(g) {
  const S = loadCatServicios().slaGarantia || 2;
  try { let d = window.effectiveStart(g.fecha, g.hora); for (let k = 0; k < S; k++) d = window.nextBusinessDay(d); return `${String(d.getDate()).padStart(2, '0')}/${String(d.getMonth() + 1).padStart(2, '0')}/${d.getFullYear()}`; } catch (e) { return ''; }
}
// Formulario (celular y PC): qué rines, motivo, qué reclaman y fotos (obligatorios).
// Garantía · campos (18/11/2026): mismos componentes de una recogida normal — rines como botones
// de opción con ✓, motivo en chips, campo de texto y la zona punteada de fotos.
function GarantiaCampos({ ticket, v, setV, toc }) {
  const cat = loadCatServicios();
  const rs = servRinesDeItems(ticket.items); const sv = servDe(ticket);
  const caja = { background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 14, padding: '14px', marginBottom: 12 };
  const tit = { fontSize: 15, fontWeight: 700, color: TOKENS.text, display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 };
  const fl = { fontSize: 13, fontWeight: 700, color: TOKENS.text, margin: '14px 0 6px' };
  const inp = { width: '100%', boxSizing: 'border-box', border: `1px solid ${TOKENS.borderInput}`, borderRadius: 10, padding: '11px 12px', fontSize: 14, fontFamily: 'inherit', background: TOKENS.surface, color: TOKENS.text, outline: 'none' };
  const rojo = { border: '1px solid #c0584f', background: '#fdf3f1' };
  const err = (t) => <div style={{ color: TOKENS.dangerText, fontSize: 12, fontWeight: 600, marginTop: 6 }}>{t}</div>;
  const leer = (files) => [...(files || [])].slice(0, 8).forEach((f) => { const rd = new FileReader(); rd.onload = async () => { const x = window.downscaleDataURL ? await window.downscaleDataURL(rd.result, 1100, 0.7) : rd.result; setV((o) => ({ ...o, fotos: [...o.fotos, x].slice(0, 8) })); }; rd.readAsDataURL(f); });
  const toggle = (i) => setV((o) => ({ ...o, rines: o.rines.includes(i) ? o.rines.filter((z) => z !== i) : [...o.rines, i].sort() }));
  const input = (onChange) => <input type="file" accept="image/*" multiple style={{ display: 'none' }} onChange={(e) => { leer(e.target.files); e.target.value = ''; }} />;
  return (
    <>
      <div style={caja}>
        <div style={tit}>¿Qué rines devolvieron?<span style={{ flex: 1 }} /><span style={{ fontSize: 12, fontWeight: 600, color: TOKENS.textSubtle }}>Toca los que volvieron</span></div>
        {rs.length ?
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            {rs.map((x, i) => {
            const on = v.rines.includes(i);
            return (
              <button key={i} type="button" onClick={() => toggle(i)} aria-pressed={on} style={{
                position: 'relative', textAlign: 'left', fontFamily: 'inherit', cursor: 'pointer', borderRadius: 11, lineHeight: 1.35,
                border: on ? `2px solid ${TOKENS.primary}` : `1px solid ${toc && !v.rines.length ? '#c0584f' : TOKENS.borderInput}`,
                background: on ? TOKENS.primaryBg : TOKENS.surface, padding: on ? '9px 10px' : '10px 11px', color: TOKENS.text
              }}>
                  <b style={{ display: 'block', fontSize: 14 }}>Rin {i + 1}</b>
                  <span style={{ fontSize: 12, color: TOKENS.textMuted }}>{[servCodigo(sv.rines[i]), x.d].filter(Boolean).join(' · ') || 'Rin'}</span>
                  {on && <span style={{ position: 'absolute', top: 8, right: 9, width: 18, height: 18, borderRadius: 9, background: TOKENS.primary, display: 'grid', placeItems: 'center' }}>{I.check(11, '#fff')}</span>}
                </button>);
          })}
          </div> :
        <div style={{ fontSize: 12.5, color: TOKENS.textMuted }}>Esta placa no trae rines.</div>}
        {toc && !v.rines.length && err('Elige al menos un rin.')}
        <div style={fl}>Motivo</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          {cat.garantia.map((m) => {
            const on = v.motivo === m;
            return <button key={m} type="button" onClick={() => setV((o) => ({ ...o, motivo: m }))} style={{ border: `1px solid ${on ? TOKENS.primary : TOKENS.borderInput}`, background: on ? TOKENS.primary : TOKENS.surface, color: on ? '#fff' : TOKENS.text, borderRadius: 999, padding: '7px 12px', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>{m}</button>;
          })}
        </div>
        <div style={fl}>Qué reclaman *</div>
        <input value={v.desc} placeholder="Ej: el color no queda igual al original" onChange={(e) => setV((o) => ({ ...o, desc: e.target.value }))} style={{ ...inp, ...(toc && !v.desc.trim() ? rojo : {}) }} />
        {toc && !v.desc.trim() && err('Escribe qué reclaman.')}
      </div>
      <div style={caja}>
        <div style={tit}>Fotos de lo que reclaman<span style={{ flex: 1 }} /><span style={{ fontSize: 12, fontWeight: 600, color: toc && !v.fotos.length ? TOKENS.dangerText : TOKENS.textSubtle }}>{v.fotos.length} fotos · mín 1</span></div>
        {v.fotos.length === 0 ?
        <label style={{ height: 110, cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 6, border: `1.5px dashed ${toc ? '#c0584f' : TOKENS.primary}`, background: TOKENS.primaryBg, color: TOKENS.primary, borderRadius: 12 }}>
            {input()}{I.cam(26, TOKENS.primary)}<span style={{ fontSize: 14, fontWeight: 800 }}>Tomar o elegir fotos</span>
          </label> :
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
            {v.fotos.map((u, i) => <div key={i} style={{ position: 'relative', aspectRatio: '1' }}><img src={u} style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: 10, display: 'block' }} /><button type="button" aria-label="Quitar foto" onClick={() => setV((o) => ({ ...o, fotos: o.fotos.filter((_, j) => j !== i) }))} style={{ position: 'absolute', top: -6, right: -6, width: 22, height: 22, borderRadius: 999, border: 'none', background: '#1b2333', color: '#fff', fontSize: 12, cursor: 'pointer', display: 'grid', placeItems: 'center', padding: 0 }}>×</button></div>)}
            {v.fotos.length < 8 && <label style={{ aspectRatio: '1', cursor: 'pointer', display: 'grid', placeItems: 'center', border: `1.5px dashed ${TOKENS.primary}`, background: TOKENS.primaryBg, borderRadius: 10 }}>{input()}{I.plus(22, TOKENS.primary)}</label>}
          </div>}
      </div>
    </>);
}
const garFaltas = (v) => [!v.rines.length && 'rines', !v.desc.trim() && 'qué reclaman', !v.fotos.length && 'fotos'].filter(Boolean);
const garVacio = () => ({ rines: [], motivo: loadCatServicios().garantia[0], desc: '', fotos: [] });
// Ticket que se le deja al taller (vista previa; la impresión va a la impresora Bluetooth).
function GarantiaTicket({ ticket, g, onCerrar }) {
  const sv = servDe(ticket);
  return ReactDOM.createPortal(
    <div onClick={onCerrar} style={{ position: 'fixed', inset: 0, background: 'rgba(11,28,48,.5)', zIndex: 1300, display: 'grid', placeItems: 'center', padding: 16 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: TOKENS.surface, borderRadius: 18, padding: 18, width: 340, maxWidth: '100%' }}>
        <div style={{ fontWeight: 800, fontSize: 16, textAlign: 'center', marginBottom: 12 }}>Ticket para el taller</div>
        <div style={{ border: `1px solid ${TOKENS.border}`, padding: '14px 14px', fontFamily: "'JetBrains Mono', monospace", fontSize: 12, lineHeight: 1.55, color: TOKENS.text }}>
          <div style={{ textAlign: 'center' }}><b>SALVALLANTAS CALI</b><br />Rodando · Mensajería</div>
          <div style={{ borderTop: '1px dashed #999', margin: '8px 0' }} /><div style={{ textAlign: 'center' }}><b>RIN DEVUELTO POR GARANTÍA</b></div><div style={{ borderTop: '1px dashed #999', margin: '8px 0' }} />
          Fecha: {g.fecha} {window.formatHora12 ? window.formatHora12(g.hora) : g.hora}<br />Placa: {ticket.placa}<br />Orden: {ticket.codigo}<br />Taller: {ticket.taller}{ticket.sede ? ' · ' + ticket.sede : ''}
          <div style={{ borderTop: '1px dashed #999', margin: '8px 0' }} />Rines: {g.rines.length} de {servRinesDeItems(ticket.items).length}<br />{g.rines.map((i) => <span key={i}>· Rin {i + 1}{servCodigo(sv.rines[i]) ? ' · ' + servCodigo(sv.rines[i]) : ''}<br /></span>)}
          <div style={{ borderTop: '1px dashed #999', margin: '8px 0' }} />Motivo: {g.motivo}<br />Reclamo: {g.desc}
          <div style={{ borderTop: '1px dashed #999', margin: '8px 0' }} />Recibe: {g.porNombre} (Salvallantas)<br />Entrega estimada: {garFechaEstimada(g)}<br /><br />Firma taller: ______________
          <div style={{ borderTop: '1px dashed #999', margin: '8px 0' }} /><div style={{ textAlign: 'center' }}>Sin costo · no genera factura</div>
        </div>
        <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
          <button type="button" onClick={onCerrar} style={{ flex: 1, border: `1px solid ${TOKENS.borderInput}`, background: TOKENS.surface, color: TOKENS.primary, borderRadius: 11, padding: '11px', fontFamily: 'inherit', fontWeight: 800, cursor: 'pointer' }}>Cerrar</button>
          <button type="button" onClick={() => { alert('Enviado a la impresora Bluetooth.'); onCerrar(); }} style={{ flex: 1, border: 0, background: TOKENS.navyDark || TOKENS.primary, color: '#fff', borderRadius: 11, padding: '11px', fontFamily: 'inherit', fontWeight: 800, cursor: 'pointer' }}>Imprimir</button>
        </div>
      </div>
    </div>, document.body);
}
// Celular · Recoger › Garantía: el taller devuelve un rin días después de entregado.
function GarantiaRecogerMovil({ onListo }) {
  const [q, setQ] = React.useState('');
  const [sel, setSel] = React.useState(null);
  const [v, setV] = React.useState(garVacio);
  const [toc, setToc] = React.useState(false);
  const [conf, setConf] = React.useState(false);
  const [tk, setTk] = React.useState(null);
  const enCurso = window.getRutaEnCurso ? window.getRutaEnCurso() : null;
  const ent = (window.loadEntregados ? window.loadEntregados() : []).map((e) => ({ ...e, id: e.ticketId, fecha: e.fechaRecogido }));
  const k = q.trim().toLowerCase();
  const L = ent.filter((e) => !garantiaAbierta(e.id) && (!k || `${e.placa} ${e.codigo} ${e.taller} ${e.sede}`.toLowerCase().includes(k)))
    .sort((a, b) => ((enCurso && b.taller === enCurso.taller ? 1 : 0) - (enCurso && a.taller === enCurso.taller ? 1 : 0)) || (b.createdAt || 0) - (a.createdAt || 0)).slice(0, 30);
  const f = garFaltas(v);
  const caja = { background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 14, padding: '12px 14px', marginBottom: 10 };
  const Cab = window.CabeceraPlaca;
  const corta = (f) => String(f || '').replace(/\s/g, '').slice(0, 5);
  const nR = (e) => servRinesDeItems(e.items).length;
  if (!sel) return (
    <div>
      <div style={{ ...caja, padding: 14 }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: TOKENS.text, marginBottom: 6 }}>¿De qué entrega?</div>
        <div style={{ position: 'relative' }}>
          <div style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', display: 'flex', pointerEvents: 'none' }}>{I.consultar(16, TOKENS.textMuted)}</div>
          <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Buscar placa u orden entregada" style={{ width: '100%', boxSizing: 'border-box', border: `1px solid ${TOKENS.borderInput}`, borderRadius: 10, padding: '11px 12px 11px 36px', fontSize: 14, fontFamily: 'inherit', background: TOKENS.surfaceLow, color: TOKENS.text, outline: 'none' }} />
        </div>
        {enCurso && !k && <div style={{ fontSize: 12, color: TOKENS.textMuted, margin: '10px 0 2px' }}>Primero las de <b>{enCurso.taller}{enCurso.sede ? ' · ' + enCurso.sede : ''}</b> (parada en curso)</div>}
        <div style={{ marginTop: 6 }}>
          {L.map((e) => <div key={e.id} onClick={() => { setSel(e); setV(garVacio()); setToc(false); }} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 0', borderTop: `1px solid ${TOKENS.border}`, cursor: 'pointer' }}>
            {Cab ? <Cab ticket={{ ...e, express: false, id: null }} /> : <b>{e.placa} · {e.codigo}</b>}
            <div style={{ flex: 1, minWidth: 0, fontSize: 12.5, lineHeight: 1.4 }}><b style={{ fontSize: 13 }}>{e.taller}</b>{e.sede ? <span style={{ color: TOKENS.textMuted }}> · {e.sede}</span> : null}<br /><span style={{ color: TOKENS.textMuted }}>Entregada {corta(e.fechaEntrega)} · {nR(e)} {nR(e) === 1 ? 'rin' : 'rines'}</span></div>
            {I.chevRight(14, TOKENS.textSubtle)}
          </div>)}
          {!L.length && <div style={{ padding: '12px 0', fontSize: 12.5, color: TOKENS.textMuted }}>No hay entregas con esa búsqueda.</div>}
        </div>
      </div>
    </div>);
  return (
    <div>
      <div style={{ ...caja, padding: 14 }}>
        {Cab ? <Cab ticket={{ ...sel, id: null }} /> : <b>{sel.placa} · {sel.codigo}</b>}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 8, fontSize: 12.5, color: TOKENS.textMuted }}>
          <span>{sel.taller}{sel.sede ? ' · ' + sel.sede : ''} · Entregada {corta(sel.fechaEntrega)}</span>
          <button type="button" onClick={() => setSel(null)} style={{ border: 0, background: 'none', color: TOKENS.primary, fontFamily: 'inherit', fontWeight: 700, fontSize: 13, cursor: 'pointer', padding: 0 }}>Cambiar</button>
        </div>
      </div>
      <GarantiaCampos ticket={sel} v={v} setV={setV} toc={toc} />
      <div style={{ display: 'flex', gap: 8 }}>
        {window.IconAction ? <window.IconAction title="Cancelar" onClick={() => setSel(null)}>{I.x(20, TOKENS.danger)}</window.IconAction> : null}
        <Button variant="primary" full disabled={f.length > 0} onClick={() => { setToc(true); if (!f.length) setConf(true); }} style={{ padding: '13px', fontSize: 15 }}>Registrar garantía</Button>
      </div>
      {f.length > 0 && window.MotivoBloqueo && <window.MotivoBloqueo>Para registrar falta: {f.join(', ')}.</window.MotivoBloqueo>}
      {conf && window.ConfirmActionModal && <window.ConfirmActionModal tone="primary" icon={<span style={{ fontSize: 22, color: GAR_COLOR.fg }}>↺</span>} title="Registrar garantía" confirmLabel="Registrar"
      ticket={sel} 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); const g = crearGarantia(sel.id, v); setTk({ t: sel, g }); }} />}
      {tk && <GarantiaTicket ticket={tk.t} g={tk.g} onCerrar={() => { setTk(null); setSel(null); onListo && onListo(); }} />}
    </div>);
}
// Celular · Entregar: garantías abiertas por entregar (encima de la lista).
function GarantiasPorEntregarMovil({ q = '', onVer }) {
  const [, r] = React.useState(0);
  React.useEffect(() => { const h = () => r((n) => n + 1); window.addEventListener('rodando-servicios', h); return () => window.removeEventListener('rodando-servicios', h); }, []);
  const ent = (window.loadEntregados ? window.loadEntregados() : []);
  let L = []; ent.forEach((e) => { const g = garantiaAbierta(e.ticketId); if (g) L.push({ e, g, est: garEstado(g) }); });
  if (q) L = L.filter(({ e }) => [e.placa, e.codigo, e.taller, e.sede, e.aseguradora].join(' ').toLowerCase().includes(q));
  L.sort((a, b) => a.est.orden - b.est.orden || b.est.dias - a.est.dias);
  if (!L.length) return null;
  const EC = [[TOKENS.dangerBg, TOKENS.dangerText], [TOKENS.warningBg, TOKENS.warningText], ['#fff2cc', '#7f6000'], [GAR_COLOR.bg, GAR_COLOR.fg]];
  const Tarjeta = window.TarjetaPlaca;
  return (
    <div style={{ marginTop: 14 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', margin: '0 2px 8px' }}>
        <span style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: '0.06em', color: TOKENS.textMuted, textTransform: 'uppercase' }}>↺ Garantías por entregar</span>
        <span style={{ fontSize: 11.5, fontWeight: 700, color: TOKENS.textSubtle }}>{L.length}</span>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {L.map(({ e, g, est }) => {
          const [cb, cf] = EC[est.orden] || EC[3];
          const tk = { ...e, id: e.ticketId, fecha: e.fechaRecogido, items: [{ tipo: 'rin', cantidad: (g.rines || []).length }] };
          return Tarjeta ? <Tarjeta key={g.id} ticket={tk} onClick={() => onVer && onVer(e)} onVer={() => onVer && onVer(e)}
            chip={<span style={{ fontSize: 11.5, fontWeight: 500, borderRadius: 99, padding: '3px 9px', whiteSpace: 'nowrap', background: cb, color: cf }}>{est.label}</span>}
            fechaK="Se espera" fechaV={garFechaEstimada(g)} /> : null;
        })}
      </div>
    </div>);
}

// ─── Seguimiento: rines esperando autorización ────────────────────────────
// ─── Rin que sale sin reparar (21/11/2026) ─────────────────────────────────
// Al entregar se marca qué rin sale sin reparar, el motivo y (opcional) la foto de la carta.
// Ese rin no se cobra: su valor queda en $0 en Servicios y cobro.
const SR_MOTIVOS = ['No se pudo reparar', 'El taller no autorizó', 'Otro'];
const srVacio = () => ({ on: false, rines: [], motivo: SR_MOTIVOS[0], det: '', foto: null });
const srFaltas = (v) => v && v.on ? [!v.rines.length && 'qué rin sale sin reparar', v.motivo === 'Otro' && !String(v.det || '').trim() && 'el motivo'].filter(Boolean) : [];
const srLista = (v) => v && v.on ? v.rines.map((i) => ({ i, motivo: v.motivo === 'Otro' ? String(v.det || '').trim() : v.motivo, foto: v.foto || null })) : [];
function servMarcarSinReparar(t, lista) {
  if (!lista || !lista.length) return;
  const s = servDe(t); const now = servAhora();
  lista.forEach((x) => { if (s.rines[x.i]) s.rines[x.i] = { ...s.rines[x.i], sinReparar: { motivo: x.motivo, foto: x.foto || null, fecha: now.fecha, por: servYo() } }; });
  servGuardar(t.id, s);
}
// 23/11/2026: marca "exacta" de rines sin reparar (desde la ficha, antes de entregar): los de la lista
// quedan marcados y los demás se desmarcan.
function servFijarSinReparar(t, lista) {
  const s = servDe(t); const now = servAhora(); const m = {}; (lista || []).forEach((x) => { m[x.i] = x; });
  s.rines = s.rines.map((r, i) => { if (m[i]) return { ...r, sinReparar: { motivo: m[i].motivo, foto: m[i].foto || null, fecha: (r.sinReparar && r.sinReparar.fecha) || now.fecha, por: (r.sinReparar && r.sinReparar.por) || servYo() } }; const { sinReparar, ...rest } = r; return rest; });
  servGuardar(t.id, s);
  try { window.dispatchEvent(new Event('rodando-servicios')); } catch (e) {}
}
// Valor inicial del bloque "sin reparar" de Registrar entrega: lo que ya se marcó en la revisión.
function srDesdeServicios(t) {
  const v = srVacio(); try { const s = servDe(t); const L = s.rines.map((r, i) => r.sinReparar ? i : -1).filter((i) => i >= 0);
    if (!L.length) return v; const sr = s.rines[L[0]].sinReparar; const motivo = SR_MOTIVOS.includes(sr.motivo) ? sr.motivo : 'Otro';
    return { ...v, on: true, rines: L, motivo, det: motivo === 'Otro' ? sr.motivo : '', foto: sr.foto || null }; } catch (e) { return v; }
}
// Ventana para marcar rines no reparables / no autorizados desde la ficha (PC y celular).
function SinRepararDlg({ r, onCancel, onOk }) {
  const n = servDe(r).rines.length;
  const [v, setV] = React.useState(() => { const x = srDesdeServicios(r); return { ...x, on: true, rines: x.rines.length ? x.rines : n === 1 ? [0] : [] }; });
  const [toc, setToc] = React.useState(false);
  const yaHabia = servDe(r).rines.some((x) => x.sinReparar);
  const faltas = srFaltas(v);
  return ReactDOM.createPortal(
    <div onClick={onCancel} style={{ position: 'fixed', inset: 0, background: 'rgba(11,28,48,.45)', zIndex: 1250, display: 'grid', placeItems: 'center', padding: 14 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: TOKENS.surface, borderRadius: 18, padding: 20, width: 440, maxWidth: '100%', maxHeight: '90vh', overflow: 'auto', boxSizing: 'border-box' }}>
        <div style={{ textAlign: 'center', fontWeight: 800, fontSize: 17 }}>Rin que no se repara</div>
        {window.CabeceraPlaca && <div style={{ display: 'flex', justifyContent: 'center', margin: '10px 0 4px' }}><window.CabeceraPlaca ticket={r} /></div>}
        <div style={{ textAlign: 'center', fontSize: 12.5, color: TOKENS.textMuted, margin: '4px 0 6px', lineHeight: 1.45 }}>Queda en $0 y sale en Novedades. Al entregar ya viene marcado.</div>
        <SinRepararCampos nRines={n} v={v} setV={setV} toc={toc} sinToggle />
        <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
          {yaHabia && <button type="button" onClick={() => onOk([])} style={{ border: `1.5px solid ${TOKENS.borderInput}`, background: TOKENS.surface, color: TOKENS.danger, borderRadius: 10, padding: '11px 12px', fontFamily: 'inherit', fontSize: 13, fontWeight: 700, cursor: 'pointer' }}>Quitar marca</button>}
          <button type="button" onClick={onCancel} style={{ flex: 1, border: `1px solid ${TOKENS.borderInput}`, background: TOKENS.surface, color: TOKENS.primary, borderRadius: 10, padding: '11px 12px', fontFamily: 'inherit', fontSize: 13.5, fontWeight: 700, cursor: 'pointer' }}>Cancelar</button>
          <button type="button" onClick={() => { if (faltas.length) { setToc(true); return; } onOk(srLista(v)); }} style={{ flex: 1, border: 0, background: TOKENS.primary, color: '#fff', borderRadius: 10, padding: '11px 12px', fontFamily: 'inherit', fontSize: 13.5, fontWeight: 800, cursor: 'pointer' }}>Guardar</button>
        </div>
      </div>
    </div>, document.body);
}
function SinRepararCampos({ nRines, v, setV, toc, sinToggle }) {
  const set = (p) => setV({ ...v, ...p });
  const fileRef = React.useRef(null);
  const rojo = toc && !v.rines.length;
  const tomar = (e) => { const f = e.target.files && e.target.files[0]; if (!f) return; const rd = new FileReader(); rd.onload = async () => { const small = window.downscaleDataURL ? await window.downscaleDataURL(rd.result, 1100, 0.7) : rd.result; set({ foto: small }); }; rd.readAsDataURL(f); e.target.value = ''; };
  const lbl = { fontSize: 10.5, fontWeight: 800, letterSpacing: '0.06em', color: TOKENS.textMuted, textTransform: 'uppercase', margin: '12px 0 6px' };
  return <>
    {!sinToggle && <button type="button" onClick={() => set({ on: !v.on, ...(!v.on && nRines === 1 && !v.rines.length ? { rines: [0] } : {}) })} style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%', textAlign: 'left', border: `1.5px solid ${v.on ? TOKENS.danger : TOKENS.border}`, background: TOKENS.surface, borderRadius: 12, padding: '11px 12px', marginTop: 14, cursor: 'pointer', fontFamily: 'inherit' }}>
      <span style={{ fontSize: 16, color: TOKENS.danger, width: 18, textAlign: 'center' }}>⊘</span>
      <span style={{ flex: 1 }}><b style={{ display: 'block', fontSize: 14, color: TOKENS.text }}>Algún rin sale sin reparar</b><span style={{ fontSize: 12, color: TOKENS.textMuted }}>No se cobra · se puede adjuntar la carta</span></span>
      <span style={{ width: 40, height: 22, borderRadius: 99, background: v.on ? TOKENS.danger : TOKENS.borderInput, position: 'relative', flexShrink: 0 }}><span style={{ position: 'absolute', top: 2, left: v.on ? 20 : 2, width: 18, height: 18, borderRadius: 99, background: '#fff', transition: 'left .15s' }} /></span>
    </button>}
    {v.on && <div style={{ padding: '2px 2px 4px' }}>
      <div style={lbl}>¿Qué rin? {rojo && <span style={{ color: TOKENS.danger, textTransform: 'none', letterSpacing: 0, fontWeight: 600 }}>· escoge al menos uno</span>}</div>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        {Array.from({ length: nRines }, (_, i) => { const on = v.rines.includes(i); return <button key={i} type="button" onClick={() => set({ rines: on ? v.rines.filter((x) => x !== i) : [...v.rines, i].sort((a, b) => a - b) })} style={{ border: `1.5px solid ${on ? TOKENS.primary : rojo ? TOKENS.danger : TOKENS.borderInput}`, background: on ? TOKENS.primaryBg : TOKENS.surface, color: on ? TOKENS.primary : TOKENS.text, borderRadius: 10, padding: '8px 14px', fontFamily: 'inherit', fontSize: 13.5, fontWeight: 700, cursor: 'pointer' }}>{on ? '✓ ' : ''}Rin {i + 1}</button>; })}
      </div>
      <div style={lbl}>Motivo</div>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        {SR_MOTIVOS.map((m) => { const on = v.motivo === m; return <button key={m} type="button" onClick={() => set({ motivo: m })} style={{ border: `1px solid ${on ? TOKENS.primary : TOKENS.borderInput}`, background: on ? TOKENS.primary : TOKENS.surface, color: on ? '#fff' : TOKENS.text, borderRadius: 999, padding: '6px 12px', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>{m}</button>; })}
      </div>
      {v.motivo === 'Otro' && <input value={v.det} onChange={(e) => set({ det: e.target.value })} placeholder="Escribe el motivo" style={{ marginTop: 8, width: '100%', boxSizing: 'border-box', border: `1px solid ${toc && !String(v.det || '').trim() ? TOKENS.danger : TOKENS.borderInput}`, background: TOKENS.surfaceLow, borderRadius: 10, padding: '10px 11px', fontFamily: 'inherit', fontSize: 14, color: TOKENS.text, outline: 'none' }} />}
      <div style={lbl}>Foto de la carta <span style={{ textTransform: 'none', letterSpacing: 0, fontWeight: 600, color: TOKENS.textSubtle }}>(opcional)</span></div>
      <input ref={fileRef} type="file" accept="image/*" onChange={tomar} style={{ display: 'none' }} />
      {v.foto ? <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}><img src={v.foto} alt="Carta" style={{ width: 64, height: 64, objectFit: 'cover', borderRadius: 9, border: `1px solid ${TOKENS.border}` }} /><button type="button" onClick={() => set({ foto: null })} style={{ background: 'none', border: 0, color: TOKENS.danger, fontFamily: 'inherit', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>Quitar foto</button></div> :
      <button type="button" onClick={() => fileRef.current && fileRef.current.click()} style={{ width: '100%', border: `1.5px dashed ${TOKENS.borderInput}`, background: TOKENS.surface, borderRadius: 12, padding: '14px', fontFamily: 'inherit', fontSize: 13.5, fontWeight: 600, color: TOKENS.primary, cursor: 'pointer' }}>＋ Agregar foto de la carta</button>}
    </div>}
  </>;
}
// ─── Historial de pausas (21/11/2026) ──────────────────────────────────────
// Cada rin guarda sus pausas cerradas en `pausas` y la actual (o la última) en `aut`.
window.PC_MEMO = window.PC_MEMO || {};
const pausaClave = (p) => (p.desdeIso || '') + (p.hora || '');
function pausasDeRin(rin) { return [...((rin && rin.pausas) || []), rin && rin.aut].filter((p) => p && p.desdeIso).sort((a, b) => pausaClave(b).localeCompare(pausaClave(a))); }
function pausasDePlaca(r) { const s = servDe(r); const out = []; s.rines.forEach((rin, i) => pausasDeRin(rin).forEach((p) => out.push({ i, p }))); return out; }
function pausaMasReciente(L) { return [...L].sort((a, b) => (a.p.estado === 'espera' ? 0 : 1) - (b.p.estado === 'espera' ? 0 : 1) || pausaClave(b.p).localeCompare(pausaClave(a.p)))[0]; }
const pausaEst = (p) => p.estado === 'espera' ? ['En pausa', PAUSA_COLOR.bg, PAUSA_COLOR.fg, PAUSA_COLOR.solid] : p.estado === 'si' ? ['Autorizado', TOKENS.successBg, TOKENS.successText, '#2f6b47'] : ['No autorizado', '#efe9f7', '#6c4aa6', '#6c4aa6'];
const pausaCorta = (f) => String(f || '').slice(0, 5);
const pausaFechas = (p, corto) => p.estado === 'espera' ? `desde ${corto ? pausaCorta(p.desde) : p.desde}` : `${pausaCorta(p.desde)} → ${corto ? pausaCorta(p.hasta) : (p.hasta || '')}`;
const pausaDias = (p) => { const n = servDiasEsperando(p); return `${n} ${n === 1 ? 'día hábil' : 'días hábiles'}`; };
const pausaMotivo = (p) => [p.motivo, p.det].filter(Boolean).join(' · ');
const rinesTxt = (L) => { const r = [...new Set(L)].sort((a, b) => a - b).map((i) => `Rin ${i + 1}`); return r.length > 1 ? r.slice(0, -1).join(', ') + ' y ' + r[r.length - 1] : r[0] || ''; };
function PausaLinea({ i, p, der, onClick }) {
  const e = pausaEst(p);
  return <div onClick={onClick} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', cursor: onClick ? 'pointer' : 'default' }}>
    <PcChip bg={e[1]} fg={e[2]}>{e[0]}</PcChip>
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontSize: 13, fontWeight: 600 }}>Rin {i + 1} <span style={{ fontWeight: 500, color: TOKENS.textMuted }}>· {pausaFechas(p)}</span></div>
      <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>{pausaDias(p)} en pausa</div>
      {pausaMotivo(p) && <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>{pausaMotivo(p)}</div>}
    </div>
    {der}
  </div>;
}
function PausaTl({ items }) {
  return <div style={{ position: 'relative', paddingLeft: 22 }}>
    <span style={{ position: 'absolute', left: 7, top: 6, bottom: 12, borderLeft: `2px solid ${TOKENS.border}` }} />
    {items.map((x, k) => <div key={k} style={{ position: 'relative', paddingBottom: 10, opacity: x.anu ? 0.6 : 1 }}>
      <span style={{ position: 'absolute', left: -20, top: 3, width: 12, height: 12, borderRadius: 99, border: '2px solid #fff', boxSizing: 'border-box', background: x.c, boxShadow: `0 0 0 1px ${x.c}` }} />
      <b style={{ fontSize: 13, fontWeight: 600, textDecoration: x.anu ? 'line-through' : 'none' }}>{x.t}</b>
      {x.d && <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 2, lineHeight: 1.4 }}>{x.d}</div>}
    </div>)}
  </div>;
}
function pausaEventos(p) {
  const h12 = (x) => x ? (window.formatHora12 ? window.formatHora12(x) : x) : '';
  const L = [{ c: PAUSA_COLOR.solid, t: p.estado === 'espera' ? 'En pausa · esperando autorización' : 'En pausa', d: [p.desde, h12(p.hora), p.por, pausaMotivo(p)].filter(Boolean).join(' · ') }];
  (p.ev || []).forEach((e) => L.push({ c: e.anu ? TOKENS.textSubtle : TOKENS.primary, t: e.tipo, d: [e.fecha, e.por, e.det && `“${e.det}”`, e.anu && `anulado: ${e.anu.motivo}`].filter(Boolean).join(' · '), anu: !!e.anu }));
  if (p.estado !== 'espera') { const e = pausaEst(p); L.push({ c: e[3], t: e[0], d: [p.hasta, h12(p.hastaHora), p.cerradoPor].filter(Boolean).join(' · ') }); }
  return L;
}
// Ficha › Historial: un solo campo. Cerrado = lo más reciente; abierto = cada rin con sus pausas.
function PcPausasFicha({ r, onVer }) {
  // 23/11/2026: "Novedades" de la ficha: pausas + rines no reparables / no autorizados.
  const [ab, setAb] = React.useState(false);
  const [, bump] = React.useReducer((n) => n + 1, 0);
  React.useEffect(() => { window.addEventListener('rodando-servicios', bump); return () => window.removeEventListener('rodando-servicios', bump); }, []);
  const ns = novedadesLista([r._estado ? r : { ...r, _estado: 'pend' }]);
  if (!ns.length) return null;
  const ult = ns.find((x) => x.tipo === 'pausa' && x.p.estado === 'espera') || ns[0];
  const rines = [...new Set(ns.map((x) => x.i))].sort((a, b) => a - b);
  const c = novChip(ult);
  const desc = ult.tipo === 'pausa' ? <>{pausaFechas(ult.p)}<div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 2, fontWeight: 500 }}>{pausaDias(ult.p)} en pausa{pausaMotivo(ult.p) ? ' · ' + pausaMotivo(ult.p) : ''}</div></> : <>{ult.fecha}<div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 2, fontWeight: 500 }}>{ult.motivo} · no se cobra</div></>;
  const flecha = <span style={{ fontSize: 12, color: TOKENS.textMuted, whiteSpace: 'nowrap' }}>{ns.length > 1 ? `${ns.length} novedades ` : ''}{ab ? '▴' : '▾'}</span>;
  const item = (x) => { if (x.tipo === 'pausa') { const e = pausaEst(x.p); return { c: e[3], t: `Pausa · ${e[0]}`, d: [pausaFechas(x.p, true), pausaDias(x.p), pausaMotivo(x.p)].filter(Boolean).join(' · ') }; } const k = novChip(x); return { c: k[2], t: k[0], d: [x.fecha, x.por, x.motivo, 'no se cobra'].filter(Boolean).join(' · ') }; };
  return <div style={{ border: `1px solid ${TOKENS.border}`, borderRadius: 12, overflow: 'hidden', marginTop: 14, background: TOKENS.surface }}>
    <div onClick={() => setAb(!ab)} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', cursor: 'pointer' }}>
      <PcChip bg={c[1]} fg={c[2]}>{c[0]}</PcChip>
      <div style={{ flex: 1, minWidth: 0, fontSize: 13, fontWeight: 600 }}>Rin {ult.i + 1} <span style={{ fontWeight: 500, color: TOKENS.textMuted }}>· </span>{desc}</div>
      {flecha}
    </div>
    {ab && <div style={{ padding: '2px 12px 10px', borderTop: `1px dashed ${TOKENS.border}` }}>
      {rines.map((i) => { const L = ns.filter((x) => x.i === i); return <div key={i}>
        <div style={{ margin: '10px 0 6px', fontSize: 13.5, fontWeight: 700 }}>Rin {i + 1} <span style={{ fontSize: 12, fontWeight: 500, color: TOKENS.textSubtle }}>· {L.length} {L.length === 1 ? 'novedad' : 'novedades'}</span></div>
        <PausaTl items={L.map(item)} />
      </div>; })}
      {onVer && <div style={{ textAlign: 'right', marginTop: 4 }}><button type="button" onClick={() => onVer(ns.some((x) => x.tipo === 'pausa' && x.p.estado === 'espera'))} style={{ background: 'none', border: 0, padding: 0, color: TOKENS.primary, fontFamily: 'inherit', fontSize: 12.5, fontWeight: 700, cursor: 'pointer' }}>Ver en Novedades ›</button></div>}
    </div>}
  </div>;
}
// Seguimiento › Historial: una fila por rin; las pausas en tarjetas con scroll horizontal (21/11/2026).
// Se ven tres; con más aparecen ‹ › y "1–3 de N", y un desvanecido a la derecha.
function PausasFilaRin({ i, ps }) {
  const ref = React.useRef(null);
  const [pos, setPos] = React.useState(0);
  const [fin, setFin] = React.useState(false);
  const n = ps.length;
  const paso = () => { const c = ref.current && ref.current.firstChild; return c ? c.offsetWidth + 10 : 1; };
  const onScroll = () => { const el = ref.current; if (!el) return; setPos(Math.round(el.scrollLeft / paso())); setFin(el.scrollLeft + el.clientWidth >= el.scrollWidth - 4); };
  const mover = (d) => { const el = ref.current; if (el) el.scrollBy({ left: d * paso() * 3, behavior: 'smooth' }); };
  const flecha = (d, off) => <button type="button" onClick={() => mover(d)} disabled={off} style={{ width: 28, height: 28, borderRadius: 8, border: `1px solid ${TOKENS.borderInput}`, background: TOKENS.surface, color: TOKENS.primary, cursor: off ? 'default' : 'pointer', opacity: off ? 0.4 : 1, fontSize: 14, fontWeight: 700, fontFamily: 'inherit' }}>{d < 0 ? '‹' : '›'}</button>;
  return <div>
    <div style={{ display: 'flex', alignItems: 'center', margin: '12px 0 8px' }}>
      <span style={{ fontSize: 13.5, fontWeight: 700 }}>Rin {i + 1} <span style={{ fontSize: 12, fontWeight: 500, color: TOKENS.textSubtle }}>· {n} {n === 1 ? 'pausa' : 'pausas'}{n > 1 ? ' · la más reciente a la izquierda' : ''}</span></span>
      {n > 3 && <span style={{ marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ fontSize: 12, color: TOKENS.textSubtle, marginRight: 4 }}>{pos + 1}–{Math.min(pos + 3, n)} de {n}</span>{flecha(-1, pos === 0)}{flecha(1, fin)}</span>}
    </div>
    <div style={{ position: 'relative' }}>
      <div ref={ref} onScroll={onScroll} style={{ display: 'flex', gap: 10, overflowX: n > 3 ? 'auto' : 'visible', scrollSnapType: 'x mandatory', paddingBottom: n > 3 ? 8 : 0, scrollbarWidth: 'thin' }}>
        {ps.map((p, k) => <div key={k} style={{ flex: '0 0 calc((100% - 20px) / 3)', minWidth: 0, scrollSnapAlign: 'start', border: `1px solid ${TOKENS.border}`, borderRadius: 12, padding: '11px 12px', background: TOKENS.surface, boxSizing: 'border-box' }}>
          <b style={{ display: 'block', fontSize: 13.5, fontWeight: 700 }}>Pausa {n - k}</b>
          <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 2, marginBottom: 10 }}>{pausaFechas(p, true)} · {pausaDias(p)}{p.estado === 'espera' ? ' · sigue abierta' : ''}</div>
          <PausaTl items={pausaEventos(p)} />
        </div>)}
      </div>
      {n > 3 && !fin && <div style={{ position: 'absolute', right: 0, top: 0, bottom: 8, width: 40, background: `linear-gradient(90deg, rgba(255,255,255,0), ${TOKENS.surface})`, pointerEvents: 'none' }} />}
    </div>
  </div>;
}
// Línea de eventos de una novedad (pausa = su bitácora; no reparable / no autorizado = marcado, servicio y carta).
function novedadEventos(x, onFoto) {
  const c = novChip(x);
  return x.tipo === 'pausa' ? pausaEventos(x.p) : (() => { const s = servDe(x.r); const rin = s.rines[x.i] || {}; const cod = servCodigo(rin); return [
            { c: c[2], t: x.nov === 'na' ? 'Marcado no autorizado' : 'Marcado no reparable', d: [x.fecha, x.por, x.motivo && `“${x.motivo}”`].filter(Boolean).join(' · ') },
            cod && { c: TOKENS.textSubtle, t: 'Servicio', d: <><span style={{ textDecoration: 'line-through' }}>{cod} · {pcPesos(rin.precio)}</span> → $ 0</> },
            x.foto ? { c: TOKENS.primary, t: 'Carta adjunta', d: <button type="button" onClick={() => onFoto(x.foto)} style={{ background: 'none', border: 0, padding: 0, color: TOKENS.primary, fontFamily: 'inherit', fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>Ver carta ›</button> } : { c: TOKENS.textSubtle, t: 'Sin carta', d: '' },
          ].filter(Boolean); })();
}
// Celular (23/11/2026): sección "Novedades" de la ficha. Las mismas tarjetas del PC, una debajo de otra.
function NovedadesFichaCel({ r, onFoto }) {
  const [, bump] = React.useReducer((n) => n + 1, 0);
  React.useEffect(() => { window.addEventListener('rodando-servicios', bump); return () => window.removeEventListener('rodando-servicios', bump); }, []);
  const ns = novedadesLista([r]).sort((a, b) => a.i - b.i || b.iso.localeCompare(a.iso));
  if (!ns.length) return null;
  const nPa = {}; ns.forEach((x) => { if (x.tipo === 'pausa') nPa[x.i] = (nPa[x.i] || 0) + 1; });
  const k = { ...nPa };
  return <div style={{ marginTop: 12 }}>
    <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: '.06em', color: TOKENS.textMuted, textTransform: 'uppercase', margin: '0 2px 8px' }}>Novedades · {ns.length}</div>
    {ns.map((x) => { const c = novChip(x); const abierta = x.tipo === 'pausa' && x.p.estado === 'espera';
      const titulo = x.tipo === 'pausa' ? `Rin ${x.i + 1} · Pausa ${k[x.i]--}` : `Rin ${x.i + 1} · ${c[0]}`;
      const sub = x.tipo === 'pausa' ? `${pausaFechas(x.p, true)} · ${pausaDias(x.p)}${abierta ? ' · sigue abierta' : ''}` : `${x.fecha} · ${x.r._estado === 'ent' ? 'salió sin reparar' : 'no se repara'}`;
      return <div key={x.k} style={{ background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 12, padding: '11px 12px', marginBottom: 8 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><b style={{ fontSize: 13.5, fontWeight: 700, flex: 1 }}>{titulo}</b><PcChip bg={c[1]} fg={c[2]}>{c[0]}</PcChip></div>
        <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 2, marginBottom: 10 }}>{sub}</div>
        <PausaTl items={novedadEventos(x, onFoto || (() => {}))} />
      </div>; })}
  </div>;
}
// 22/11/2026: fila de un rin con una tarjeta por novedad (mismo molde que las pausas), la más reciente a la izquierda.
function NovedadesFilaRin({ i, ns, focoK, onAccion, onFoto }) {
  const ref = React.useRef(null);
  const [pos, setPos] = React.useState(0);
  const [fin, setFin] = React.useState(false);
  const n = ns.length;
  const cel = window.PcCelCtx ? React.useContext(window.PcCelCtx) : false; // 27/11/2026: celular → tarjeta al 60 % y se asoma la siguiente
  const desliza = cel ? n > 1 : n > 3;
  const anchoT = cel ? (n > 1 ? '0 0 60%' : '0 0 100%') : '0 0 calc((100% - 20px) / 3)';
  const paso = () => { const c = ref.current && ref.current.firstChild; return c ? c.offsetWidth + 10 : 1; };
  const onScroll = () => { const el = ref.current; if (!el) return; setPos(Math.round(el.scrollLeft / paso())); setFin(el.scrollLeft + el.clientWidth >= el.scrollWidth - 4); };
  const mover = (d) => { const el = ref.current; if (el) el.scrollBy({ left: d * paso() * 3, behavior: 'smooth' }); };
  const flecha = (d, off) => <button type="button" onClick={() => mover(d)} disabled={off} style={{ width: 28, height: 28, borderRadius: 8, border: `1px solid ${TOKENS.borderInput}`, background: TOKENS.surface, color: TOKENS.primary, cursor: off ? 'default' : 'pointer', opacity: off ? 0.4 : 1, fontSize: 14, fontWeight: 700, fontFamily: 'inherit' }}>{d < 0 ? '‹' : '›'}</button>;
  React.useEffect(() => { if (!focoK || !ref.current) return; const k = ns.findIndex((x) => x.k === focoK); if (k > 2) ref.current.scrollLeft = k * paso(); }, [focoK]);
  const nPa = ns.filter((x) => x.tipo === 'pausa').length; let kp = nPa;
  const btn = (t, l, st) => <button type="button" onClick={() => onAccion(t)} style={{ flex: t === 'nuevo' ? '1 1 100%' : 1, border: `1.5px solid ${TOKENS.borderInput}`, background: TOKENS.surface, color: TOKENS.primary, borderRadius: 9, padding: '6px 8px', fontFamily: 'inherit', fontSize: 12, fontWeight: 700, cursor: 'pointer', ...st }}>{l}</button>;
  return <div>
    <div style={{ display: 'flex', alignItems: 'center', margin: '12px 0 8px' }}>
      <span style={{ fontSize: 13.5, fontWeight: 700 }}>Rin {i + 1} <span style={{ fontSize: 12, fontWeight: 500, color: TOKENS.textSubtle }}>· {n} {n === 1 ? 'novedad' : 'novedades'}{n > 1 ? (cel ? ' · desliza para ver más' : ' · la más reciente a la izquierda') : ''}</span></span>
      {!cel && n > 3 && <span style={{ marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ fontSize: 12, color: TOKENS.textSubtle, marginRight: 4 }}>{pos + 1}–{Math.min(pos + 3, n)} de {n}</span>{flecha(-1, pos === 0)}{flecha(1, fin)}</span>}
    </div>
    <div style={{ position: 'relative' }}>
      <div ref={ref} onScroll={onScroll} style={{ display: 'flex', gap: 10, overflowX: desliza ? 'auto' : 'visible', scrollSnapType: 'x mandatory', paddingBottom: desliza ? 8 : 0, scrollbarWidth: 'thin' }}>
        {ns.map((x) => { const on = x.k === focoK; const c = novChip(x); const abierta = x.tipo === 'pausa' && x.p.estado === 'espera';
          const titulo = x.tipo === 'pausa' ? `Pausa ${kp--}` : c[0];
          const sub = x.tipo === 'pausa' ? `${pausaFechas(x.p, true)} · ${pausaDias(x.p)}${abierta ? ' · sigue abierta' : ''}` : `${x.fecha} · sale sin reparar`;
          const items = novedadEventos(x, onFoto);
          return <div key={x.k} style={{ flex: anchoT, minWidth: 0, scrollSnapAlign: 'start', border: `1px solid ${on ? TOKENS.primaryBorder : TOKENS.border}`, padding: '11px 12px', boxShadow: 'none', borderRadius: 12, background: TOKENS.surface, boxSizing: 'border-box', display: 'flex', flexDirection: 'column' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><b style={{ fontSize: 13.5, fontWeight: 700, flex: 1 }}>{titulo}</b><PcChip bg={c[1]} fg={c[2]}>{c[0]}</PcChip></div>
            <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 2, marginBottom: 10 }}>{sub}</div>
            <PausaTl items={items} />
            {abierta && onAccion && <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 'auto', paddingTop: 10, borderTop: `1px solid ${TOKENS.border}` }}>
              {btn('nuevo', '＋ Seguimiento')}{btn('no', 'No autorizada', { color: TOKENS.danger })}{btn('si', 'Autorizada', { background: TOKENS.success, border: 0, color: '#fff' })}</div>}
          </div>; })}
      </div>
      {desliza && !fin && <div style={{ position: 'absolute', right: 0, top: 0, bottom: 8, width: 40, background: `linear-gradient(90deg, rgba(255,255,255,0), ${TOKENS.surface})`, pointerEvents: 'none' }} />}
    </div>
  </div>;
}
// Ir a Seguimiento con la placa filtrada (desde la ficha).
function pcVerSeguimiento(placa, abierta) { window.rdSegFiltro = { tab: abierta ? 'pend' : 'hist', q: placa }; window.dispatchEvent(new CustomEvent('pc-ir', { detail: 'seguimiento' })); }
// 22/11/2026: Novedades por fecha: cada pausa y cada rin no reparable / no autorizado, la más reciente primero.
const novIso = (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')}` : ''; };
function novedadesLista(regs) {
  const out = [];
  regs.forEach((r) => {
    if (r._estado === 'anu') return;
    const s = servDe(r); const e = r._ent || null;
    s.rines.forEach((rin, i) => {
      pausasDeRin(rin).forEach((p) => out.push({ k: `${r.id}#${i}#p${pausaClave(p)}`, tipo: 'pausa', r, i, p, nov: p.estado === 'no' ? 'na' : 'pausa', motivo: p.motivo || '', iso: (p.desdeIso || '') + (p.hora || '') }));
      const sr = rin.sinReparar || (e && (e.sinReparar || []).find((x) => x.i === i));
      if (sr) { const f = sr.fecha || (e && e.fechaEntrega) || ''; out.push({ k: `${r.id}#${i}#sr`, tipo: 'sr', r, i, nov: /autoriz/i.test(sr.motivo || '') ? 'na' : 'nr', motivo: sr.motivo || '', fecha: f, por: sr.por || (e && e.entregadoPorNombre) || '', foto: sr.foto || null, iso: novIso(f) + '99' }); }
    });
  });
  return out.sort((a, b) => b.iso.localeCompare(a.iso));
}
const novChip = (x) => x.tipo === 'pausa' ? pausaEst(x.p) : x.nov === 'na' ? ['No autorizado', '#efe9f7', '#6c4aa6'] : ['No reparable', '#fbe3e1', '#9c443c'];
function PcSeguimiento({ regs, toast, ir }) {
  const cel = window.PcCelCtx ? React.useContext(window.PcCelCtx) : false; // 27/11/2026: versión celular (admin)
  const cat = loadCatServicios();
  const ini = React.useRef(window.rdSegFiltro || window.PC_MEMO.seg || {}).current; window.rdSegFiltro = null;
  const [tab, setTab] = React.useState(ini.tab || 'pend');
  const [q, setQ] = React.useState(ini.q || '');
  const [selH, setSelH] = React.useState(ini.selH || null);
  const kq = q.trim().toLowerCase();
  const coincide = (r) => !kq || `${r.placa} ${r.codigo} ${r.taller} ${r.sede || ''}`.toLowerCase().includes(kq);
  const L = servPendientes(regs).filter((x) => coincide(x.r));
  const [selK, setSelK] = React.useState(ini.selK || null);
  // 22/11/2026: Historial › Por placa | Por fecha (lista de novedades a la izquierda, el mismo panel a la derecha).
  const [vista, setVista] = React.useState(ini.vista || 'placa');
  const [fil, setFil] = React.useState(ini.fil || 'todas');
  const [selF, setSelF] = React.useState(null);
  const [mes, setMes] = React.useState(!!ini.mes);
  React.useEffect(() => { window.PC_MEMO.seg = { tab, q, selH, selK, vista, fil, selF, mes }; }, [tab, q, selH, selK, vista, fil, selF, mes]);
  const [dlg, setDlg] = React.useState(null);
  const NF = novedadesLista(regs).filter((x) => coincide(x.r));
  const mesIso = new Date().toISOString().slice(0, 7);
  const NFv = NF.filter((x) => (fil === 'todas' || (fil === 'pausa' ? x.tipo === 'pausa' : x.nov === fil)) && (!mes || x.iso.startsWith(mesIso)));
  const fSel = NFv.find((x) => x.k === selF) || NFv[0] || null;
  const enFecha = tab === 'hist' && vista === 'fecha';
  // Acciones sobre una pausa abierta desde el historial (su tarjeta trae los botones).
  const [accT, setAccT] = React.useState(null);
  const sel = tab === 'hist' ? (accT ? servPendientes(regs).find((x) => x.r.id === accT.id && x.i === accT.i) : null) : (L.find((x) => `${x.r.id}#${x.i}` === selK) || L[0]);
  const [foto, setFoto] = React.useState(null);
  const [ficha, setFicha] = React.useState(null);
  const ev = sel ? (sel.rin.aut.ev || []) : [];
  const accion = (fn, msg, tono) => { servActualizarRin(sel.r, sel.i, fn); pcAvisar(); toast(msg, tono); };
  const cerrar = (si, valor) => {
    const now = servAhora();
    accion((rin) => { rin.aut.estado = si ? 'si' : 'no'; rin.aut.hastaIso = now.iso; rin.aut.hasta = now.fecha; rin.aut.hastaHora = now.hora; rin.aut.cerradoPor = servYo(); if (si && valor) { rin.aut.valorAutorizado = valor; rin.precio = valor; } },
    si ? `Autorizada · ${sel.r.placa} rin ${sel.i + 1} · el plazo sigue` : `No autorizada · ${sel.r.placa} rin ${sel.i + 1}`, si ? 'g' : true);
    setSelK(null); setAccT(null);
  };
  const det = (k, v) => <div style={{ display: 'grid', gridTemplateColumns: '150px 1fr', borderTop: `1px solid ${TOKENS.border}` }}><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 }}>{v}</span></div>;
  const izq =
  <>
      {L.map((x) => { const k = `${x.r.id}#${x.i}`; const on = sel && k === `${sel.r.id}#${sel.i}`; const ult = (x.rin.aut.ev || []).filter((e) => !e.anu).slice(-1)[0];
        return (
          // 19/11/2026: tarjetas blancas sobre gris; la seleccionada con borde azul marcado.
          <div key={k} onClick={() => setSelK(k)} style={{ background: TOKENS.surface, border: on ? `2px solid ${TOKENS.primary}` : '1px solid #dfe5ee', borderRadius: 12, padding: on ? 11 : 12, marginBottom: 8, cursor: 'pointer', boxShadow: on ? '0 2px 8px rgba(31,61,119,.12)' : 'none' }}>
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: 8 }}>{window.PlacaOrdenChica ? <window.PlacaOrdenChica placa={x.r.placa} codigo={x.r.codigo} /> : <PcPlaca p={x.r.placa} />}<span style={{ fontSize: 12.5, fontWeight: 700, color: TOKENS.textMuted, paddingBottom: 3 }}>· Rin {x.i + 1}</span>{x.r.express && <PcChipExpress solo />}<span style={{ flex: 1 }} />
              <PcChip bg={x.dias >= cat.alerta ? TOKENS.dangerBg : '#fff2cc'} fg={x.dias >= cat.alerta ? TOKENS.dangerText : '#7f6000'}>{x.dias} {x.dias === 1 ? 'día' : 'días'} esperando</PcChip></div>
            <div style={{ fontSize: 12.5, color: TOKENS.textMuted, marginTop: 7 }}><b style={{ color: TOKENS.text, fontWeight: 600 }}>{x.r.taller}</b>{x.r.sede ? ' · ' + x.r.sede : ''} · {x.r.aseguradora} · {x.rin.aut.motivo}</div>
            <div style={{ fontSize: 12, color: TOKENS.textSubtle, marginTop: 3 }}>{ult ? `Último: ${ult.tipo} · ${ult.fecha}` : `Desde el ${x.rin.aut.desde} · sin seguimiento todavía`}</div>
          </div>); })}
      {!L.length && <div style={{ padding: 30, textAlign: 'center', color: TOKENS.textMuted, fontSize: 13.5 }}>✓ No hay rines esperando autorización.</div>}
      {L.length > 0 && <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 4 }}>En rojo los rines que llevan {cat.alerta} días hábiles o más esperando la autorización.</div>}
    </>;
  const der = !sel ? <div style={{ height: '100%', minHeight: 300, display: 'grid', placeItems: 'center', color: TOKENS.textMuted, fontSize: 13.5 }}>Aquí aparecen los rines en pausa: solicita la autorización desde la ficha de la placa.</div> :
  <div style={{ maxWidth: 760 }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 12, flexWrap: cel ? 'wrap' : 'nowrap' }}>{window.CabeceraPlaca && <window.CabeceraPlaca ticket={sel.r} grande />}<div style={{ paddingBottom: 8, ...(cel ? { order: 3, flexBasis: '100%', paddingBottom: 0 } : {}) }}><b style={{ fontSize: 15 }}>Rin {sel.i + 1}</b> <span style={{ fontSize: 12.5, color: TOKENS.textSubtle }}>· esperando autorización</span></div><span style={{ flex: 1 }} /><PcBtn onClick={() => setFicha(sel.r.id)}>Abrir ficha</PcBtn></div>
      {/* 19/11/2026: tarjetas blancas sobre gris, como la ficha. */}
      <div style={{ background: TOKENS.surface, border: '1px solid #dfe5ee', borderRadius: 14, padding: 14, marginTop: 14 }}>
      <b style={{ display: 'block', fontSize: 14, fontWeight: 700, marginBottom: 10 }}>Datos</b>
      <div style={{ border: `1px solid ${TOKENS.border}`, borderRadius: 12, overflow: 'hidden' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '150px 1fr' }}><span style={{ background: TOKENS.surfaceLow, padding: '8px 12px', fontSize: 12, color: TOKENS.textMuted, fontWeight: 700 }}>Taller</span><span style={{ padding: '8px 12px', fontWeight: 600, fontSize: 13.5 }}>{sel.r.taller}{sel.r.sede ? ' · ' + sel.r.sede : ''}</span></div>
        {det('Aseguradora', sel.r.aseguradora)}
        {det('Motivo', <>{sel.rin.aut.motivo}{sel.rin.aut.det ? <span style={{ color: TOKENS.textMuted, fontWeight: 500 }}> · {sel.rin.aut.det}</span> : null}</>)}
        {det('Servicio', <><span style={{ fontFamily: pcMono, fontWeight: 800 }}>{servCodigo(sel.rin)}</span> · {pcPesos(sel.rin.precio)} <span style={{ color: TOKENS.textSubtle, fontWeight: 500, fontSize: 12.5 }}>sin IVA</span></>)}
        {det('En pausa desde', `${sel.rin.aut.desde} · ${sel.dias} ${sel.dias === 1 ? 'día hábil' : 'días hábiles'} · ${sel.rin.aut.por || ''}`)}
      </div>
      </div>
      <div style={{ background: TOKENS.surface, border: '1px solid #dfe5ee', borderRadius: 14, padding: 14, marginTop: 12 }}>
      <div style={{ display: 'flex', alignItems: 'center', marginBottom: 12 }}><b style={{ flex: 1, fontSize: 14, fontWeight: 700 }}>Seguimiento</b><PcBtn style={{ padding: '7px 12px', fontSize: 12.5 }} onClick={() => setDlg({ t: 'nuevo' })}>＋ Agregar seguimiento</PcBtn></div>
      <div style={{ position: 'relative', paddingLeft: 22 }}>
        <span style={{ position: 'absolute', left: 7, top: 6, bottom: 6, borderLeft: `2px solid ${TOKENS.border}` }} />
        {[{ ini: true, tipo: 'Esperando autorización', fecha: sel.rin.aut.desde, por: sel.rin.aut.por, det: sel.rin.aut.motivo + ' · plazo en pausa' }, ...ev].map((e, j) =>
        <div key={j} style={{ position: 'relative', paddingBottom: 12, opacity: e.anu ? 0.6 : 1 }}>
            <span style={{ position: 'absolute', left: -20, top: 3, width: 12, height: 12, borderRadius: 99, border: '2px solid #fff', boxSizing: 'border-box', background: e.ini ? PAUSA_COLOR.solid : e.anu ? TOKENS.textSubtle : TOKENS.primary, boxShadow: `0 0 0 1px ${e.ini ? '#d9a514' : e.anu ? TOKENS.textSubtle : TOKENS.primary}` }} />
            <b style={{ fontSize: 13, fontWeight: 600, textDecoration: e.anu ? 'line-through' : 'none' }}>{e.tipo}</b>
            {!e.ini && !e.anu && <button type="button" onClick={() => setDlg({ t: 'anular', j: j - 1 })} style={{ background: 'none', border: 0, color: TOKENS.anulado, fontFamily: 'inherit', fontSize: 11.5, fontWeight: 500, cursor: 'pointer', paddingLeft: 8 }}>Anular</button>}
            <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>{[e.fecha, e.hora && (window.formatHora12 ? window.formatHora12(e.hora) : e.hora), e.por, e.det].filter(Boolean).join(' · ')}</div>
            {e.anu && <div style={{ fontSize: 12, color: TOKENS.anuladoText, marginTop: 2 }}>Anulado · {[e.anu.motivo, e.anu.nota && `"${e.anu.nota}"`, e.anu.por, e.anu.fecha].filter(Boolean).join(' · ')}</div>}
          </div>)}
      </div>
      <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', paddingTop: 12, borderTop: `1px solid ${TOKENS.border}` }}>
        <PcBtn tone="r" onClick={() => setDlg({ t: 'no' })}>No autorizada</PcBtn><PcBtn tone="g" onClick={() => setDlg({ t: 'si' })}>Autorizada</PcBtn>
      </div>
      </div>
    </div>;
  // ── Historial (22/11/2026): Por placa (tarjetas) | Por fecha (tabla compacta). A la derecha el mismo panel:
  //    Datos + Seguimiento con una tarjeta por novedad (pausa, no reparable, no autorizado) en la fila de su rin.
  const tarjetaCss = { background: TOKENS.surface, border: '1px solid #dfe5ee', borderRadius: 14, padding: 14, marginTop: 12 };
  const NA = novedadesLista(regs);
  const grupos = {}; NA.forEach((x) => { (grupos[x.r.id] = grupos[x.r.id] || { r: x.r, ns: [] }).ns.push(x); });
  const H = Object.values(grupos).filter((g) => coincide(g.r)).map((g) => ({ ...g, ult: g.ns.find((x) => x.tipo === 'pausa' && x.p.estado === 'espera') || g.ns[0] }))
    .sort((a, b) => b.ns[0].iso.localeCompare(a.ns[0].iso));
  const hSel = H.find((x) => x.r.id === selH) || H[0];
  const fechaNov = (x) => x.tipo === 'pausa' ? x.p.desde : x.fecha;
  const izqH = <>
    {H.map((x) => { const on = hSel && x.r.id === hSel.r.id; const c = novChip(x.ult); const nP = x.ns.length; return (
      <div key={x.r.id} onClick={() => setSelH(x.r.id)} style={{ background: TOKENS.surface, border: on ? `2px solid ${TOKENS.primary}` : '1px solid #dfe5ee', borderRadius: 12, padding: on ? 11 : 12, marginBottom: 8, cursor: 'pointer', boxShadow: on ? '0 2px 8px rgba(31,61,119,.12)' : 'none' }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: 8 }}>{window.PlacaOrdenChica ? <window.PlacaOrdenChica placa={x.r.placa} codigo={x.r.codigo} /> : <PcPlaca p={x.r.placa} />}<span style={{ flex: 1 }} /><PcChip bg={c[1]} fg={c[2]}>{c[0]}</PcChip></div>
        <div style={{ fontSize: 12.5, color: TOKENS.textMuted, marginTop: 7 }}><b style={{ color: TOKENS.text, fontWeight: 600 }}>{x.r.taller}</b>{x.r.sede ? ' · ' + x.r.sede : ''} · {x.r.aseguradora}</div>
        <div style={{ fontSize: 12, color: TOKENS.textSubtle, marginTop: 3 }}>{nP} {nP === 1 ? 'novedad' : 'novedades'} · {rinesTxt(x.ns.map((y) => y.i))} · última {fechaNov(x.ns[0])}</div>
      </div>); })}
    {!H.length && <div style={{ padding: 30, textAlign: 'center', color: TOKENS.textMuted, fontSize: 13.5 }}>{kq ? `Ninguna placa con novedades coincide con “${q.trim()}”.` : 'Todavía no hay novedades en el historial.'}</div>}
  </>;
  const thF = { textAlign: 'left', fontSize: 10.5, fontWeight: 800, letterSpacing: '.06em', textTransform: 'uppercase', color: TOKENS.textMuted, background: TOKENS.surfaceLow, padding: '9px 10px', borderBottom: `1px solid ${TOKENS.border}`, whiteSpace: 'nowrap', position: 'sticky', top: 0, zIndex: 1 };
  const tdF = { padding: '9px 10px', borderBottom: `1px solid ${TOKENS.border}`, whiteSpace: 'nowrap', fontWeight: 500, fontSize: 12.5 };
  const izqF = <>
    <div style={{ background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 12, overflow: 'hidden' }}>
      <table style={{ borderCollapse: 'separate', borderSpacing: 0, width: '100%' }}>
        <thead><tr>{['Fecha', 'Placa', 'Orden', 'Ítem'].map((h, k) => <th key={h} style={{ ...thF, borderLeft: k ? `1px solid ${TOKENS.border}` : 0 }}>{h}</th>)}</tr></thead>
        <tbody>{NFv.map((x) => { const on = fSel && fSel.k === x.k; const bg = on ? { background: TOKENS.primaryBg } : {}; const bl = { borderLeft: `1px solid ${TOKENS.border}` }; return (
          <tr key={x.k} className="pc-fila" onClick={() => setSelF(x.k)} style={{ cursor: 'pointer' }}>
            <td style={{ ...tdF, ...bg, ...(on ? { boxShadow: `inset 3px 0 0 ${TOKENS.primary}` } : {}) }}>{fechaNov(x)}</td>
            <td style={{ ...tdF, ...bl, ...bg }}><PcPlaca p={x.r.placa} /></td>
            <td style={{ ...tdF, ...bl, ...bg, fontFamily: pcMono }}>{x.r.codigo}</td>
            <td style={{ ...tdF, ...bl, ...bg }}>Rin {x.i + 1}</td>
          </tr>); })}
          {!NFv.length && <tr><td colSpan={4} style={{ padding: 30, textAlign: 'center', color: TOKENS.textMuted, fontSize: 13 }}>{kq ? `Ninguna novedad coincide con “${q.trim()}”.` : 'No hay novedades con esos filtros.'}</td></tr>}
        </tbody>
      </table>
    </div>
    <div style={{ fontSize: 12, color: TOKENS.textSubtle, marginTop: 8 }}>Cada fila es una novedad de un rin; el tipo se ve en su tarjeta.</div>
  </>;
  const panelPlaca = (r, ns, foco) => {
    if (!r) return <div style={{ height: '100%', minHeight: 300, display: 'grid', placeItems: 'center', color: TOKENS.textMuted, fontSize: 13.5 }}>Aquí aparecen las novedades de cada placa.</div>;
    const rines = [...new Set(ns.map((y) => y.i))].sort((a, b) => a - b);
    const ult = ns.find((x) => x.tipo === 'pausa' && x.p.estado === 'espera') || ns[0];
    const c = novChip(foco || ult);
    const nPa = ns.filter((x) => x.tipo === 'pausa').length; const nNr = ns.filter((x) => x.tipo === 'sr' && x.nov === 'nr').length; const nNa = ns.filter((x) => x.tipo === 'sr' && x.nov === 'na').length;
    const resumen = [nPa && `${nPa} ${nPa === 1 ? 'pausa' : 'pausas'}`, nNr && `${nNr} no reparable${nNr > 1 ? 's' : ''}`, nNa && `${nNa} no autorizado${nNa > 1 ? 's' : ''}`].filter(Boolean).join(' · ');
    const nT = diasPausaTicket(r.id);
    return <div>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 12, flexWrap: cel ? 'wrap' : 'nowrap' }}>{window.CabeceraPlaca && <window.CabeceraPlaca ticket={r} grande />}
        <div style={{ paddingBottom: 8, display: 'flex', alignItems: 'center', gap: 8, ...(cel ? { order: 3, flexBasis: '100%', paddingBottom: 0, flexWrap: 'wrap' } : {}) }}><b style={{ fontSize: 16 }}>{foco ? `Rin ${foco.i + 1}` : rinesTxt(rines)}</b>{!foco && <span style={{ fontSize: 12.5, color: TOKENS.textSubtle }}>· {ns.length} {ns.length === 1 ? 'novedad' : 'novedades'}</span>}<PcChip bg={c[1]} fg={c[2]}>{c[0]}</PcChip></div>
        <span style={{ flex: 1 }} /><PcBtn onClick={() => setFicha(r.id)}>Abrir ficha</PcBtn></div>
      <div style={{ ...tarjetaCss, marginTop: 14 }}><b style={{ display: 'block', fontSize: 14, fontWeight: 700, marginBottom: 10 }}>Datos</b>
        <div style={{ border: `1px solid ${TOKENS.border}`, borderRadius: 12, overflow: 'hidden' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '150px 1fr' }}><span style={{ background: TOKENS.surfaceLow, padding: '8px 12px', fontSize: 12, color: TOKENS.textMuted, fontWeight: 700 }}>Taller</span><span style={{ padding: '8px 12px', fontWeight: 600, fontSize: 13.5 }}>{r.taller}{r.sede ? ' · ' + r.sede : ''}</span></div>
          {det('Aseguradora', r.aseguradora)}
          {det('Tiempo en pausa', `${nT} ${nT === 1 ? 'día hábil' : 'días hábiles'} en total`)}
          {det('Novedades', resumen)}
        </div></div>
      <div style={tarjetaCss}><b style={{ display: 'block', fontSize: 14, fontWeight: 700, marginBottom: 4 }}>Seguimiento</b>
        {rines.map((i) => <NovedadesFilaRin key={r.id + i} i={i} ns={ns.filter((y) => y.i === i)} focoK={foco && foco.k} onFoto={setFoto}
          onAccion={(t) => { setAccT({ id: r.id, i }); setDlg({ t }); }} />)}
      </div>
    </div>;
  };
  const derH = hSel ? panelPlaca(hSel.r, hSel.ns, null) : panelPlaca(null);
  const derF = fSel ? panelPlaca(fSel.r, NA.filter((x) => x.r.id === fSel.r.id), fSel) : panelPlaca(null);
  const cabezaSeg = <div>
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <div style={{ display: 'inline-flex', background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 10, padding: 3, gap: 3 }}>
        {[['pend', `Pendientes · ${L.length}`], ['hist', `Historial · ${H.length}`]].map(([k, l]) => { const on = tab === k; return <button key={k} type="button" onClick={() => setTab(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 }} />{tab === 'pend' && <PcChipPausa txt="Plazo en pausa" />}
    </div>
    {tab === 'hist' && <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column', gap: 8 }}>
      <div style={{ display: 'inline-flex', alignSelf: 'flex-start', background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 10, padding: 3, gap: 3 }}>
        {[['placa', 'Por placa'], ['fecha', 'Por fecha']].map(([k, l]) => { const on = vista === k; return <button key={k} type="button" onClick={() => setVista(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>
      {vista === 'fecha' && <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>{[['todas', 'Todas'], ['pausa', 'Pausas'], ['nr', 'No reparable'], ['na', 'No autorizado']].map(([k, l]) => { const on = fil === k; const n = NF.filter((x) => (k === 'todas' || (k === 'pausa' ? x.tipo === 'pausa' : x.nov === k)) && (!mes || x.iso.startsWith(mesIso))).length; return <button key={k} type="button" onClick={() => setFil(k)} style={{ border: `1px solid ${on ? TOKENS.primary : TOKENS.borderInput}`, background: on ? TOKENS.primary : TOKENS.surface, color: on ? '#fff' : TOKENS.text, borderRadius: 99, padding: '5px 10px', fontFamily: 'inherit', fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>{l} <span style={{ opacity: .7, fontWeight: 500 }}>{n}</span></button>; })}
        <button type="button" onClick={() => setMes(!mes)} style={{ border: `1px solid ${mes ? TOKENS.primary : TOKENS.borderInput}`, background: mes ? TOKENS.primary : TOKENS.surface, color: mes ? '#fff' : TOKENS.text, borderRadius: 99, padding: '5px 10px', fontFamily: 'inherit', fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>Este mes</button></div>}
    </div>}
    <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Buscar placa, orden o taller" style={{ marginTop: 10, width: '100%', boxSizing: 'border-box', border: `1px solid ${TOKENS.borderInput}`, borderRadius: 10, padding: '8px 11px', fontFamily: 'inherit', fontSize: 13, background: TOKENS.surfaceLow, color: TOKENS.text, outline: 'none' }} />
  </div>;
  const fichaR = ficha ? regs.find((x) => x.id === ficha) : null;
  return (
    <>
      {pcDosColumnas(440, cabezaSeg, tab === 'hist' ? (enFecha ? izqF : izqH) : izq, tab === 'hist' ? (enFecha ? derF : derH) : der, '#eef1f6', '#eef1f6')}
      {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="Carta" style={{ maxWidth: '86vw', maxHeight: '86vh', borderRadius: 10, background: '#fff' }} /></div>}
      {dlg && dlg.t === 'nuevo' && <PcDialogo tono="p" icono="＋" titulo="Agregar seguimiento" ticket={sel.r} msg={`Rin ${sel.i + 1} · queda en la bitácora con fecha y quién`} confirmar="Guardar"
      campos={[{ k: 'tipo', l: 'Tipo', ops: cat.resp }, { k: 'det', l: 'Detalle', req: true, ph: 'Ej: Se reenvió el correo al ajustador' }]} onCancel={() => { setDlg(null); setAccT(null); }}
      onOk={(v) => { setDlg(null); const now = servAhora(); accion((rin) => { rin.aut.ev = [...(rin.aut.ev || []), { tipo: v.tipo, det: v.det.trim(), fecha: now.fecha, hora: now.hora, por: servYo() }]; }, 'Seguimiento guardado'); }} />}
      {dlg && dlg.t === 'anular' && <PcDialogo tono="m" icono="✕" titulo="Anular seguimiento" msg={`${ev[dlg.j].tipo} · ${ev[dlg.j].fecha} · queda tachado en la bitácora con el motivo; no se borra.`} confirmar="Anular"
      campos={[{ k: 'motivo', l: 'Motivo', ops: cat.anula }, { k: 'nota', l: 'Nota' }]} onCancel={() => { setDlg(null); setAccT(null); }}
      onOk={(v) => { const j = dlg.j; setDlg(null); const now = servAhora(); accion((rin) => { rin.aut.ev[j].anu = { motivo: v.motivo, nota: v.nota.trim(), por: servYo(), fecha: now.fecha }; }, 'Seguimiento anulado', 'm'); }} />}
      {dlg && dlg.t === 'si' && <PcDialogo tono="g" icono="✓" titulo="Autorizada" ticket={sel.r} msg={`Rin ${sel.i + 1} · sale de Novedades y el plazo vuelve a contar. Si la aseguradora aprobó otro valor, cámbialo aquí.`} confirmar="Autorizada"
      campos={[{ k: 'valor', l: 'Valor autorizado sin IVA', peso: true, def: sel.rin.precio }]} onCancel={() => { setDlg(null); setAccT(null); }} onOk={(v) => { setDlg(null); cerrar(true, v.valor); }} />}
      {dlg && dlg.t === 'no' && <PcDialogo tono="r" icono="✕" titulo="No autorizada" ticket={sel.r} msg={`Rin ${sel.i + 1} · no se trabaja y se devuelve sin reparar (valor $0). Los demás rines siguen.`} confirmar="No autorizada"
      campos={[]} onCancel={() => { setDlg(null); setAccT(null); }} onOk={() => { setDlg(null); cerrar(false); }} />}
      {fichaR && cel && <div style={{ position: 'fixed', top: 0, bottom: 0, ...(window.PC_CEL_FIJO || { left: 0, right: 0 }), zIndex: 80, background: TOKENS.bg, overflow: 'auto' }}>
        {fichaR._source === 'entregado' && fichaR._ent && window.ResumenEntregadoScreen ? <window.ResumenEntregadoScreen entrega={fichaR._ent} onBack={() => setFicha(null)} admin /> :
        window.ResumenEntregaScreen ? <window.ResumenEntregaScreen ticket={fichaR._t || fichaR} onBack={() => setFicha(null)} admin /> : null}
      </div>}
      {fichaR && !cel && <PcDetalle r={fichaR} toast={toast} onClose={() => setFicha(null)} onEntregar={() => { setFicha(null); ir('registros'); }} onEditar={() => { setFicha(null); ir('registros'); }} onAnular={() => { setFicha(null); ir('registros'); }} onReactivar={() => setFicha(null)} />}
    </>);
}

// ─── Catálogos › Servicios ───────────────────────────────────────────────
const PC_CATSERV_SUB = [['serv', 'Servicios, precios y plazos', 'RP, RM, soldadura, express y garantía'], ['garantia', 'Motivos de garantía', 'Por qué el taller devuelve un rin'], ['pausa', 'Motivos de pausa', 'Por qué un rin espera autorización'], ['resp', 'Tipos de seguimiento', 'Lo que se anota en la bitácora'], ['anula', 'Motivos de anulación', 'Para anular un seguimiento']];
function PcCatServIzq({ sub, setSub }) {
  const c = loadCatServicios();
  return <>{PC_CATSERV_SUB.map(([k, t, d]) => <div key={k} onClick={() => setSub(k)} style={pcItemCard(sub === k, false, { display: 'block' })}><b style={{ fontSize: 13.5 }}>{t}</b><div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>{k === 'serv' ? `RP ${pcPesos(c.rp)} · RM ${pcPesos(c.rm)} · + S ${pcPesos(c.sold)}` : `${c[k].length} opciones · ${d}`}</div></div>)}</>;
}
function PcCatServDer({ sub, toast }) {
  const [c, setC] = React.useState(loadCatServicios);
  const [nuevo, setNuevo] = React.useState('');
  const [quitar, setQuitar] = React.useState(null);
  const guardar = (n, msg) => { setC(n); saveCatServicios(n); toast(msg); };
  const fila = (k, txt, nodo) => <div style={{ display: 'grid', gridTemplateColumns: '80px 1fr auto', alignItems: 'center', gap: 12, padding: '10px 12px', borderTop: `1px solid ${TOKENS.border}` }}><b style={{ fontFamily: pcMono }}>{k}</b><span style={{ fontSize: 13.5 }}>{txt}</span>{nodo}</div>;
  if (sub === 'serv') return (
    <div style={{ maxWidth: 640 }}>
      <b style={{ fontSize: 16 }}>Servicios y precios</b>
      <div style={{ fontSize: 12.5, color: TOKENS.textMuted, margin: '4px 0 14px' }}>Precios sugeridos sin IVA. Se cargan al escoger el servicio de cada rin y ahí se pueden cambiar. Un solo precio por rin.</div>
      <div style={{ border: `1px solid ${TOKENS.border}`, borderRadius: 12, overflow: 'hidden', background: TOKENS.surface }}>
        <div style={{ marginTop: -1 }}>{fila('RP', SERV_NOMBRE.RP, <PcPesoInput value={c.rp} onChange={(n) => guardar({ ...c, rp: n }, 'Precio de RP guardado')} />)}</div>
        {fila('RM', SERV_NOMBRE.RM, <PcPesoInput value={c.rm} onChange={(n) => guardar({ ...c, rm: n }, 'Precio de RM guardado')} />)}
        {fila('+ S', 'Soldadura · se suma al sugerido', <PcPesoInput value={c.sold} onChange={(n) => guardar({ ...c, sold: n }, 'Valor de soldadura guardado')} />)}
      </div>
      <div style={{ fontSize: 12.5, color: TOKENS.textMuted, marginTop: 8 }}>RPS sugerido: {pcPesos(c.rp + c.sold)} · RMS sugerido: {pcPesos(c.rm + c.sold)}</div>
      {[['slaExpress', <PcChipExpress />, 'Plazo express guardado'], ['slaGarantia', <PcChipGarantia />, 'Plazo de garantía guardado']].map(([k, chip, msg], i) =>
      <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: i ? 10 : 18, paddingTop: i ? 0 : 14, borderTop: i ? 'none' : `1px solid ${TOKENS.border}`, fontSize: 13.5 }}>
          <span style={{ minWidth: 100 }}>{chip}</span><span style={{ flex: 1 }}>Plazo para entregar</span>
          <PcSeg value={c[k] || 2} onChange={(v) => guardar({ ...c, [k]: v }, msg)} options={[[1, '1 día hábil'], [2, '2 días hábiles']]} />
        </div>)}
      <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 6 }}>Las placas normales siguen con el plazo de Ajustes (3 días hábiles).</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 10, fontSize: 13.5 }}>
        Alerta en Novedades desde <input type="number" min="1" value={c.alerta} onChange={(e) => guardar({ ...c, alerta: Math.max(1, Number(e.target.value) || 5) }, 'Alerta guardada')} style={{ ...pcInp, width: 64, textAlign: 'center' }} /> días hábiles esperando
      </div>
    </div>);
  const [, t, d] = PC_CATSERV_SUB.find((x) => x[0] === sub);
  const L = c[sub];
  return (
    <div style={{ maxWidth: 560 }}>
      <b style={{ fontSize: 16 }}>{t}</b>
      <div style={{ fontSize: 12.5, color: TOKENS.textMuted, margin: '4px 0 14px' }}>{d}.{sub === 'pausa' ? ' "Soldadura" solo aparece en los rines marcados con soldadura.' : ''} "Otro" siempre va al final.</div>
      <div style={{ border: `1px solid ${TOKENS.border}`, borderRadius: 12, overflow: 'hidden', background: TOKENS.surface }}>
        {L.map((x, i) => <div key={x} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 12px', borderTop: i ? `1px solid ${TOKENS.border}` : 'none', fontSize: 13.5 }}><span style={{ flex: 1 }}>{x}</span>{x === 'Otro' || (sub === 'pausa' && x === 'Soldadura') ? <span style={{ fontSize: 11.5, color: TOKENS.textSubtle }}>fijo</span> : <PcBtn tone="r" style={{ padding: '4px 9px', fontSize: 11.5 }} onClick={() => setQuitar(x)}>Quitar</PcBtn>}</div>)}
      </div>
      <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
        <input value={nuevo} onChange={(e) => setNuevo(e.target.value)} placeholder="Agregar opción" style={{ ...pcInp, flex: 1 }} />
        <PcBtn tone="p" disabled={!nuevo.trim() || L.some((x) => x.toLowerCase() === nuevo.trim().toLowerCase())} onClick={() => { const n = [...L]; n.splice(Math.max(0, n.length - 1), 0, nuevo.trim()); guardar({ ...c, [sub]: n }, 'Opción agregada'); setNuevo(''); }}>Agregar</PcBtn>
      </div>
      {quitar && window.ConfirmActionModal && <window.ConfirmActionModal tone="danger" icon={I.alert(24, TOKENS.danger)} title="Quitar opción" confirmLabel="Quitar" message={`"${quitar}" deja de aparecer en la lista. Lo que ya se anotó con esa opción se conserva.`}
      onDismiss={() => setQuitar(null)} onConfirm={() => { guardar({ ...c, [sub]: L.filter((x) => x !== quitar) }, 'Opción quitada'); setQuitar(null); }} />}
    </div>);
}

Object.assign(window, { servFijarSinReparar, srDesdeServicios, SinRepararDlg, NovedadesFichaCel, loadSuministrosMap, suministrosDe, guardarSuministros, agregarSuministro, quitarSuministro, sumTxt, sumLista, suministrosDeReg, PcSuministroDlg, PcSuministrosFicha });
Object.assign(window, { garFechaEstimada, deshacerEntrega, deshechasDe, MOTIVOS_DESHACER, loadGarantias, garantiasDe, garantiaAbierta, crearGarantia, entregarGarantia, garEstado, garDiasDesde, GarantiaCampos, GarantiaTicket, GarantiaRecogerMovil, GarantiasPorEntregarMovil, PcChipGarantia, GAR_COLOR, garFaltas, garVacio, reinicioPlazo, loadCatServicios, saveCatServicios, loadServicios, servDe, servGuardar, servCodigo, servValor, servResumen, ticketEnPausa, diasPausaTicket, servPendientes, servRinesDeItems, PcChipPausa, PcChipExpress, PAUSA_COLOR, ServChips, SERV_CHIP, PcPausasFicha, pcVerSeguimiento, pausasDePlaca, SinRepararCampos, srVacio, srFaltas, srLista, servMarcarSinReparar });
