// Login + Dashboard + auxiliary screens

// ─── Usuarios (lista local, DEMO) ──────────────────────────────────────────
// El login ya es real (Supabase, datos.js). Esta lista solo alimenta nombres, mensajeros y la
// pantalla Usuarios hasta pasarla a la tabla perfil (paso 2). Sus PIN ya no sirven para entrar.
const RODANDO_USUARIOS = [
  { usuario: 'cesar', nombre: 'César', rol: 'mensajero', pin: '1234' },
  { usuario: 'sebastian', nombre: 'Sebastián', rol: 'admin', pin: '1234' },
];
const LS_SESION = 'rodando.sesion';
// Parte 2 (27/11/2026): la sesión real la maneja Supabase (datos.js). Aquí queda la copia rápida
// {id, usuario, nombre, rol} que leen las pantallas; las copias viejas del PIN (sin id) no cuentan.
function loadSesion() {
  try {
    const s = JSON.parse(localStorage.getItem(LS_SESION) || sessionStorage.getItem(LS_SESION) || 'null');
    return s && s.rol && s.id ? s : null;
  } catch (e) { return null; }
}
// Usuario con el que se inició sesión (13/11/2026): se guarda en cada recogida, entrega y solicitud.
// Quién es quién (13/11/2026): los mensajeros y los nombres salen de los usuarios del login.
// Usuarios editables desde el panel del PC (13/11/2026). Arrancan con la lista de arriba.
const LS_USUARIOS = 'rodando.usuarios';
function loadUsuarios() {
  try { const l = JSON.parse(localStorage.getItem(LS_USUARIOS) || 'null'); if (Array.isArray(l) && l.length) return l; } catch (e) {}
  return RODANDO_USUARIOS.map((u) => ({ ...u, activo: true }));
}
function saveUsuarios(list) {
  try { localStorage.setItem(LS_USUARIOS, JSON.stringify(list)); } catch (e) {}
  try { window.dispatchEvent(new Event('rodando-usuarios')); } catch (e) {}
}
function mensajerosApp() { return loadUsuarios().filter((u) => u.rol === 'mensajero' && u.activo !== false); }
function nombreDeUsuario(usuario) {
  if (!usuario) return '';
  const u = loadUsuarios().find((x) => x.usuario === usuario);
  if (u) return u.nombre;
  if (usuario === 'juan-diego') { const m = mensajerosApp()[0]; return m ? m.nombre : ''; } // datos viejos
  return '';
}
function usuarioActual() { return window.rdSesionActual || loadSesion() || null; }
function saveSesion(s) { if (!s) { try { localStorage.removeItem(LS_SESION); sessionStorage.removeItem(LS_SESION); } catch (e) {} } } // la copia la guarda datos.js

function LoginScreen({ onLogin, ancho }) {
  const [user, setUser] = React.useState('');
  const [clave, setClave] = React.useState('');
  const [verClave, setVerClave] = React.useState(false);
  const [keep, setKeep] = React.useState(() => { try { return localStorage.getItem('rodando.mantenerSesion') !== '0'; } catch (e) { return true; } });
  const [error, setError] = React.useState('');
  const [entrando, setEntrando] = React.useState(false);

  // Parte 2 (27/11/2026): usuario + contraseña contra Supabase. Los admins entran con su correo.
  const puede = user.trim().length > 0 && clave.length >= 6 && !entrando;
  const entrar = async () => {
    if (!puede) return;
    if (!window.rdEntrar) { setError('No se pudo conectar con el servidor. Recarga la página.'); return; }
    setEntrando(true); setError('');
    const r = await window.rdEntrar(user, clave, keep);
    setEntrando(false);
    if (!r.ok) { setError(r.error); setClave(''); return; }
    onLogin(r.sesion.rol);
  };

  const formulario = (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div>
            <FieldLabel upper>Usuario</FieldLabel>
            <TextInput value={user} onChange={(v) => { setUser(v); setError(''); }} placeholder="tu usuario (o tu correo, si eres admin)" icon={I.user(18, TOKENS.textMuted)} />
          </div>
          <div>
            <FieldLabel upper>Contraseña</FieldLabel>
            <div style={{ position: 'relative' }}>
              <input type={verClave ? 'text' : 'password'} value={clave} autoComplete="current-password" aria-label="Contraseña"
                onChange={(e) => { setClave(e.target.value); setError(''); }}
                onKeyDown={(e) => { if (e.key === 'Enter') entrar(); }}
                placeholder="mínimo 6 caracteres"
                style={{ width: '100%', boxSizing: 'border-box', padding: '14px 74px 14px 14px', fontSize: 16, borderRadius: 12,
                  border: `1.5px solid ${TOKENS.borderInput}`, background: TOKENS.surfaceLow, color: TOKENS.text, outline: 'none', fontFamily: 'inherit' }} />
              <button type="button" onClick={() => setVerClave((v) => !v)}
                style={{ position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)', border: 0, background: 'transparent',
                  color: TOKENS.primary, fontSize: 13, fontWeight: 600, cursor: 'pointer', padding: '6px 8px' }}>{verClave ? 'Ocultar' : 'Ver'}</button>
            </div>
          </div>

          <label style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 14, color: TOKENS.text, cursor: 'pointer', marginTop: 2 }}>
            <input type="checkbox" checked={keep} onChange={(e) => setKeep(e.target.checked)}
              style={{ width: 20, height: 20, accentColor: TOKENS.primary, margin: 0 }} />
            Mantener la sesión en este {ancho ? 'equipo' : 'celular'}
          </label>

          {error && <div style={{ fontSize: 13, fontWeight: 600, color: TOKENS.dangerText, background: TOKENS.dangerBg, borderRadius: 10, padding: '10px 12px' }}>{error}</div>}

          <Button variant="primary" full onClick={entrar} disabled={!puede} style={{ padding: '15px', marginTop: 4, fontSize: 15 }}>
            {entrando ? 'Entrando…' : 'Entrar'}
          </Button>
          <div style={{ textAlign: 'center', fontSize: 12.5, color: TOKENS.textMuted, lineHeight: 1.45 }}>
            ¿Olvidaste la contraseña? Pídele a un administrador que la cambie.
          </div>
        </div>
  );
  // PC (17/11/2026): dos mitades. Marca en rojo a la izquierda (cuadro blanco, logo rojo), formulario a la derecha.
  if (ancho) return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', minHeight: '100vh', fontFamily: 'Inter, -apple-system, system-ui, sans-serif', color: TOKENS.text }}>
      <div style={{ background: RODANDO_ROJO, color: '#fff', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 16, position: 'relative', padding: 24 }}>
        <span style={{ width: 160, height: 160, borderRadius: 36, background: '#fff', display: 'grid', placeItems: 'center', boxShadow: '0 18px 40px rgba(80,10,8,.30)' }}><RodandoIcon height={70} color={RODANDO_ROJO} /></span>
        <div style={{ fontSize: 48, fontWeight: 800, letterSpacing: '-0.02em', marginTop: 6 }}>Rodando</div>
        <div style={{ fontSize: 15, opacity: 0.88, fontWeight: 500 }}>Mensajería · Salvallantas</div>
        <div style={{ position: 'absolute', bottom: 22, fontSize: 12, opacity: 0.75 }}>Salvallantas Cali</div>
      </div>
      <div style={{ background: '#fff', display: 'grid', placeItems: 'center', padding: 24 }}>
        <div style={{ width: 380, maxWidth: '100%' }}>
          <div style={{ fontSize: 26, fontWeight: 800, color: TOKENS.text }}>Iniciar sesión</div>
          <div style={{ fontSize: 13.5, color: TOKENS.textMuted, margin: '4px 0 22px' }}>Entra con tu usuario y contraseña.</div>
          {formulario}
        </div>
      </div>
    </div>);

  return (
    <div style={{ background: TOKENS.bg, display: 'flex', flexDirection: 'column', minHeight: '100vh', padding: '36px 24px 24px' }}>
      <div style={{ marginTop: 48, marginBottom: 30, textAlign: 'center' }}>
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 16 }}>
          <RodandoTile size={104} radius={24} shadow="0 12px 24px rgba(217,48,42,0.25)" />
        </div>
        <div style={{ fontSize: 30, fontWeight: 800, color: RODANDO_ROJO, letterSpacing: '-0.02em' }}>Rodando</div>
        <div style={{ fontSize: 13, color: TOKENS.textMuted, marginTop: 4, fontWeight: 500 }}>Mensajería · Salvallantas</div>
      </div>

      {formulario}

      <div style={{ flex: 1, minHeight: 28 }} />
      <div style={{ textAlign: 'center', fontSize: 11, color: TOKENS.textSubtle, lineHeight: 1.5 }}>
        Rodando · Salvallantas
      </div>
    </div>);

}

// ─── Inicio (tablero) ──────────────────────────────────────────────────────
// Ya no repite las acciones (viven en la barra inferior). Es un tablero
// operativo accionable, con paneles distintos para admin y mensajero.

// Rutas y notificaciones ahora viven en notifications.jsx + screens-rutas.jsx.

function parseDDMMYYYY(s) {
  const m = String(s || '').match(/(\d{1,2})\s*\/\s*(\d{1,2})\s*\/\s*(\d{4})/);
  return m ? new Date(+m[3], +m[2] - 1, +m[1]) : null;
}
function startOfWeekMon(d) {
  const x = new Date(d.getFullYear(), d.getMonth(), d.getDate());
  const wd = (x.getDay() + 6) % 7; // 0 = lunes
  x.setDate(x.getDate() - wd);
  return x;
}

function useInicioData() {
  const read = () => {
    const saved = window.loadPendientesSaved && window.loadPendientesSaved() || [];
    const entregados = window.loadEntregados && window.loadEntregados() || [];
    const demo = window.PENDIENTES_DEMO || [];
    const deliveredIds = new Set(entregados.map((e) => e.ticketId));
    const anuMap = window.loadAnulacionMap ? window.loadAnulacionMap() : new Map();
    const pendientes = [...saved, ...demo]
      .filter((t) => !deliveredIds.has(t.id))
      .filter((t) => { const a = anuMap.get(t.id); return !a || a.estadoActual !== 'anulado'; })
      .map((t) => window.withAnulacion ? window.withAnulacion(t, anuMap) : t);

    const today = new Date();
    const hoyIso = window.isoOf(today);
    const weekStart = startOfWeekMon(today);
    const isoOfStr = (s) => {const d = parseDDMMYYYY(s);return d ? window.isoOf(d) : null;};
    const inWeek = (s) => {const d = parseDDMMYYYY(s);return d && d >= weekStart;};

    // ── Flujo (por fecha del evento) ──────────────────────────────
    const recogidasFechas = [
    ...pendientes.map((t) => t.fecha),
    ...entregados.map((e) => e.fechaRecogido)];

    const recHoy = recogidasFechas.filter((f) => isoOfStr(f) === hoyIso).length;
    const recSemana = recogidasFechas.filter((f) => inWeek(f)).length;
    const entHoy = entregados.filter((e) => isoOfStr(e.fechaEntrega) === hoyIso).length;
    const entSemana = entregados.filter((e) => {
      const d = e.createdAt ? new Date(e.createdAt) : parseDDMMYYYY(e.fechaEntrega);
      return d && d >= weekStart;
    }).length;

    // ── Backlog por severidad (días hábiles) ──────────────────────
    const sev = { aldia: 0, atrasado: 0, critico: 0 };
    pendientes.forEach((t) => {sev[window.ticketSeverity(t, today).level]++;});
    // Estados de PROCESOS (13/11/2026): 0 Vencido · 1 Retrasado · 2 Vence hoy · 3 En plazo
    const est = [0, 0, 0, 0];
    pendientes.forEach((t) => {const e = estadoProcesos(t);est[e.orden]++;});

    return {
      pendientes, entregados,
      flujo: { recHoy, recSemana, entHoy, entSemana },
      sev, est, totalPend: pendientes.length,
      atrasadosCount: sev.atrasado + sev.critico
    };
  };
  const [data, setData] = React.useState(read);
  React.useEffect(() => {
    const refresh = () => setData(read());
    refresh();
    window.addEventListener('storage', refresh);
    window.addEventListener('focus', refresh);
    window.addEventListener('rodando-dias-especiales', refresh);
    window.addEventListener('rodando-anulaciones', refresh);
    return () => {
      window.removeEventListener('storage', refresh);
      window.removeEventListener('focus', refresh);
      window.removeEventListener('rodando-dias-especiales', refresh);
      window.removeEventListener('rodando-anulaciones', refresh);
    };
  }, []);
  return data;
}

// ── Mis notas: checklist personal y libre del mensajero (persistente) ──────
// Por usuario (13/11/2026): cada quien tiene su libreta; el admin puede dejarle notas al mensajero.
const LS_CHECKLIST_KEY = 'rodando.checklist';
function checklistKey(usuario) {
  const u = usuario || ((window.usuarioActual && window.usuarioActual()) || {}).usuario || '';
  return LS_CHECKLIST_KEY + '.' + u;
}
function loadChecklist(usuario) {
  try {
    const k = checklistKey(usuario);
    const raw = localStorage.getItem(k);
    if (raw !== null) return JSON.parse(raw) || [];
    // Migración: la libreta vieja (sin usuario) era del mensajero.
    const old = localStorage.getItem(LS_CHECKLIST_KEY);
    const dueno = usuario || ((window.usuarioActual && window.usuarioActual()) || {}).usuario;
    if (old && dueno && window.mensajerosApp && window.mensajerosApp().some((m) => m.usuario === dueno)) { localStorage.setItem(k, old); localStorage.removeItem(LS_CHECKLIST_KEY); return JSON.parse(old) || []; }
    return [];
  } catch (e) { return []; }
}
function saveChecklist(list, usuario) {
  try { localStorage.setItem(checklistKey(usuario), JSON.stringify(list)); } catch (e) {}
  try { window.dispatchEvent(new Event('rodando-notas')); } catch (e) {}
}

function MisNotas() {
  const [items, setItems] = React.useState(loadChecklist);
  const [text, setText] = React.useState('');
  const [expanded, setExpanded] = React.useState(false);
  const persist = (next) => { setItems(next); saveChecklist(next); };
  const add = () => {
    const t = text.trim();
    if (!t) return;
    persist([...items, { id: 'n-' + Date.now(), text: t, done: false }]);
    setText('');
  };
  const toggle = (id) => persist(items.map(it => it.id === id ? { ...it, done: !it.done } : it));
  const remove = (id) => persist(items.filter(it => it.id !== id));
  const clearDone = () => persist(items.filter(it => !it.done));
  const pend = items.filter(it => !it.done);
  const done = items.filter(it => it.done);
  const ordered = [...pend, ...done]; // pendientes arriba, hechas abajo
  const LIMIT = 5;
  const visible = expanded ? ordered : ordered.slice(0, LIMIT);

  return (
    <div style={{ background: TOKENS.surface, borderRadius: 14, border: `1px solid ${TOKENS.border}`, overflow: 'hidden' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 12px', borderBottom: `1px solid ${TOKENS.border}` }}>
        <input
          value={text}
          onChange={(e) => setText(e.target.value)}
          onKeyDown={(e) => { if (e.key === 'Enter') add(); }}
          placeholder="Anota un recado…"
          style={{ flex: 1, minWidth: 0, border: 'none', outline: 'none', background: 'transparent', fontSize: 14, color: TOKENS.text, fontFamily: 'inherit' }} />
        <button onClick={add} disabled={!text.trim()} aria-label="Agregar" style={{
          flexShrink: 0, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          width: 32, height: 32, borderRadius: 9, border: 'none', cursor: text.trim() ? 'pointer' : 'default',
          background: text.trim() ? TOKENS.primary : TOKENS.surfaceLow,
        }}>{I.plus(18, text.trim() ? '#fff' : TOKENS.textSubtle)}</button>
      </div>

      {items.length === 0 ? (
        <div style={{ padding: '14px 14px', fontSize: 12.5, color: TOKENS.textMuted, lineHeight: 1.5 }}>
          Tus recados personales: lo que la app no necesita pero tú sí. Ej: <i>recoger pintura donde Valenzuela</i>, <i>pasar por repuestos donde el proveedor</i>.
        </div>
      ) : (
        <div>
          {visible.map((it, i) => (
            <div key={it.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderTop: i === 0 ? 'none' : `1px solid ${TOKENS.border}` }}>
              <button onClick={() => toggle(it.id)} aria-label="Marcar" style={{
                flexShrink: 0, width: 22, height: 22, borderRadius: 6, cursor: 'pointer', padding: 0,
                border: `2px solid ${it.done ? TOKENS.success : TOKENS.borderInput}`,
                background: it.done ? TOKENS.success : 'transparent',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>{it.done && I.check(13, '#fff')}</button>
              <span style={{ flex: 1, minWidth: 0, fontSize: 13.5, color: it.done ? TOKENS.textSubtle : TOKENS.text, fontWeight: it.done ? 500 : 600, textDecoration: it.done ? 'line-through' : 'none', lineHeight: 1.35, wordBreak: 'break-word' }}>{it.text}
                {it.deNombre && <span style={{ display: 'block', fontSize: 11, fontWeight: 600, color: TOKENS.textMuted, textDecoration: 'none', marginTop: 2 }}>De {it.deNombre}</span>}</span>
              <button onClick={() => remove(it.id)} aria-label="Borrar" style={{ flexShrink: 0, background: 'transparent', border: 'none', cursor: 'pointer', padding: 4, color: TOKENS.textSubtle, display: 'flex' }}>{I.trash(15, TOKENS.textSubtle)}</button>
            </div>
          ))}
          {ordered.length > LIMIT && (
            <button onClick={() => setExpanded(e => !e)} style={{
              width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
              padding: '9px 12px', borderTop: `1px solid ${TOKENS.border}`, background: 'transparent',
              border: 'none', borderTopWidth: 1, borderTopStyle: 'solid', borderTopColor: TOKENS.border,
              cursor: 'pointer', fontFamily: 'inherit', fontSize: 12, fontWeight: 700, color: TOKENS.primary,
            }}>
              {expanded ? 'Ver menos' : `Ver todas (${ordered.length})`}
              <span style={{ display: 'flex', transform: expanded ? 'rotate(180deg)' : 'none', transition: 'transform .15s' }}>{I.chev(15, TOKENS.primary)}</span>
            </button>
          )}
          {done.length > 0 && (
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 12px', borderTop: `1px solid ${TOKENS.border}`, background: TOKENS.surfaceLow }}>
              <span style={{ fontSize: 11, color: TOKENS.textMuted, fontWeight: 600 }}>{done.length} {done.length === 1 ? 'hecha' : 'hechas'}</span>
              <button onClick={clearDone} style={{ background: 'transparent', border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 11.5, fontWeight: 700, color: TOKENS.primary }}>Limpiar hechas</button>
            </div>
          )}
        </div>
      )}
    </div>);

}

// ── Encargos (23/11/2026): encargos + notas de la oficina en una sola cosa ────────────────
// Tarea de la oficina para el mensajero: Entregar, Recoger o Hacer. Con taller del catálogo
// (placa opcional) u otro lugar escrito. No usa número de orden ni aparece en Registros.
// Las notas personales del mensajero siguen en su libreta (Mis notas).
const LS_ENCARGOS_KEY = 'rodando.encargos.v1';
const ENC_TIPO = { entregar: ['↗', 'Entregar'], recoger: ['↙', 'Recoger'], hacer: ['✓', 'Hacer'] };
// 27/11/2026: la acción del encargo lleva su color (Entregar = turquesa de garantía, Recoger = verde, Hacer = ámbar); "Encargo" queda en gris.
const ENC_COLOR = { entregar: ['#0e7490', '#e6f7fa', '#b3e3ec'], recoger: ['#1d7a4a', '#e4f4ea', '#bfe2cc'], hacer: ['#8a5a00', '#fdf0d5', '#f0d9a8'] };
function EncEtiquetas({ tipo, grande, sinEncargo, fondo }) {
  const T = ENC_TIPO[tipo] || ['✓', 'Encargo']; const c = ENC_COLOR[tipo] || [TOKENS.textMuted, TOKENS.surfaceLow, TOKENS.border];
  const base = { display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: grande ? 11 : 10, fontWeight: 800, letterSpacing: '0.05em', borderRadius: 6, padding: grande ? '3px 8px' : '2px 6px', whiteSpace: 'nowrap', border: '1px solid' };
  return <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, verticalAlign: 'middle' }}>
    {!sinEncargo && <span style={{ ...base, color: TOKENS.textMuted, background: fondo || TOKENS.surfaceLow, borderColor: TOKENS.border }}>ENCARGO</span>}
    <span style={{ ...base, color: c[0], background: c[1], borderColor: c[2] }}>{T[0]} {T[1].toUpperCase()}</span>
  </span>;
}
function loadEncargos() { try { return (JSON.parse(localStorage.getItem(LS_ENCARGOS_KEY)) || []).map(window.catCanonObj || ((x) => x)); } catch (e) { return []; } }
function saveEncargos(list) {
  try { (window.safeSetItem || ((k, v) => { localStorage.setItem(k, v); return true; }))(LS_ENCARGOS_KEY, JSON.stringify(list)); } catch (e) {}
  try { window.dispatchEvent(new Event('rodando-encargos')); window.dispatchEvent(new Event('rodando-notas')); } catch (e) {}
}
const encHoyIso = () => { const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; };
const encDeIso = (iso) => { const m = String(iso || '').match(/^(\d{4})-(\d{2})-(\d{2})/); return m ? `${m[3]}/${m[2]}/${m[1]}` : ''; };
function encParaTxt(e) {
  if (!e.fechaIso) return 'Sin fecha';
  const h = encHoyIso(); const m = new Date(); m.setDate(m.getDate() + 1);
  const man = `${m.getFullYear()}-${String(m.getMonth() + 1).padStart(2, '0')}-${String(m.getDate()).padStart(2, '0')}`;
  return e.fechaIso === h ? 'Hoy' : e.fechaIso === man ? 'Mañana' : e.fechaIso < h ? `${encDeIso(e.fechaIso).slice(0, 5)} · atrasado` : encDeIso(e.fechaIso).slice(0, 5);
}
const encDonde = (e) => e.cliente ? `Cliente particular · ${e.cliente.nombre}` : e.lugarTipo === 'otro' ? (e.direccion || '') : [e.taller, e.sede].filter(Boolean).join(' · ');
function crearEncargo(x) {
  const yo = (window.usuarioActual && window.usuarioActual()) || {};
  const e = { id: 'enc-' + Date.now() + '-' + Math.random().toString(36).slice(2, 6), estado: 'pend', creadoAt: Date.now(), creadoPor: yo.usuario || '', creadoPorNombre: yo.nombre || '', ...x };
  saveEncargos([e, ...loadEncargos()]);
  if (window.addNotif && e.para) window.addNotif({ id: 'n-enc-' + Date.now(), tipo: 'nota', para: 'mensajero', paraUsuario: e.para, estado: 'pendiente', titulo: `Tarea · ${ENC_TIPO[e.tipo][1]}`, mensaje: `${e.que}${encDonde(e) ? ' · ' + encDonde(e) : ''}`, actor: yo.usuario, createdAt: Date.now(), resolucion: null });
  return e;
}
function actualizarEncargo(id, fn) { saveEncargos(loadEncargos().map((e) => e.id === id ? { ...e, ...fn(e) } : e)); }
function marcarEncargoHecho(id, { foto, comprobante, nota } = {}) {
  const yo = (window.usuarioActual && window.usuarioActual()) || {}; const now = new Date();
  actualizarEncargo(id, () => ({ estado: 'hecho', hecho: { fecha: fechaDDMMYYYY(now), hora: `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`, por: yo.usuario || '', porNombre: yo.nombre || '', foto: foto || null, comprobante: String(comprobante || '').trim(), nota: String(nota || '').trim() } }));
}
function reabrirEncargo(id) { actualizarEncargo(id, () => ({ estado: 'pend', hecho: null })); }
function quitarEncargo(id) { saveEncargos(loadEncargos().filter((e) => e.id !== id)); }
const encargosDe = (usuario) => loadEncargos().filter((e) => !e.para || e.para === usuario);
const encargosPendientesDe = (usuario) => encargosDe(usuario).filter((e) => e.estado !== 'hecho');
// Migración (una vez): encargos viejos (placas en Por entregar con "encargo") y notas que la oficina
// le dejó al mensajero pasan al formato nuevo.
function migrarEncargos() {
  try {
    if (localStorage.getItem('rodando.encargos.migrado')) return;
    const nuevos = [];
    const defM = (window.mensajerosApp && (window.mensajerosApp()[0] || {}).usuario) || 'cesar';
    const pend = JSON.parse(localStorage.getItem('rodando.pendientes') || '[]');
    const quedan = pend.filter((t) => {
      if (!t.encargo) return true;
      const que = (t.items || []).map((it) => `${it.cantidad || 1} ${it.tipo === 'valvula' ? 'válvula' : it.tipo}${(Number(it.cantidad) || 1) > 1 ? 's' : ''}${it.referencia ? ' ' + it.referencia : ''}`).join(' + ') || 'Encargo';
      nuevos.push({ id: 'enc-m-' + t.id, tipo: 'entregar', que, lugarTipo: 'taller', taller: t.taller || '', sede: t.sede || '', placa: t.placa || '', aseguradora: t.aseguradora || '', fechaIso: t.fechaLimiteIso || '', urgente: !!t.express, nota: t.nota || '', para: defM, estado: 'pend', creadoAt: Date.now(), creadoPor: t.digitadoPor || '', creadoPorNombre: t.digitadoPorNombre || '' });
      return false;
    });
    if (quedan.length !== pend.length) localStorage.setItem('rodando.pendientes', JSON.stringify(quedan));
    (window.mensajerosApp ? window.mensajerosApp() : []).forEach((m) => {
      const l = loadChecklist(m.usuario); const de = l.filter((n) => n.de);
      if (!de.length) return;
      de.forEach((n) => nuevos.push({ id: 'enc-n-' + n.id, tipo: 'hacer', que: n.text, lugarTipo: 'otro', direccion: '', para: m.usuario, estado: n.done ? 'hecho' : 'pend', hecho: n.done ? { fecha: '', porNombre: m.nombre } : null, creadoAt: n.createdAt || Date.now(), creadoPor: n.de, creadoPorNombre: n.deNombre || '' }));
      try { localStorage.setItem(checklistKey(m.usuario), JSON.stringify(l.filter((n) => !n.de))); } catch (e) {}
    });
    if (nuevos.length) localStorage.setItem(LS_ENCARGOS_KEY, JSON.stringify([...nuevos, ...loadEncargos()]));
    localStorage.setItem('rodando.encargos.migrado', '1');
  } catch (e) {}
}
try { migrarEncargos(); } catch (e) {}
function useEncargos() {
  const [, bump] = React.useReducer((x) => x + 1, 0);
  React.useEffect(() => { window.addEventListener('rodando-encargos', bump); window.addEventListener('storage', bump); return () => { window.removeEventListener('rodando-encargos', bump); window.removeEventListener('storage', bump); }; }, []);
  return loadEncargos();
}
// Celular: encargos de la oficina para el mensajero. Tocar uno abre la hoja para marcarlo hecho.
function EncargosOficina({ soloPendientes }) {
  useEncargos();
  const [, bump] = React.useReducer((x) => x + 1, 0);
  React.useEffect(() => { window.addEventListener('rodando-paradas', bump); return () => window.removeEventListener('rodando-paradas', bump); }, []);
  const yo = (window.usuarioActual && window.usuarioActual()) || {};
  const hoy = fechaDDMMYYYY(new Date());
  const paradas = window.loadParadas ? window.loadParadas() : [];
  const enRutaEnc = new Set(paradas.filter((p) => p.tipo === 'encargo' && (p.estado === 'pendiente' || p.estado === 'en_curso')).map((p) => p.encargoId));
  const L = encargosDe(yo.usuario).filter((e) => e.estado !== 'hecho' || (!soloPendientes && e.hecho && e.hecho.fecha === hoy))
    .sort((a, b) => (a.estado === 'hecho') - (b.estado === 'hecho') || (b.urgente ? 1 : 0) - (a.urgente ? 1 : 0) || String(a.fechaIso || '9').localeCompare(String(b.fechaIso || '9')));
  // 23/11/2026: también las recogidas de placas que le asignó la oficina (se cierran en Rutas).
  const sols = paradas.filter((p) => p.tipo === 'recoger' && p.creadaPor === 'admin' && p.asignadoA === yo.usuario && ['solicitud', 'pendiente', 'en_curso'].includes(p.estado) && p.fecha === hoy);
  const [abierto, setAbierto] = React.useState(null);
  const [verSol, setVerSol] = React.useState(null);
  if (!L.length && !sols.length) return null;
  const chipRuta = <span style={{ marginLeft: 6, fontSize: 10.5, fontWeight: 700, borderRadius: 99, padding: '1px 7px', background: TOKENS.primaryBg, color: TOKENS.primary, border: `1px solid ${TOKENS.primaryBorder}` }}>En tu ruta</span>;
  const caja = (h) => <span style={{ flexShrink: 0, width: 22, height: 22, borderRadius: 6, border: `2px solid ${h ? TOKENS.success : TOKENS.borderInput}`, background: h ? TOKENS.success : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', marginTop: 1 }}>{h && I.check(13, '#fff')}</span>;
  const fila = { display: 'flex', gap: 10, alignItems: 'flex-start', width: '100%', textAlign: 'left', background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 12, padding: '10px 11px', marginTop: 6, fontFamily: 'inherit', cursor: 'pointer' };
  return <div>
    {sols.map((p) => <button key={p.id} type="button" onClick={() => setVerSol(p)} style={fila}>
      {caja(false)}
      <span style={{ flex: 1, minWidth: 0 }}>
        <span style={{ fontSize: 13.5, color: TOKENS.text, lineHeight: 1.35 }}><b style={{ fontWeight: 700 }}>↙ Recoger placas</b> {(p.placas || []).map((pl) => <span key={pl} style={{ fontFamily: "'JetBrains Mono', monospace", fontWeight: 700, fontSize: 11.5, background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 5, padding: '1px 5px', marginLeft: 4 }}>{pl}</span>)}{p.estado !== 'solicitud' && chipRuta}</span>
        <span style={{ display: 'block', fontSize: 11.5, color: TOKENS.textMuted, marginTop: 3 }}>{[p.taller + (p.sede ? ' · ' + p.sede : ''), p.referencia, p.prioridad === 'alta' && '↑ Prioridad'].filter(Boolean).join(' · ')}</span>
      </span>
    </button>)}
    {L.map((e) => { const h = e.estado === 'hecho'; return (
      <button key={e.id} type="button" onClick={() => setAbierto(e)} style={{ ...fila, border: `1px solid ${e.urgente && !h ? TOKENS.primaryBorder : TOKENS.border}` }}>
        {caja(h)}
        <span style={{ flex: 1, minWidth: 0 }}>
          <span style={{ fontSize: 13.5, color: h ? TOKENS.textSubtle : TOKENS.text, textDecoration: h ? 'line-through' : 'none', lineHeight: 1.35 }}><b style={{ fontWeight: 700 }}>{ENC_TIPO[e.tipo][0]} {ENC_TIPO[e.tipo][1]}</b> {e.que}{e.placa && <span style={{ fontFamily: "'JetBrains Mono', monospace", fontWeight: 700, fontSize: 11.5, background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 5, padding: '1px 5px', marginLeft: 6 }}>{e.placa}</span>}{!h && enRutaEnc.has(e.id) && chipRuta}</span>
          <span style={{ display: 'block', fontSize: 11.5, color: TOKENS.textMuted, marginTop: 3 }}>{[encDonde(e), h ? `hecho${e.hecho && e.hecho.hora ? ' ' + (window.formatHora12 ? window.formatHora12(e.hecho.hora) : e.hecho.hora) : ''}` : encParaTxt(e).toLowerCase(), e.urgente && !h && '↑ Prioridad'].filter(Boolean).join(' · ')}</span>
        </span>
      </button>); })}
    {abierto && ReactDOM.createPortal(<EncargoHechoSheet e={abierto} onClose={() => setAbierto(null)} />, document.body)}
    {verSol && ReactDOM.createPortal(<div onClick={() => setVerSol(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(11,28,48,0.45)', zIndex: 1100, display: 'flex', alignItems: 'flex-end', justifyContent: 'center' }}>
      <div onClick={(x) => x.stopPropagation()} style={{ background: TOKENS.bg, borderRadius: '18px 18px 0 0', width: '100%', maxWidth: 440, padding: '12px 16px 22px' }}>
        <div style={{ width: 36, height: 4, borderRadius: 2, background: TOKENS.border, margin: '0 auto 12px' }} />
        <div style={{ fontSize: 12, fontWeight: 800, letterSpacing: '.06em', color: TOKENS.textMuted }}>TAREA · RECOGER PLACAS</div>
        <div style={{ fontSize: 18, fontWeight: 800, marginTop: 4 }}>{(verSol.placas || []).join(', ')}</div>
        <div style={{ background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 12, padding: '8px 12px', marginTop: 12, fontSize: 13, lineHeight: 1.7 }}>
          <div><b>{verSol.taller}{verSol.sede ? ' · ' + verSol.sede : ''}</b></div>
          {verSol.direccion && <div style={{ color: TOKENS.textMuted }}>{verSol.direccion}</div>}
          {verSol.cliente && <div style={{ color: TOKENS.textMuted }}>{verSol.cliente.telefono}</div>}
          <div>{verSol.referencia}</div>
          {verSol.notas && <div style={{ color: TOKENS.textMuted }}>{verSol.notas}</div>}
        </div>
        <div style={{ fontSize: 12.5, color: TOKENS.textMuted, marginTop: 10, lineHeight: 1.5 }}>{verSol.estado === 'solicitud' ? 'Está en Rutas › Por planear › Por recoger. Agrégala a tu ruta y, al llegar, regístrala con Recoger.' : 'Está en tu ruta. Se cierra al registrar la recogida.'}</div>
      </div>
    </div>, document.body)}
  </div>;
}
function EncargoHechoSheet({ e, onClose }) {
  const [foto, setFoto] = React.useState(null);
  const [comp, setComp] = React.useState('');
  const [nota, setNota] = React.useState('');
  const ref = React.useRef(null);
  const h = e.estado === 'hecho';
  const leer = (f) => { if (!f) return; const rd = new FileReader(); rd.onload = async () => { let src = rd.result; try { if (window.downscaleDataURL) src = await window.downscaleDataURL(src, 1200, 0.75); } catch (x) {} setFoto(src); }; rd.readAsDataURL(f); };
  const fila = (k, v) => v ? <div style={{ display: 'flex', gap: 10, fontSize: 13, padding: '6px 0', borderTop: `1px solid ${TOKENS.border}` }}><span style={{ width: 86, flexShrink: 0, color: TOKENS.textMuted, fontWeight: 600 }}>{k}</span><span style={{ fontWeight: 600 }}>{v}</span></div> : null;
  const inp = { width: '100%', boxSizing: 'border-box', border: `1px solid ${TOKENS.borderInput}`, borderRadius: 10, padding: '10px 12px', fontFamily: 'inherit', fontSize: 14, marginTop: 6 };
  return <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(11,28,48,0.45)', zIndex: 1100, display: 'flex', alignItems: 'flex-end', justifyContent: 'center' }}>
    <div onClick={(x) => x.stopPropagation()} style={{ background: TOKENS.bg, borderRadius: '18px 18px 0 0', width: '100%', maxWidth: 440, padding: '12px 16px 22px', maxHeight: '86vh', overflow: 'auto' }}>
      <div style={{ width: 36, height: 4, borderRadius: 2, background: TOKENS.border, margin: '0 auto 12px' }} />
      <div><EncEtiquetas tipo={e.tipo} grande /></div>
      <div style={{ fontSize: 18, fontWeight: 800, marginTop: 4, color: TOKENS.text }}>{e.que}</div>
      <div style={{ background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 12, padding: '4px 12px', marginTop: 12 }}>
        {fila('Dónde', encDonde(e))}{fila('Placa', e.placa)}{fila('Para', `${encParaTxt(e)}${e.urgente ? ' · ↑ Prioridad' : ''}`)}{e.cliente && fila('Cliente', `${e.cliente.nombre} · ${e.cliente.telefono}`)}{fila('Nota', e.nota)}{fila('De', e.creadoPorNombre)}
        {h && fila('Hecho', [e.hecho.fecha, e.hecho.porNombre, e.hecho.comprobante].filter(Boolean).join(' · '))}
      </div>
      {h ? <>
        {e.hecho.foto && <img src={e.hecho.foto} alt="Soporte" style={{ width: '100%', borderRadius: 12, marginTop: 12 }} />}
        <button type="button" onClick={() => { reabrirEncargo(e.id); onClose(); }} style={{ width: '100%', marginTop: 14, padding: 13, borderRadius: 12, border: `1px solid ${TOKENS.borderInput}`, background: TOKENS.surface, color: TOKENS.primary, fontFamily: 'inherit', fontSize: 14.5, fontWeight: 700 }}>Desmarcar</button>
      </> : <>
        {e.tipo === 'entregar' && e.placa && <div style={{ marginTop: 12 }}><div style={{ fontSize: 12, fontWeight: 700, color: TOKENS.textMuted }}>Factura o remisión <span style={{ fontWeight: 500 }}>(opcional)</span></div><input value={comp} onChange={(x) => setComp(x.target.value.toUpperCase())} placeholder="Ej. SE 16555" style={inp} /></div>}
        <div style={{ marginTop: 12 }}><div style={{ fontSize: 12, fontWeight: 700, color: TOKENS.textMuted }}>Foto <span style={{ fontWeight: 500 }}>(opcional)</span></div>
          {foto ? <img src={foto} alt="Soporte" onClick={() => setFoto(null)} style={{ width: '100%', borderRadius: 12, marginTop: 6 }} /> :
          <button type="button" onClick={() => ref.current && ref.current.click()} style={{ width: '100%', marginTop: 6, padding: 14, borderRadius: 12, border: `1.5px dashed ${TOKENS.primary}`, background: TOKENS.primaryBg, color: TOKENS.primary, fontFamily: 'inherit', fontSize: 14, fontWeight: 700 }}>📷 Tomar foto</button>}
          <input ref={ref} type="file" accept="image/*" capture="environment" style={{ display: 'none' }} onChange={(x) => leer(x.target.files && x.target.files[0])} /></div>
        <input value={nota} onChange={(x) => setNota(x.target.value)} placeholder="Nota (opcional)" style={{ ...inp, marginTop: 12 }} />
        <button type="button" onClick={() => { marcarEncargoHecho(e.id, { foto, comprobante: comp, nota }); onClose(); }} style={{ width: '100%', marginTop: 14, padding: 14, borderRadius: 12, border: 0, background: TOKENS.primary, color: '#fff', fontFamily: 'inherit', fontSize: 15, fontWeight: 800 }}>Marcar hecho</button>
      </>}
    </div>
  </div>;
}
// Panel de la libreta (celular): encargos de la oficina arriba y Mis notas abajo.
function EncargosYNotas() {
  const L = useEncargos();
  const yo = (window.usuarioActual && window.usuarioActual()) || {};
  const hay = encargosDe(yo.usuario).some((e) => e.estado !== 'hecho' || (e.hecho && e.hecho.fecha === fechaDDMMYYYY(new Date()))) || (window.loadParadas ? window.loadParadas() : []).some((p) => p.tipo === 'recoger' && p.creadaPor === 'admin' && p.asignadoA === yo.usuario && ['solicitud', 'pendiente', 'en_curso'].includes(p.estado) && p.fecha === fechaDDMMYYYY(new Date()));
  const lbl = { fontSize: 10.5, fontWeight: 800, letterSpacing: '.06em', color: TOKENS.textMuted, margin: '4px 2px 2px' };
  return <div>
    {hay && <><div style={lbl}>DE LA OFICINA</div><EncargosOficina /><div style={{ ...lbl, marginTop: 16, marginBottom: 6 }}>MIS NOTAS</div></>}
    <MisNotas />
  </div>;
}

// ── Tiempo en sitio por taller (histórico persistente, vista admin) ────────
const LS_TIEMPOS_KEY = 'rodando.tiempos';
function loadTiempos() {
  try { return JSON.parse(localStorage.getItem(LS_TIEMPOS_KEY) || '[]'); } catch (e) { return []; }
}
function seedTiemposIfEmpty() {
  if (loadTiempos().length > 0) return;
  const M = (m) => m * 60000, DAY = 86400000, now = Date.now();
  const e = (taller, sede, m, d) => ({ taller, sede, ms: M(m), ts: now - d * DAY });
  const seed = [
    e('Mazko', 'Norte', 32, 3), e('Mazko', 'Norte', 28, 2), e('Mazko', 'Norte', 35, 1),
    e('Coches de la Sabana', '8va', 24, 3), e('Coches de la Sabana', '8va', 19, 1),
    e('Renovautos', 'Sur', 18, 2), e('Renovautos', 'Sur', 21, 1),
    e('Almotores', 'Volkswagen', 15, 2), e('Almotores', 'Volkswagen', 13, 1),
    e('Almotores', 'Kia', 12, 3), e('Almotores', 'Kia', 9, 2), e('Almotores', 'Kia', 14, 1), e('Almotores', 'Kia', 11, 0),
    e('Autosuperior', 'Norte', 8, 2), e('Autosuperior', 'Norte', 7, 1),
  ];
  try { localStorage.setItem(LS_TIEMPOS_KEY, JSON.stringify(seed)); } catch (er) {}
}

function TiempoTalleresCard() {
  React.useEffect(() => { seedTiemposIfEmpty(); }, []);
  const tiempos = loadTiempos();
  const map = new Map();
  tiempos.forEach(t => {
    const key = `${t.taller}|${t.sede}`;
    if (!map.has(key)) map.set(key, { taller: t.taller, sede: t.sede, total: 0, n: 0 });
    const g = map.get(key); g.total += t.ms; g.n += 1;
  });
  const rows = [...map.values()].map(g => ({ ...g, avg: g.total / g.n })).sort((a, b) => b.avg - a.avg).slice(0, 5);
  const max = rows.length ? rows[0].avg : 1;

  if (rows.length === 0) {
    return (
      <div style={{ padding: '18px 14px', background: TOKENS.surface, borderRadius: 14, border: `1px solid ${TOKENS.border}`, fontSize: 12.5, color: TOKENS.textMuted, lineHeight: 1.5 }}>
        Aún no hay datos de tiempos. Se registran automáticamente al finalizar paradas en la ruta.
      </div>);
  }

  return (
    <div style={{ background: TOKENS.surface, borderRadius: 14, border: `1px solid ${TOKENS.border}`, overflow: 'hidden' }}>
      {rows.map((r, i) => {
        const mins = Math.max(1, Math.round(r.avg / 60000));
        const pct = Math.round(r.avg / max * 100);
        const color = TOKENS.primary; // regla de color (13/11/2026): sin naranja
        return (
          <div key={r.taller + r.sede} style={{ padding: '12px 14px', borderTop: i === 0 ? 'none' : `1px solid ${TOKENS.border}` }}>
            <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 10, marginBottom: 7 }}>
              <span style={{ fontSize: 13.5, fontWeight: 700, color: TOKENS.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', minWidth: 0 }}>
                {r.taller}<span style={{ color: TOKENS.textMuted, fontWeight: 500 }}> · {r.sede}</span>
              </span>
              <span style={{ flexShrink: 0, fontSize: 14, fontWeight: 800, color, fontFamily: 'monospace' }}>{mins} min</span>
            </div>
            <div style={{ height: 8, background: TOKENS.surfaceLow, borderRadius: 999, overflow: 'hidden' }}>
              <div style={{ width: pct + '%', height: '100%', background: color, borderRadius: 999, transition: 'width .4s ease' }} />
            </div>
            <div style={{ fontSize: 11, color: TOKENS.textSubtle, marginTop: 5, fontWeight: 600 }}>
              {r.n} {r.n === 1 ? 'visita' : 'visitas'}{r.n < 3 ? ' · pocas muestras' : ''}
            </div>
          </div>);
      })}
    </div>);

}

// ─── Inicio del mensajero: "Tablero del día" (elegido 10/11/2026) ──────────
// Arriba lo que tiene que hacer hoy (Por Recoger · Por Entregar · Por Enviar),
// después la lista de lo que está por entregar con el estado en los MISMOS
// términos de PROCESOS, la semana y sus notas plegadas. La alerta de
// atrasados (SLA) es del administrador: no depende del mensajero.

// Estado de un pendiente con el vocabulario de PROCESOS (meta 3 días hábiles).
function estadoProcesos(t) {
  const sev = window.ticketSeverity ? window.ticketSeverity(t, new Date()) : { dias: 0 };
  // Express (16/11/2026): plazo propio (2 días hábiles por defecto). Los días en pausa (rines
  // esperando autorización) no cuentan; mientras haya un rin en pausa, el estado es "En pausa".
  let S = t.express ? (window.loadCatServicios ? window.loadCatServicios().slaExpress : 2) : (window.loadSlaConfig ? window.loadSlaConfig().slaHabiles : 3);
  // Encargo con fecha (21/11/2026): el plazo son los días hábiles hasta la fecha que puso el admin.
  if (t.fechaLimiteIso && window.businessDaysElapsed && window.effectiveStart) {
    try { const [y, m, dd] = t.fechaLimiteIso.split('-').map(Number); S = Math.max(0, window.businessDaysElapsed(window.effectiveStart(t.fecha, t.horaRecogida), new Date(y, m - 1, dd, 12))); } catch (e) {}
  }
  // Mientras está en pausa, los días quedan congelados; cuando se resuelve, el plazo empieza de cero.
  const re = window.reinicioPlazo && t.id ? window.reinicioPlazo(t.id) : null;
  const d = re && window.effectiveStart ? window.businessDaysElapsed(window.effectiveStart(re.fecha, re.hora), new Date()) :
    Math.max(0, (sev.dias || 0) - (window.diasPausaTicket && t.id ? window.diasPausaTicket(t.id) : 0));
  if (window.ticketEnPausa && t.id && window.ticketEnPausa(t.id)) return { label: 'En pausa', bg: (window.PAUSA_COLOR || {}).bg || '#fdf0d5', fg: (window.PAUSA_COLOR || {}).fg || '#8a5a00', orden: 3, dias: d, pausa: true };
  if (d < S) return { label: 'En plazo', bg: TOKENS.successBg, fg: TOKENS.successText, orden: 3, dias: d };
  if (d === S) return { label: 'Vence hoy', bg: '#fff2cc', fg: '#7f6000', orden: 2, dias: d };
  if (d === S + 1) return { label: 'Retrasado', bg: TOKENS.warningBg, fg: TOKENS.warningText, orden: 1, dias: d };
  return { label: 'Vencido', bg: TOKENS.dangerBg, fg: TOKENS.dangerText, orden: 0, dias: d };
}
function resumenItems(t) {
  const items = t.items || [];
  const rines = items.filter((i) => i && i.tipo === 'rin').reduce((n, i) => n + (Number(i.cantidad) || 1), 0);
  const acc = window.inferAccion ? window.inferAccion({ items }) : null;
  // CANT cuenta solo rines; si el ticket es solo de llantas, se dice así.
  const llantas = items.filter((i) => i && i.tipo === 'llanta').reduce((n, i) => n + (Number(i.cantidad) || 1), 0);
  const r = rines > 0 ? (rines === 1 ? '1 rin' : `${rines} rines`) :
  llantas > 0 ? (llantas === 1 ? '1 llanta' : `${llantas} llantas`) : 'sin ítems';
  if (rines === 0) return r;
  return acc ? `${r} · ${acc.short.toLowerCase()}` : r;
}
// Hora/fecha corta de cuándo se registró una parada: "9:40", "Ayer", "8 nov".
function cuandoCorto(ts) {
  if (!ts) return '—';
  const d = new Date(ts), hoy = new Date();
  const ini = (x) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime();
  const dias = Math.round((ini(hoy) - ini(d)) / 86400000);
  if (dias <= 0) return d.toLocaleTimeString('es-CO', { hour: 'numeric', minute: '2-digit', hour12: false });
  if (dias === 1) return 'Ayer';
  return d.toLocaleDateString('es-CO', { day: 'numeric', month: 'short' }).replace('.', '');
}
const ESTADO_PARADA = {
  en_curso: { label: 'En curso', bg: TOKENS.cautionBg, fg: TOKENS.cautionText, border: TOKENS.caution, blink: true, orden: 0 },
  // Regla de color (13/11/2026): el azul claro es solo "en curso". Pendiente y Solicitud en gris; los distingue el borde.
  pendiente: { label: 'Pendiente', bg: TOKENS.surface, fg: TOKENS.text, border: TOKENS.borderInput, orden: 1 },
  solicitud: { label: 'Solicitud', bg: TOKENS.surfaceLow, fg: TOKENS.textMuted, border: TOKENS.borderInput, dashed: true, orden: 2 }
};
// "hoy 8:10" · "desde ayer" · "desde 8 nov"
function cuandoDesc(ts) {
  const c = cuandoCorto(ts);
  if (c === '—' || c === 'Ayer') return c === 'Ayer' ? 'desde ayer' : '';
  return /:/.test(c) ? 'hoy ' + c : 'desde ' + c;
}
// Placa (o placas) en el mismo lugar de siempre. Varias → la primera y "+N".
function PlacaSlot({ placas, onDark, grande }) {
  const list = (placas || []).filter(Boolean);
  if (!list.length) {
    return <span style={{ fontSize: grande ? 13 : 11, fontWeight: 700, color: onDark ? '#c9d6ee' : TOKENS.textSubtle, border: `1px dashed ${onDark ? 'rgba(255,255,255,.4)' : TOKENS.borderInput}`, borderRadius: 6, padding: '3px 7px', flexShrink: 0, whiteSpace: 'nowrap' }}>Sin placa</span>;
  }
  return (
    <span style={{ ...slotStyle, whiteSpace: 'nowrap', ...(grande ? { fontSize: 16, padding: '5px 9px', borderRadius: 7, background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, color: TOKENS.text } : null) }}>
      {list[0]}{list.length > 1 && <span style={{ fontFamily: 'inherit', fontSize: grande ? 11 : 10.5, color: TOKENS.textMuted, marginLeft: 4 }}>+{list.length - 1}</span>}
    </span>);
}
function ChipEstado({ e }) {
  return (
    <span style={{ ...chipStyle(e.bg, e.fg), border: e.border ? `1px ${e.dashed ? 'dashed' : 'solid'} ${e.border}` : 'none', display: 'inline-flex', alignItems: 'center', gap: 5 }}>
      {e.blink && <span style={{ width: 7, height: 7, borderRadius: 999, background: e.fg, animation: 'rdBlink 1.4s infinite' }} />}
      {e.label}
    </span>);
}
// Placas de un destino de la ruta: recogidas → p.placas; entregas → placa del ticket.
function placasDestino(d, pendientes) {
  const out = [];
  d.tareas.forEach((t) => {
    if (t.tipo === 'recoger') (t.placas || []).forEach((x) => out.push(x));
    else (t.consecutivos || []).forEach((c) => {
      const tk = pendientes.find((x) => String(x.codigo) === String(c));
      if (tk && tk.placa) out.push(tk.placa);
    });
  });
  return [...new Set(out)];
}
// Ruta de hoy agrupada por destino (igual que la pestaña Mi ruta de Rutas).
function rutaDeHoy() {
  const hoy = typeof fechaDDMMYYYY === 'function' ? fechaDDMMYYYY() : null;
  const paradas = (window.loadParadas ? window.loadParadas() : []).filter((p) =>
  (!hoy || p.fecha === hoy) && ['pendiente', 'en_curso', 'completada'].includes(p.estado));
  if (!paradas.length || typeof groupByDestino !== 'function') return null;
  const destinos = groupByDestino(paradas).sort((a, b) => a.orden - b.orden);
  const hechas = destinos.filter((d) => d.estado === 'completada').length;
  const actual = destinos.find((d) => d.estado === 'en_curso') || destinos.find((d) => d.estado !== 'completada') || null;
  const enMarcha = hechas > 0 || destinos.some((d) => d.estado === 'en_curso');
  return { total: destinos.length, hechas, actual, enMarcha, terminada: hechas === destinos.length };
}

// Tarjeta "Mi ruta" (12/11/2026): muestra lo siguiente que hay que hacer y solo
// deja INICIAR o FINALIZAR esa parada (+ abrir Waze/Maps). El registro se hace en
// Recoger / Entregar; la organización de la ruta, en Rutas.
function MiRutaCard({ ruta, pendientes, onNav }) {
  const [finalizando, setFinalizando] = React.useState(null);
  const box = { marginTop: 12, background: TOKENS.surface, border: `1px solid ${TOKENS.primaryBorder}`, borderRadius: 16, padding: 14 };
  const top = { display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 12, fontWeight: 800, color: TOKENS.primary, letterSpacing: '0.06em', textTransform: 'uppercase' };
  const right = { letterSpacing: 0, textTransform: 'none', color: TOKENS.textMuted, fontWeight: 700 };
  const btnStyle = (bg, fg) => ({
    flex: 1, whiteSpace: 'nowrap', border: 'none', borderRadius: 11, padding: 11,
    fontFamily: 'inherit', fontSize: 14, fontWeight: 800, cursor: 'pointer', background: bg, color: fg
  });

  if (!ruta) {
    return (
      <div style={box}>
        <div style={top}>Mi ruta</div>
        <div style={{ fontSize: 13, color: TOKENS.textMuted, marginTop: 6 }}>No tienes ruta para hoy.</div>
        <div style={{ display: 'flex', marginTop: 12 }}>
          <button type="button" onClick={() => onNav('rutas')} style={btnStyle(TOKENS.primaryBg, TOKENS.primary)}>Armar ruta</button>
        </div>
      </div>);
  }
  const pct = Math.round(ruta.hechas / ruta.total * 100);
  const bar =
  <div style={{ height: 6, borderRadius: 9, background: TOKENS.surfaceLow, margin: '9px 0 12px', overflow: 'hidden' }}>
      <div style={{ width: pct + '%', height: '100%', background: ruta.terminada ? TOKENS.success : TOKENS.primary, borderRadius: 9 }} />
    </div>;
  if (ruta.terminada) {
    return (
      <div style={box}>
        <div style={top}>Mi ruta <span style={right}>{ruta.total} de {ruta.total} hechas</span></div>
        {bar}
        <div style={{ fontSize: 14, fontWeight: 800, color: TOKENS.successText }}>✓ Ruta terminada</div>
      </div>);
  }
  const d = ruta.actual;
  const enCurso = d.estado === 'en_curso';
  const tipos = [...new Set(d.tareas.map((t) => t.tipo))];
  const tipoTxt = tipos.map((t) => t === 'recoger' ? 'Recoger' : t === 'entregar' ? 'Entregar' : 'Otro').join(' · ');
  // 20/11/2026: la orden va en su recuadro junto a la placa, no en el texto.
  const det = d.tareas.map((t) => t.tipo === 'entregar' ? ((t.consecutivos || []).length > 1 ? `${t.consecutivos.length} órdenes` : '') : (t.referencia || '').replace(/^Recogida( solicitada)?\s*—\s*/i, '')).filter(Boolean).join(' · ');
  const iniciarTxt = tipos.length === 1 && tipos[0] === 'recoger' ? 'Iniciar recogida' : tipos.length === 1 && tipos[0] === 'entregar' ? 'Iniciar entrega' : 'Iniciar parada';

  const iniciar = () => {
    const now = Date.now();
    d.tareas.forEach((t) => { if (t.estado === 'pendiente') window.updateParada(t.id, { estado: 'en_curso', iniciadaEn: now }); });
  };
  const confirmarFinalizar = () => {
    const now = Date.now();
    d.tareas.forEach((t) => window.updateParada(t.id, { estado: 'completada', completadaEn: now }));
    if (d.iniciadaEn) {
      try {
        const log = JSON.parse(localStorage.getItem('rodando.tiempos') || '[]');
        log.push({ taller: d.taller, sede: d.sede, ms: now - d.iniciadaEn, fecha: fechaDDMMYYYY(), ts: now });
        localStorage.setItem('rodando.tiempos', JSON.stringify(log));
      } catch (e) {}
    }
    setFinalizando(null);
  };

  return (
    <div style={box}>
      <div style={top}>Mi ruta <span style={right}>{ruta.hechas} de {ruta.total} hechas</span></div>
      {bar}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', minHeight: 22 }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 10.5, fontWeight: 800, borderRadius: 6, padding: '2px 7px', background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, color: TOKENS.textMuted, textTransform: 'uppercase', letterSpacing: '0.04em' }}>{d.tareas && d.tareas.some((t) => t.tipo === 'entregar') && !d.tareas.some((t) => t.tipo === 'recoger') ? I.truck(12, TOKENS.textMuted) : d.tareas && d.tareas.every((t) => t.tipo === 'recoger') ? I.recoger(12, TOKENS.textMuted) : null}{tipoTxt}</span>
        {enCurso && d.iniciadaEn &&
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontFamily: "'JetBrains Mono', monospace", fontSize: 12, fontWeight: 600, color: TOKENS.cautionText, background: TOKENS.cautionBg, border: `1px solid ${TOKENS.caution}`, borderRadius: 999, padding: '2px 9px' }}>
            <span style={{ width: 7, height: 7, borderRadius: 999, background: TOKENS.cautionText, animation: 'rdBlink 1.4s infinite' }} />
            {typeof LiveTimer === 'function' ? <LiveTimer since={d.iniciadaEn} /> : null}
          </span>}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10, marginTop: 4 }}>
        <div style={{ minWidth: 0 }}>
          <span style={{ display: 'block', fontSize: 10.5, fontWeight: 700, color: TOKENS.textMuted }}>{enCurso ? 'Parada actual' : 'Siguiente parada'}</span>
          <div style={{ fontSize: 16, fontWeight: 800, color: TOKENS.text, marginTop: 4, lineHeight: 1.2 }}>{d.taller}</div>
          {d.sede && <div style={{ fontSize: 12.5, fontWeight: 700, color: TOKENS.textMuted, marginTop: 1 }}>{d.sede}</div>}
        </div>
        {(() => { const pls = placasDestino(d, pendientes); const tEnt = d.tareas.find((t) => t.tipo === 'entregar'); const cod = tEnt && (tEnt.consecutivos || [])[0];
          return pls.length && window.PlacaOrdenChica ? <span style={{ display: 'inline-flex', alignItems: 'flex-end', gap: 4, flexShrink: 0 }}><window.PlacaOrdenChica placa={pls[0]} codigo={tipos.length === 1 && tipos[0] === 'entregar' ? cod : null} />{pls.length > 1 && <span style={{ fontSize: 11, fontWeight: 700, color: TOKENS.textMuted, paddingBottom: 4 }}>+{pls.length - 1}</span>}</span> : <PlacaSlot placas={pls} grande />; })()}
      </div>
      <div style={{ ...ellip, fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>{[d.direccion, det].filter(Boolean).join(' · ')}</div>
      <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
        {enCurso ?
        <button type="button" onClick={() => setFinalizando(d)} style={btnStyle(TOKENS.primary, '#fff')}>Finalizar</button> :
        <button type="button" onClick={iniciar} style={btnStyle(TOKENS.primary, '#fff')}>{iniciarTxt}</button>}
        <button type="button" aria-label="Cómo llegar (Waze / Maps)" title="Cómo llegar"
          onClick={() => { if (typeof openInMaps === 'function') openInMaps(d); }}
          style={{ width: 46, flex: 'none', border: `1px solid ${TOKENS.primaryBorder}`, background: TOKENS.surface, borderRadius: 11, cursor: 'pointer', display: 'grid', placeItems: 'center' }}>
          {I.map ? I.map(20, TOKENS.primary) : I.route(20, TOKENS.primary)}
        </button>
      </div>
      {finalizando && typeof FinalizarDestinoModal === 'function' &&
      ReactDOM.createPortal(<FinalizarDestinoModal destino={finalizando} onDismiss={() => setFinalizando(null)} onConfirm={confirmarFinalizar} />, document.body)}
    </div>);
}

function recogidasActivas() {
  const paradas = window.loadParadas ? window.loadParadas() : [];
  return paradas
    .filter((p) => p.tipo === 'recoger' && ESTADO_PARADA[p.estado])
    .sort((a, b) => ESTADO_PARADA[a.estado].orden - ESTADO_PARADA[b.estado].orden || (a.createdAt || 0) - (b.createdAt || 0));
}

// Pestañas pegadas a la tabla (variante B, elegida 10/11/2026).
function DiaTabs({ value, onChange, counts }) {
  const tabs = [['recoger', 'Por Recoger'], ['entregar', 'Por Entregar'], ['enviar', 'Por Enviar']];
  return (
    <div role="tablist" style={{
      display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', background: TOKENS.surfaceLow,
      border: `1px solid ${TOKENS.border}`, borderBottom: 'none', borderRadius: '14px 14px 0 0', overflow: 'hidden'
    }}>
      {tabs.map(([k, label]) => {
        const on = value === k;
        const alerta = k === 'enviar' && counts[k] > 0;
        const numColor = on ? TOKENS.primary : alerta ? TOKENS.warningText : TOKENS.text;
        return (
          <button key={k} role="tab" aria-selected={on} type="button" onClick={() => onChange(k)} style={{
            fontFamily: 'inherit', cursor: 'pointer', border: 'none', padding: '10px 4px 9px',
            background: on ? TOKENS.surface : 'transparent', borderBottom: `3px solid ${on ? TOKENS.primary : 'transparent'}`,
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
            color: on ? TOKENS.primary : TOKENS.textMuted
          }}>
            <span style={{ fontSize: 24, fontWeight: 800, lineHeight: 1.1, color: numColor }}>{counts[k]}</span>
            <span style={{ fontSize: 11.5, fontWeight: 700, whiteSpace: 'nowrap' }}>{label}</span>
          </button>);
      })}
    </div>);
}

const filaStyle = (i) => ({
  width: '100%', display: 'flex', alignItems: 'center', gap: 10, padding: '12px 12px', textAlign: 'left',
  background: 'transparent', border: 'none', borderTop: i === 0 ? 'none' : `1px solid ${TOKENS.border}`,
  cursor: 'pointer', fontFamily: 'inherit', color: TOKENS.text
});
const slotStyle = { fontFamily: "'JetBrains Mono', monospace", fontWeight: 600, fontSize: 12.5, background: TOKENS.surfaceLow, borderRadius: 6, padding: '3px 7px', flexShrink: 0 };
const chipStyle = (bg, fg) => ({ fontSize: 10.5, fontWeight: 600, borderRadius: 999, padding: '4px 9px', background: bg, color: fg, whiteSpace: 'nowrap', flexShrink: 0 });
const ellip = { display: 'block', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' };

function FilaDia({ i, slot, titulo, sub, chip, onClick }) {
  return (
    <button type="button" onClick={onClick} style={filaStyle(i)}>
      {typeof slot === 'string' ? <span style={slotStyle}>{slot}</span> : slot}
      <span style={{ flex: 1, minWidth: 0 }}>
        <span style={{ ...ellip, fontSize: 13.5, fontWeight: 700 }}>{titulo}</span>
        {sub && <span style={{ ...ellip, fontSize: 12, color: TOKENS.textMuted }}>{sub}</span>}
      </span>
      {chip}
    </button>);
}

function InicioMensajero({ role, onNav, onLogout }) {
  const d = useInicioData();
  const perfilNombre = usePerfilName();
  const [verResumen, setVerResumen] = React.useState(false);
  const [filtro, setFiltro] = React.useState('recoger');
  const [, bump] = React.useReducer((x) => x + 1, 0);
  React.useEffect(() => {
    window.addEventListener('rodando-paradas', bump);
    return () => window.removeEventListener('rodando-paradas', bump);
  }, []);
  const notifs = window.useNotifs ? window.useNotifs(role) : [];
  const pendNotifs = notifs.filter((n) => n.estado === 'pendiente');
  const recogidas = recogidasActivas();
  const porEnviar = window.rodandoPorEnviar ? window.rodandoPorEnviar() : 0;
  const counts = { recoger: recogidas.length, entregar: d.totalPend, enviar: porEnviar };
  const fecha = new Date().toLocaleDateString('es-CO', { weekday: 'long', day: 'numeric', month: 'short' });
  const TOP = 5;

  let filas, vacio, verTodos;
  if (filtro === 'recoger') {
    filas = recogidas.slice(0, TOP).map((p, i) => {
      const e = ESTADO_PARADA[p.estado];
      const ref = (p.referencia || '').replace(/^Recogida( solicitada)?\s*—\s*/i, '');
      return <FilaDia key={p.id} i={i} slot={<PlacaSlot placas={p.placas} />} titulo={`${p.taller}${p.sede ? ' · ' + p.sede : ''}`}
        sub={[ref, cuandoDesc(p.createdAt)].filter(Boolean).join(' · ')} chip={<ChipEstado e={e} />} onClick={() => onNav('rutas')} />;
    });
    vacio = 'No tienes recogidas pendientes.';
    verTodos = () => onNav('rutas');
  } else if (filtro === 'entregar') {
    filas = d.pendientes
      .map((t) => ({ t, e: estadoProcesos(t) }))
      .sort((a, b) => a.e.orden - b.e.orden || b.e.dias - a.e.dias)
      .slice(0, TOP)
      .map(({ t, e }, i) =>
      <FilaDia key={t.id} i={i} slot={t.placa || '—'} titulo={`${t.taller}${t.sede ? ' · ' + t.sede : ''}`}
        sub={resumenItems(t)} chip={<span style={chipStyle(e.bg, e.fg)}>{e.label}</span>} onClick={() => onNav('entregar')} />);
    vacio = 'No tienes nada por entregar.';
    verTodos = () => onNav('entregar');
  } else {
    // La cola de envío sin señal llega en la semana 3; mientras tanto está vacía.
    filas = [];
    vacio = null;
    verTodos = null;
  }

  return (
    <div style={{ background: TOKENS.bg, display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
      {window.NotifToasts && <NotifToasts role={role} onOpen={() => onNav('notificaciones')} />}
      <AppHeader avatar hideRuta notif={pendNotifs.length} onBell={() => onNav('notificaciones')} onAvatar={() => setVerResumen(true)} />
      <div style={{ flex: 1, padding: '16px 16px 28px', overflow: 'auto' }}>
        <div style={{ fontSize: 13, color: TOKENS.textMuted, fontWeight: 500 }}>Hola, {perfilNombre} · {fecha}</div>
        <div style={{ fontSize: 24, fontWeight: 800, color: TOKENS.text, marginTop: 2, letterSpacing: '-0.01em' }}>Mi día</div>

        {/* Esta semana: franja de una línea */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 6, whiteSpace: 'nowrap', marginTop: 12,
          background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 12, padding: '9px 12px',
          fontSize: 12.5, color: TOKENS.textMuted
        }}>
          <span>Semana</span><span style={{ flex: 1 }} />
          <span><b style={{ color: TOKENS.text, fontSize: 14 }}>{d.flujo.recSemana}</b> recogidos</span>
          <span>·</span>
          <span><b style={{ color: TOKENS.text, fontSize: 14 }}>{d.flujo.entSemana}</b> entregados</span>
        </div>

        <MiRutaCard ruta={rutaDeHoy()} pendientes={d.pendientes} onNav={onNav} />
        {window.encargosPendientesDe && (encargosPendientesDe((usuarioActual() || {}).usuario).length > 0 || (window.loadParadas ? window.loadParadas() : []).some((p) => p.tipo === 'recoger' && p.creadaPor === 'admin' && p.asignadoA === (usuarioActual() || {}).usuario && p.estado === 'solicitud' && p.fecha === fechaDDMMYYYY(new Date()))) && <>
          <SectionLabel>Tareas</SectionLabel>
          <EncargosOficina soloPendientes />
        </>}

        <SectionLabel>Hoy</SectionLabel>
        <DiaTabs value={filtro} onChange={setFiltro} counts={counts} />
        <div style={{ ...tableCardStyle, borderRadius: '0 0 14px 14px' }}>
          {filas.length > 0 ? filas :
          filtro === 'enviar' ?
          <div style={{ padding: '20px 14px', textAlign: 'center', fontSize: 13, color: TOKENS.textMuted }}>
            <div style={{ fontSize: 14, fontWeight: 800, color: TOKENS.successText, marginBottom: 3 }}>✓ Todo enviado</div>
            No hay nada pendiente por subir.
          </div> :
          <div style={{ padding: '18px 14px', textAlign: 'center', fontSize: 13, color: TOKENS.textMuted }}>{vacio}</div>}
          {verTodos && counts[filtro] > 0 &&
          <button type="button" onClick={verTodos} style={{
            width: '100%', padding: '11px', border: 'none', borderTop: `1px solid ${TOKENS.border}`, background: 'transparent',
            fontFamily: 'inherit', fontSize: 12.5, fontWeight: 700, color: TOKENS.primary, cursor: 'pointer'
          }}>Ver todos ({counts[filtro]}) →</button>}
        </div>


        <div style={{ marginTop: 24, textAlign: 'center' }}>
          <button onClick={onLogout} style={{
            background: 'transparent', border: 'none', cursor: 'pointer', fontFamily: 'inherit',
            fontSize: 12.5, fontWeight: 600, color: TOKENS.textMuted, display: 'inline-flex', alignItems: 'center', gap: 6, padding: '8px 12px'
          }}>{I.logout(16, TOKENS.textMuted)}<span>Cerrar sesión</span></button>
        </div>
      </div>
      <BottomNav current="dashboard" onNav={onNav} />
      {verResumen &&
      <TrabajadorResumenCard role={role} onClose={() => setVerResumen(false)}
        onVerPerfil={() => { setVerResumen(false); onNav('ajustes'); }} />}
    </div>);
}

function DashboardScreen({ role, onNav, onLogout }) {
  const isAdmin = role === 'admin';
  if (!isAdmin) return <InicioMensajero role={role} onNav={onNav} onLogout={onLogout} />;
  const d = useInicioData();
  const perfilNombre = usePerfilName();
  const [verResumen, setVerResumen] = React.useState(false);
  const notifs = window.useNotifs ? window.useNotifs(role) : [];
  const pendNotifs = notifs.filter((n) => n.estado === 'pendiente').
  sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));

  return (
    <div style={{ background: TOKENS.bg, display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
      {window.NotifToasts && <NotifToasts role={role} onOpen={() => onNav('notificaciones')} />}
      <AppHeader
        avatar
        notif={pendNotifs.length}
        onBell={() => onNav('notificaciones')}
        onAvatar={() => onNav('ajustes')} />
      <div style={{ flex: 1, padding: '18px 16px 28px', overflow: 'auto' }}>
        <div style={{ fontSize: 13, color: TOKENS.textMuted, fontWeight: 500 }}>Hola, {perfilNombre} · {fechaCorta()}</div>
        <div style={{ fontSize: 22, fontWeight: 700, color: TOKENS.text, marginTop: 2, letterSpacing: '-0.01em' }}>Operación de hoy</div>

        {/* ── Alerta (13/11/2026): placas vencidas y retrasadas → Consultar filtrado ── */}
        {(d.est[0] + d.est[1]) > 0 &&
        <div style={{ marginTop: 16 }}>
            <AlertBanner
            tone="danger"
            icon={I.alert(20, TOKENS.danger)}
            title={d.est[0] > 0 ? `${d.est[0]} ${d.est[0] === 1 ? 'placa vencida' : 'placas vencidas'}` : `${d.est[1]} ${d.est[1] === 1 ? 'placa retrasada' : 'placas retrasadas'}`}
            sub={(d.est[0] > 0 && d.est[1] > 0 ? `y ${d.est[1]} ${d.est[1] === 1 ? 'retrasada' : 'retrasadas'} · ` : '') + `pasaron la meta de ${window.loadSlaConfig ? window.loadSlaConfig().slaHabiles : 3} días hábiles`}
            cta="Atender"
            onClick={() => onNav('consultar', { filter: 'pendiente', severity: [0, 1] })} />
          </div>
        }

        <PorDecidirAdmin onNav={onNav} />
        <MensajerosHoyAdmin onNav={onNav} />

        {/* ── Estado de pendientes (13/11/2026): los cuatro estados de PROCESOS ── */}
        <SectionLabel>
          Estado de pendientes
          <span style={{ textTransform: 'none', letterSpacing: 0, fontWeight: 600, color: TOKENS.textSubtle }}>
            {d.totalPend} {d.totalPend === 1 ? 'placa' : 'placas'}
          </span>
        </SectionLabel>
        <div style={tableCardStyle}>
          <div style={{ padding: '15px 14px 7px' }}>
            <div style={{ display: 'flex', height: 10, borderRadius: 999, overflow: 'hidden', background: TOKENS.surfaceLow, gap: 2 }}>
              {d.totalPend > 0 && ESTADOS_ADMIN.map((m, o) => d.est[o] > 0 && <div key={o} title={`${m.label}: ${d.est[o]}`} style={{ flex: d.est[o], background: m.color, minWidth: 5 }} />)}
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', padding: '2px 14px 9px' }}>
            <span style={{ flex: 1 }} />
            <span style={sevColHead}>Cant.</span>
            <span style={sevColHead}>%</span>
          </div>
          {ESTADOS_ADMIN.map((m, o) => {
            const count = d.est[o];
            const pct = d.totalPend ? Math.round(count / d.totalPend * 100) : 0;
            return <SevRow key={o} meta={m} count={count} pct={pct} last={o === 3} onClick={() => onNav('consultar', { filter: 'pendiente', severity: [o] })} />;
          })}
        </div>

        {/* ── Tabla 1 · Flujo de trabajo (Hoy / Semana) ─────────── */}
        <SectionLabel>Flujo de trabajo</SectionLabel>
        <div style={tableCardStyle}>
          <div style={flowHeadStyle}>
            <span style={{ flex: 1 }} />
            <span style={flowColHead}>Hoy</span>
            <span style={flowColHead}>Semana</span>
          </div>
          <FlowRow
            icon={I.recoger} color={TOKENS.textMuted} label="Recogidos"
            hoy={d.flujo.recHoy} semana={d.flujo.recSemana}
            onClick={() => onNav('consultar', { filter: 'todos', date: 'hoy' })}
            onHoy={() => onNav('consultar', { filter: 'todos', date: 'hoy' })} />
          <FlowRow
            icon={I.truck} color={TOKENS.textMuted} label="Entregados"
            hoy={d.flujo.entHoy} semana={d.flujo.entSemana} last
            onClick={() => onNav('consultar', { filter: 'entregado', date: 'hoy' })}
            onHoy={() => onNav('consultar', { filter: 'entregado', date: 'hoy' })} />
        </div>

        {/* ── Tiempo en sitio por taller (solo admin) ───────────── */}
        {isAdmin && (
          <>
            <SectionLabel>
              Tiempo en sitio por taller
              <span style={{ textTransform: 'none', letterSpacing: 0, fontWeight: 600, color: TOKENS.textSubtle }}>
                Promedio
              </span>
            </SectionLabel>
            <TiempoTalleresCard />
          </>
        )}

        {/* Cerrar sesión — discreto */}
        <div style={{ marginTop: 26, textAlign: 'center' }}>
          <button onClick={onLogout} style={{
            background: 'transparent', border: 'none', cursor: 'pointer', fontFamily: 'inherit',
            fontSize: 12.5, fontWeight: 600, color: TOKENS.textMuted,
            display: 'inline-flex', alignItems: 'center', gap: 6, padding: '8px 12px'
          }}>
            {I.logout(16, TOKENS.textMuted)}
            <span>Cerrar sesión</span>
          </button>
        </div>
      </div>
      <BottomNav current="dashboard" onNav={onNav} />
      {verResumen && (
        <TrabajadorResumenCard
          role={role}
          onClose={() => setVerResumen(false)}
          onVerPerfil={() => { setVerResumen(false); onNav('ajustes'); }} />
      )}
    </div>);

}

// ── Card resumen del trabajador (al tocar el avatar en Inicio) ────────────
// Vista rápida que NO saca al usuario del tablero: identidad + contacto +
// actividad del día. Para editar datos o ajustes, lleva a "Mi perfil".
function TrabajadorResumenCard({ role, onClose, onVerPerfil }) {
  const isAdmin = role === 'admin';
  const perfil = window.loadPerfil ? window.loadPerfil() : { nombre: 'Juan Diego', telefono: '', placa: '', identificacion: '' };

  const hoy = fechaDDMMYYYY();
  const paradas = (window.loadParadas ? window.loadParadas() : []).filter((p) => p.fecha === hoy);
  const completadas = paradas.filter((p) => p.estado === 'completada');
  const destinos = new Set(completadas.map((p) => `${p.taller}|${p.sede}`));
  const pendientes = paradas.filter((p) => p.estado === 'pendiente' || p.estado === 'en_curso');
  let ms = 0;
  try {
    ms = JSON.parse(localStorage.getItem('rodando.tiempos') || '[]').
    filter((t) => t.fecha === hoy).reduce((s, t) => s + (t.ms || 0), 0);
  } catch (e) {}
  const fmtDur = (x) => {
    const m = Math.round((x || 0) / 60000);
    if (m < 1) return '0m';
    if (m < 60) return `${m}m`;
    const h = Math.floor(m / 60), mm = m % 60;
    return mm ? `${h}h ${mm}m` : `${h}h`;
  };

  const stats = isAdmin ?
  [{ n: destinos.size, label: 'Paradas hoy' }, { n: pendientes.length, label: 'Pendientes' }] :
  [
  { n: destinos.size, label: 'Paradas' },
  { n: fmtDur(ms), label: 'En sitio' },
  { n: pendientes.length, label: 'Pendientes' }];


  const photo = window.loadAvatar ? window.loadAvatar() : '';
  const resumenActividad = isAdmin ?
  `${destinos.size} ${destinos.size === 1 ? 'parada' : 'paradas'} · ${pendientes.length} pend.` :
  `${destinos.size} ${destinos.size === 1 ? 'parada' : 'paradas'} · ${fmtDur(ms)} en sitio`;

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 1200, background: 'rgba(11,28,48,0.62)',
      display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
      padding: '34px 16px 24px', backdropFilter: 'blur(3px)', overflowY: 'auto'
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: '100%', maxWidth: 300, position: 'relative', margin: 'auto' }}>

        {/* Cerrar */}
        <button onClick={onClose} aria-label="Cerrar" style={{
          position: 'absolute', top: -12, right: -8, zIndex: 3, width: 34, height: 34, borderRadius: 999,
          background: '#fff', border: `1px solid ${TOKENS.border}`, cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 4px 12px rgba(11,28,48,0.25)'
        }}>{I.x(16, TOKENS.text)}</button>

        {/* Clip / lanyard */}
        <div style={{ display: 'flex', justifyContent: 'center', position: 'relative', zIndex: 2 }}>
          <div style={{
            width: 46, height: 30, background: TOKENS.primaryDark, borderRadius: '8px 8px 3px 3px',
            display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 3px 6px rgba(11,28,48,0.3)'
          }}>
            <div style={{ width: 20, height: 7, borderRadius: 999, background: TOKENS.bg, opacity: 0.85 }} />
          </div>
        </div>

        {/* Carnet */}
        <div style={{
          marginTop: -4, background: TOKENS.surface, borderRadius: 16, overflow: 'hidden',
          boxShadow: '0 26px 64px rgba(11,28,48,0.4)', border: `1px solid ${TOKENS.border}`
        }}>
          {/* Wordmark de marca */}
          <div style={{ padding: '16px 20px 12px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <RodandoIcon height={30} />
              <span style={{ fontSize: 34, fontWeight: 800, letterSpacing: '-0.03em', color: RODANDO_ROJO, lineHeight: 1 }}>Rodando</span>
              <span style={{ fontSize: 13, fontWeight: 700, color: RODANDO_ROJO, opacity: 0.6, alignSelf: 'flex-start' }}>®</span>
            </div>
            <div style={{ fontSize: 9.5, fontWeight: 700, color: TOKENS.textSubtle, letterSpacing: '0.16em', textTransform: 'uppercase', marginTop: 5 }}>
              Mensajería · Salvallantas
            </div>
          </div>

          {/* Foto tipo carnet */}
          <div style={{ position: 'relative', margin: '0 20px', aspectRatio: '5 / 4', borderRadius: 12, overflow: 'hidden', background: TOKENS.primaryBg }}>
            {photo ?
            <img src={photo} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} /> :
            <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'rgba(255,255,255,0.92)', fontSize: 64, fontWeight: 800, letterSpacing: '0.02em', background: TOKENS.primaryBg, color: TOKENS.primary }}>{window.deriveInitials ? window.deriveInitials(perfil.nombre) : ''}</div>}
            {/* Estado del día como sello */}
            <div style={{
              position: 'absolute', top: 10, right: 10, background: 'rgba(255,255,255,0.92)', borderRadius: 999,
              padding: '4px 10px', fontSize: 10, fontWeight: 800, color: TOKENS.primary, letterSpacing: '0.03em',
              display: 'flex', alignItems: 'center', gap: 5, boxShadow: '0 2px 6px rgba(11,28,48,0.18)'
            }}>
              <span style={{ width: 6, height: 6, borderRadius: 999, background: TOKENS.success }} />
              Activo
            </div>
          </div>

          {/* Nombre + rol */}
          <div style={{ padding: '14px 20px 0' }}>
            <div style={{ fontSize: 23, fontWeight: 800, color: TOKENS.text, letterSpacing: '-0.015em', lineHeight: 1.1 }}>{perfil.nombre}</div>
            <div style={{ fontSize: 13, fontWeight: 600, color: TOKENS.textMuted, marginTop: 3 }}>
              {isAdmin ? 'Administrador de operación' : 'Mensajero'}
            </div>
          </div>

          {/* Pie de datos */}
          <div style={{ display: 'flex', gap: 10, padding: '14px 20px 4px' }}>
            <BadgeFact label="Móvil" value={perfil.telefono || '—'} />
            {isAdmin ?
            <BadgeFact label="ID" value={perfil.identificacion || '—'} align="right" /> :
            <BadgeFact label="Placa" value={perfil.placa || '—'} mono align="right" />}
          </div>

          {/* Actividad del día */}
          <div style={{ margin: '12px 20px 0', padding: '10px 12px', background: TOKENS.surfaceLow, borderRadius: 10, border: `1px solid ${TOKENS.border}`, display: 'flex', alignItems: 'center', gap: 8 }}>
            {I.route(15, TOKENS.primary)}
            <span style={{ fontSize: 12, fontWeight: 600, color: TOKENS.text }}>Hoy</span>
            <span style={{ flex: 1 }} />
            <span style={{ fontSize: 12, fontWeight: 700, color: TOKENS.textMuted }}>{resumenActividad}</span>
          </div>

          {/* Acción */}
          <div style={{ padding: '14px 20px 18px' }}>
            <button onClick={onVerPerfil} style={{
              width: '100%', padding: '12px', borderRadius: 11, cursor: 'pointer', fontFamily: 'inherit',
              background: TOKENS.primary, border: 'none', color: '#fff', fontSize: 13.5, fontWeight: 700,
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7
            }}>{I.user(16, '#fff')} Ver mi perfil</button>
          </div>
        </div>
      </div>
    </div>);

}
function BadgeFact({ label, value, mono, align }) {
  return (
    <div style={{ flex: 1, minWidth: 0, textAlign: align === 'right' ? 'right' : 'left' }}>
      <div style={{ fontSize: 9.5, fontWeight: 700, color: TOKENS.textSubtle, letterSpacing: '0.08em', textTransform: 'uppercase' }}>{label}</div>
      <div style={{ fontSize: 13.5, fontWeight: 700, color: TOKENS.text, marginTop: 3, fontFamily: mono ? 'monospace' : 'inherit', letterSpacing: mono ? '0.06em' : 0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{value}</div>
    </div>);

}

// ── Sub-componentes del tablero ───────────────────────────────────────────
// Estados del admin (13/11/2026): los mismos cuatro de PROCESOS, meta de 3 días hábiles.
const ESTADOS_ADMIN = [
  { label: 'Vencido', rango: '5+ días hábiles', color: TOKENS.danger },
  { label: 'Retrasado', rango: '4 días hábiles', color: TOKENS.warning },
  { label: 'Vence hoy', rango: '3 días hábiles', color: '#f2c94c' },
  { label: 'En plazo', rango: '0–2 días hábiles', color: TOKENS.success }
];
// Por decidir: solicitudes de anulación en espera (solo aparece si hay).
function PorDecidirAdmin({ onNav }) {
  const [, r] = React.useState(0);
  React.useEffect(() => {const h = () => r((n) => n + 1);const ev = ['rodando-anulaciones', 'rodando-notifs', 'rodando-catalogo'];ev.forEach((e) => window.addEventListener(e, h));return () => ev.forEach((e) => window.removeEventListener(e, h));}, []);
  const sols = (window.loadSolicitudesAnulacion ? window.loadSolicitudesAnulacion() : []).filter((x) => x.estado === 'espera');
  // Talleres que escribió el mensajero en Recoger (13/11/2026) → Catálogos › Por revisar.
  const tns = window.catPendientesMensajero ? window.catPendientesMensajero() : [];
  const cors = (window.loadCorrecciones ? window.loadCorrecciones() : []).filter((x) => x.estado === 'espera');
  if (!sols.length && !tns.length && !cors.length) return null;
  const fila = (key, icon, iconBg, titulo, sub, onClick, first) =>
  <button key={key} type="button" onClick={onClick} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 11, padding: '12px 13px', background: 'transparent', border: 'none', borderTop: first ? 'none' : `1px solid ${TOKENS.border}`, cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left' }}>
      <span style={{ width: 34, height: 34, borderRadius: 10, background: iconBg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{icon}</span>
      <span style={{ flex: 1, minWidth: 0 }}>
        <b style={{ display: 'block', fontSize: 14, color: TOKENS.text }}>{titulo}</b>
        <span style={{ display: 'block', fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>{sub}</span>
      </span>
      <span style={{ fontSize: 13, fontWeight: 800, color: TOKENS.primary }}>Ver ›</span>
    </button>;
  const filas = [];
  if (sols.length) {
    const nombres = [...new Set(sols.map((x) => x.porNombre).filter(Boolean))].join(', ');
    const antigua = Math.min(...sols.map((x) => x.createdAt || Date.now()));
    filas.push(fila('anu', I.ban(17, TOKENS.anulado), TOKENS.anuladoBg, `${sols.length} ${sols.length === 1 ? 'solicitud de anulación' : 'solicitudes de anulación'}`,
    `${nombres ? 'De ' + nombres + ' · ' : ''}la más antigua ${window.relTime ? window.relTime(antigua) : ''}`, () => onNav('notificaciones'), !filas.length));
  }
  if (cors.length) {
    const nombres = [...new Set(cors.map((x) => x.porNombre).filter(Boolean))].join(', ');
    filas.push(fila('cor', I.pencil(17, '#8a5a00'), '#fdf0d5', `${cors.length} ${cors.length === 1 ? 'corrección de entrega' : 'correcciones de entrega'}`,
    `${nombres ? 'De ' + nombres + ' · ' : ''}${cors.slice(0, 2).map((x) => x.placa).join(', ')}${cors.length > 2 ? '…' : ''}`, () => onNav('notificaciones'), !filas.length));
  }
  if (tns.length) {
    const nombres = [...new Set(tns.map((x) => x.porNombre).filter(Boolean))].join(', ');
    filas.push(fila('tal', I.building(17, '#7f6000'), '#fff2cc', `${tns.length} ${tns.length === 1 ? 'taller nuevo por revisar' : 'talleres nuevos por revisar'}`,
    `${nombres ? 'Los escribió ' + nombres + ' · ' : ''}${tns.slice(0, 2).map((x) => x.taller).join(', ')}${tns.length > 2 ? '…' : ''}`, () => { window.rdAbrirCatalogo = 'revisar'; onNav('ajustes'); }, !filas.length));
  }
  return (
    <>
      <SectionLabel>Por decidir</SectionLabel>
      <div style={tableCardStyle}>{filas}</div>
    </>);
}
// Mensajeros hoy: progreso de la ruta y parada en curso → Rutas.
function MensajerosHoyAdmin({ onNav }) {
  const [, r] = React.useState(0);
  React.useEffect(() => {const h = () => r((n) => n + 1);window.addEventListener('rodando-paradas', h);const t = setInterval(h, 5000);return () => {window.removeEventListener('rodando-paradas', h);clearInterval(t);};}, []);
  const ms = window.mensajerosApp ? window.mensajerosApp() : [];
  if (!ms.length) return null;
  const hoy = fechaDDMMYYYY();
  const paradas = window.loadParadas ? window.loadParadas() : [];
  return (
    <>
      <SectionLabel>Mensajeros hoy</SectionLabel>
      <div style={tableCardStyle}>
        {ms.map((m, i) => {
          const mine = paradas.filter((p) => p.fecha === hoy && p.asignadoA === m.usuario && ['pendiente', 'en_curso', 'completada'].includes(p.estado));
          const dest = window.groupByDestino ? window.groupByDestino(mine) : [];
          const hechas = dest.filter((x) => x.estado === 'completada').length;
          const cur = dest.find((x) => x.estado === 'en_curso');
          const pct = dest.length ? Math.round(hechas / dest.length * 100) : 0;
          return (
            <button key={m.usuario} type="button" onClick={() => onNav('rutas')} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 11, padding: '12px 13px', background: 'transparent', border: 'none', borderTop: i ? `1px solid ${TOKENS.border}` : 'none', cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left' }}>
              <span style={{ width: 34, height: 34, borderRadius: 999, background: TOKENS.primaryBg, color: TOKENS.primary, fontSize: 12, fontWeight: 800, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{window.deriveInitials ? window.deriveInitials(m.nombre) : ''}</span>
              <span style={{ flex: 1, minWidth: 0 }}>
                <b style={{ display: 'block', fontSize: 14, color: TOKENS.text }}>{m.nombre}</b>
                <span style={{ display: 'block', fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>{dest.length ? `${hechas} de ${dest.length} ${dest.length === 1 ? 'parada completada' : 'paradas completadas'}` : 'Sin ruta para hoy'}</span>
                {dest.length > 0 && <span style={{ display: 'block', height: 6, borderRadius: 999, background: TOKENS.surfaceLow, overflow: 'hidden', marginTop: 6 }}><span style={{ display: 'block', width: pct + '%', height: '100%', background: TOKENS.primary, borderRadius: 999 }} /></span>}
                {cur &&
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11.5, fontWeight: 500, color: TOKENS.cautionText, background: TOKENS.cautionBg, borderRadius: 999, padding: '2px 9px', marginTop: 6 }}>
                    <span style={{ width: 7, height: 7, borderRadius: 999, background: TOKENS.cautionText, animation: 'rdBlink 1.4s infinite' }} />
                    En curso: {cur.taller}{cur.sede ? ' · ' + cur.sede : ''}{cur.iniciadaEn && window.LiveTimer ? <> · <window.LiveTimer since={cur.iniciadaEn} /></> : null}
                  </span>
                }
              </span>
              <span style={{ fontSize: 13, fontWeight: 800, color: TOKENS.primary, flexShrink: 0 }}>Ruta ›</span>
            </button>);
        })}
      </div>
    </>);
}

function SectionLabel({ children }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      fontSize: 11.5, fontWeight: 700, color: TOKENS.textMuted,
      letterSpacing: '0.06em', textTransform: 'uppercase',
      margin: '22px 2px 11px'
    }}>{children}</div>);
}
const seeAllBtn = {
  background: 'transparent', border: 'none', cursor: 'pointer', fontFamily: 'inherit',
  fontSize: 11, fontWeight: 700, color: TOKENS.primary, letterSpacing: '0.02em',
  textTransform: 'none', padding: 0
};
const assignRowStyle = {
  display: 'flex', alignItems: 'center', gap: 12, width: '100%',
  padding: '11px 12px', background: TOKENS.surface, borderRadius: 12,
  border: `1px solid ${TOKENS.border}`, cursor: 'pointer', fontFamily: 'inherit'
};

function AlertBanner({ tone, icon, title, sub, cta, onClick }) {
  const cfg = tone === 'danger' ?
  { bg: TOKENS.dangerBg, bd: TOKENS.dangerBorder, tx: TOKENS.danger } :
  { bg: '#dde9fb', bd: '#b9d2f4', tx: TOKENS.primaryText };
  return (
    <button onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 12, width: '100%', textAlign: 'left',
      padding: '12px 14px', borderRadius: 13, cursor: 'pointer', fontFamily: 'inherit',
      background: cfg.bg, border: `1px solid ${cfg.bd}`
    }}>
      <div style={{
        width: 38, height: 38, borderRadius: 10, flexShrink: 0,
        background: 'rgba(255,255,255,0.6)',
        display: 'flex', alignItems: 'center', justifyContent: 'center'
      }}>{icon}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 800, color: cfg.tx }}>{title}</div>
        <div style={{ fontSize: 11.5, color: cfg.tx, opacity: 0.82, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{sub}</div>
      </div>
      <div style={{
        flexShrink: 0, display: 'flex', alignItems: 'center', gap: 3,
        fontSize: 12, fontWeight: 700, color: cfg.tx
      }}>
        <span>{cta}</span>{I.arrowR(15, cfg.tx)}
      </div>
    </button>);
}

function MetricTile({ icon, color, value, unit, label, foot, onClick }) {
  return (
    <button onClick={onClick} style={{
      display: 'flex', flexDirection: 'column', alignItems: 'flex-start',
      padding: '15px 14px 13px', background: TOKENS.surface, borderRadius: 14,
      border: `1px solid ${TOKENS.border}`, cursor: 'pointer', fontFamily: 'inherit',
      textAlign: 'left', minHeight: 124
    }}>
      <div style={{
        width: 34, height: 34, borderRadius: 9, background: `${color}15`,
        display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 12
      }}>{icon(19, color)}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 5 }}>
        <span style={{ fontSize: 28, fontWeight: 800, color: TOKENS.text, lineHeight: 1 }}>{value}</span>
        <span style={{ fontSize: 11.5, fontWeight: 600, color: TOKENS.textMuted }}>{unit}</span>
      </div>
      <div style={{ fontSize: 12.5, fontWeight: 600, color: TOKENS.text, marginTop: 7, lineHeight: 1.25 }}>{label}</div>
      <div style={{ fontSize: 10.5, color: TOKENS.textSubtle, marginTop: 'auto', paddingTop: 6 }}>{foot}</div>
    </button>);
}

// ── Tablas del tablero (Flujo + Estado de pendientes) ─────────────────────
const tableCardStyle = {
  background: TOKENS.surface, border: `1px solid ${TOKENS.border}`,
  borderRadius: 14, overflow: 'hidden'
};
const flowHeadStyle = {
  display: 'flex', alignItems: 'center', padding: '10px 14px 8px',
  borderBottom: `1px solid ${TOKENS.border}`
};
const flowColHead = {
  width: 62, textAlign: 'right', fontSize: 10.5, fontWeight: 700,
  color: TOKENS.textMuted, letterSpacing: '0.04em', textTransform: 'uppercase'
};
const sevColHead = {
  width: 54, textAlign: 'right', fontSize: 10.5, fontWeight: 700,
  color: TOKENS.textMuted, letterSpacing: '0.04em', textTransform: 'uppercase'
};

function FlowRow({ icon, color, label, hoy, semana, onClick, onHoy, last }) {
  const cellBtn = {
    width: 62, textAlign: 'right', background: 'transparent', border: 'none',
    cursor: 'pointer', fontFamily: 'inherit', padding: '6px 0',
    borderRadius: 8
  };
  return (
    <div style={{
      display: 'flex', alignItems: 'center', width: '100%', padding: '7px 14px',
      borderBottom: last ? 'none' : `1px solid ${TOKENS.border}`
    }}>
      <button onClick={onClick} style={{
        display: 'flex', alignItems: 'center', flex: 1, minWidth: 0, gap: 11,
        background: 'transparent', border: 'none', cursor: 'pointer',
        fontFamily: 'inherit', padding: '6px 0', textAlign: 'left'
      }}>
        <div style={{
          width: 30, height: 30, borderRadius: 8, background: `${color}15`,
          display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0
        }}>{icon(17, color)}</div>
        <span style={{ fontSize: 13.5, fontWeight: 600, color: TOKENS.text }}>{label}</span>
      </button>
      <button onClick={onHoy || onClick} style={{ ...cellBtn, fontSize: 18, fontWeight: 800, color: TOKENS.text }}>{hoy}</button>
      <span style={{ width: 62, textAlign: 'right', fontSize: 18, fontWeight: 700, color: TOKENS.textMuted, padding: '6px 0' }}>{semana}</span>
    </div>);
}

function ProportionBar({ sev, total }) {
  const segs = [
  { k: 'aldia', v: sev.aldia },
  { k: 'atrasado', v: sev.atrasado },
  { k: 'critico', v: sev.critico }].
  filter((s) => s.v > 0);
  return (
    <div style={{ display: 'flex', height: 10, borderRadius: 999, overflow: 'hidden', background: '#eef1f5', gap: 2 }}>
      {total > 0 && segs.map((s) =>
      <div key={s.k} title={`${window.SEVERITY_META[s.k].label}: ${s.v}`}
      style={{ flex: s.v, background: window.SEVERITY_META[s.k].color, minWidth: 5 }} />
      )}
    </div>);
}

function SevRow({ meta, count, pct, onClick, last }) {
  return (
    <button onClick={onClick} style={{
      display: 'flex', alignItems: 'center', width: '100%', padding: '12px 14px',
      background: 'transparent', border: 'none', borderTop: `1px solid ${TOKENS.border}`,
      cursor: 'pointer', fontFamily: 'inherit'
    }}>
      <span style={{ width: 11, height: 11, borderRadius: 999, background: meta.color, marginRight: 12, flexShrink: 0 }} />
      <span style={{ flex: 1, textAlign: 'left', minWidth: 0 }}>
        <span style={{ display: 'block', fontSize: 13.5, fontWeight: 700, color: TOKENS.text }}>{meta.label}</span>
        <span style={{ display: 'block', fontSize: 11, color: TOKENS.textMuted, marginTop: 1 }}>{meta.rango}</span>
      </span>
      <span style={{ width: 54, textAlign: 'right', fontSize: 18, fontWeight: 800, color: count ? TOKENS.text : TOKENS.textSubtle }}>{count}</span>
      <span style={{ width: 54, textAlign: 'right', fontSize: 13, fontWeight: 600, color: TOKENS.textMuted }}>{pct}%</span>
    </button>);
}

// ─── Imprimir (ticket preview) ────────────────────────────────────────────
const ticketTh = { padding: '3px 4px', textAlign: 'center', fontWeight: 700, fontSize: 10, textTransform: 'uppercase' };
const ticketTd = { padding: '4px 4px', textAlign: 'center', verticalAlign: 'top' };
function ImprimirScreen({ ticket, onBack, onPrint }) {
  return (
    <div style={{ background: TOKENS.bg, display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
      <AppHeader title="Imprimir Ticket" onBack={onBack} bell={false} />
      <div style={{ padding: '16px' }}>
        <div style={{ fontSize: 12, color: TOKENS.textMuted, marginBottom: 10, textAlign: 'center' }}>
          Vista previa · 58 mm · Impresora térmica Bluetooth
        </div>
        {/* Ticket */}
        <div style={{
          background: '#fff', padding: '20px 18px', borderRadius: 8,
          boxShadow: '0 2px 8px rgba(0,0,0,0.08)',
          fontFamily: '"SF Mono", "Consolas", "Menlo", monospace',
          fontSize: 12, color: '#000', lineHeight: 1.55,
          backgroundImage: 'repeating-linear-gradient(135deg, transparent 0, transparent 2px, rgba(0,0,0,0.012) 2px, rgba(0,0,0,0.012) 4px)',
          position: 'relative'
        }}>
          {/* Torn top edge */}
          <div style={{
            position: 'absolute', top: -6, left: 0, right: 0, height: 6,
            backgroundImage: 'linear-gradient(135deg, #fff 33%, transparent 33%), linear-gradient(45deg, #fff 33%, transparent 33%)',
            backgroundSize: '8px 8px'
          }} />
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontWeight: 700, fontSize: 14, letterSpacing: '0.1em' }}>RODANDO · SALVALLANTAS S.A.S.</div>
            <div style={{ fontSize: 10 }}>NIT 900.123.456-7</div>
            <div style={{ fontSize: 10 }}>Recolección de Llantas y Rines</div>
          </div>
          <div style={{ borderTop: '1px dashed #000', margin: '10px 0' }} />

          {[
          ['Fecha', ticket.fecha],
          ['Orden', '' + ticket.codigo],
          [ticket.idType === 'vin' ? 'VIN' : 'Placa', ticket.placa],
          ['Aseguradora', ticket.aseguradora],
          ['Taller', ticket.taller],
          ['Sede', ticket.sede],
          ['Mensajero', window.userName ? window.userName() : 'Juan Diego']].
          map(([k, v]) =>
          <div key={k} style={{ display: 'flex', justifyContent: 'space-between' }}>
              <span>{k}:</span><span style={{ fontWeight: 600 }}>{v}</span>
            </div>
          )}

          <div style={{ borderTop: '1px dashed #000', margin: '10px 0' }} />
          <div style={{ fontWeight: 700, textTransform: 'uppercase', fontSize: 11, marginBottom: 6 }}>Producto a retirar</div>
          {/* Tabla: Item · Información · Cant. */}
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 11, tableLayout: 'fixed' }}>
            <colgroup>
              <col style={{ width: '30px' }} />
              <col />
              <col style={{ width: '34px' }} />
            </colgroup>
            <thead>
              <tr style={{ borderBottom: '1px solid #000' }}>
                <th style={ticketTh}>Item</th>
                <th style={{ ...ticketTh, textAlign: 'left' }}>Información</th>
                <th style={{ ...ticketTh, textAlign: 'right' }}>Cant.</th>
              </tr>
            </thead>
            <tbody>
              {ticket.items.map((it, i) => {
                const label = it.tipo === 'rin' ? `RIN ${it.tamano}"${it.material ? ` ${it.material}` : ''}` :
                it.tipo === 'llanta' ? `LLANTA ${it.marca ? it.marca + ' ' : ''}${it.referencia || ''}`.trim() :
                `VÁLVULA ${it.valvulaSensor === 'Sí' ? 'TPMS' : 'std'}`;
                // Desglose "3x 0620 · 1x 0625" para DOT/calidad con variaciones.
                const fmt = (field) => llantaBreakdown(it, field).
                map((g) => `${g.count}x ${g.value}`).join(' · ');
                return (
                  <tr key={it.id} style={{ borderBottom: '1px solid #000', verticalAlign: 'top' }}>
                    <td style={ticketTd}>{String(i + 1).padStart(2, '0')}</td>
                    <td style={{ ...ticketTd, borderLeft: '1px solid #000', borderRight: '1px solid #000', textAlign: 'left', wordBreak: 'break-word' }}>
                      <div style={{ fontWeight: 700 }}>{label}</div>
                      {it.tipo === 'rin' &&
                      <div style={{ marginTop: 2 }}>{`${it.huecos} · Tapa ${it.tapa} · Tapa Valv ${it.tapaValvula}`}</div>
                      }
                      {it.tipo === 'llanta' &&
                      <div style={{ marginTop: 2 }}>
                          <div>DOT: {fmt('dot') || '—'}</div>
                          <div>Calidad: {fmt('calidad') || '—'}</div>
                        </div>
                      }
                      {it.tipo === 'valvula' &&
                      <div style={{ marginTop: 2 }}>{it.valvulaSensor === 'Sí' ? 'Con sensor TPMS' : 'Sin sensor'}</div>
                      }
                      {it.observaciones &&
                      <div style={{ marginTop: 2, fontStyle: 'italic' }}>Obs: {it.observaciones}</div>
                      }
                    </td>
                    <td style={{ ...ticketTd, textAlign: 'right', fontWeight: 700 }}>{it.cantidad}×</td>
                  </tr>);
              })}
            </tbody>
          </table>
          <div style={{ borderTop: '1px dashed #000', margin: '10px 0' }} />
          <div style={{ display: 'flex', justifyContent: 'space-between', fontWeight: 700 }}>
            <span>TOTAL ITEMS</span>
            <span>{ticket.items.reduce((s, it) => s + Number(it.cantidad), 0)}</span>
          </div>
          <div style={{ borderTop: '1px dashed #000', margin: '10px 0' }} />
          <div style={{ textAlign: 'center', marginTop: 10, fontSize: 10 }}>
            ¡Gracias!
          </div>
          {/* Torn bottom */}
          <div style={{
            marginTop: 12, height: 6,
            backgroundImage: 'linear-gradient(225deg, #fff 33%, transparent 33%), linear-gradient(315deg, #fff 33%, transparent 33%)',
            backgroundSize: '8px 8px'
          }} />
        </div>

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

}

// ─── Ticket generado (12/11/2026) ───────────────────────────────────────
// Después de "Generar ticket": consecutivo, Imprimir, Nueva recogida, Volver al inicio.
function CerrarTicketScreen({ placa, codigo, idType, isEditing, onImprimir, onNuevo, onMenu }) {
  const idLabel = idType === 'vin' ? 'del VIN' : 'de la placa';
  const enCurso = window.getRutaEnCurso ? window.getRutaEnCurso() : null;
  return (
    <div style={{ background: TOKENS.bg, display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
      <AppHeader title={isEditing ? 'Cambios guardados' : 'Ticket generado'} />
      <div style={{ flex: 1, padding: '28px 20px 24px', textAlign: 'center' }}>
        <div style={{ width: 76, height: 76, borderRadius: 999, background: TOKENS.successBg, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '12px auto 16px' }}>
          <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke={TOKENS.success} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5" /></svg>
        </div>
        <div style={{ fontSize: 22, fontWeight: 800, color: TOKENS.text, letterSpacing: '-0.01em' }}>{isEditing ? 'Cambios guardados' : 'Ticket generado'}</div>
        <div style={{ fontSize: 13.5, color: TOKENS.textMuted, marginTop: 6, lineHeight: 1.5 }}>
          La recogida {idLabel} <b style={{ color: TOKENS.text }}>{placa}</b> quedó guardada.
        </div>
        <div style={{ display: 'inline-block', marginTop: 16, fontFamily: "'JetBrains Mono', monospace", fontSize: 26, fontWeight: 600, color: TOKENS.text, background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 12, padding: '10px 18px' }}>{codigo}</div>
        <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 6 }}>{fechaHoraCorta()}</div>

        <div style={{ display: 'grid', gap: 8, marginTop: 22, textAlign: 'left' }}>
          <Button variant="primary" full icon={I.print(16, '#fff')} onClick={onImprimir} style={{ padding: '13px', fontSize: 15 }}>Imprimir ticket</Button>
          <Button variant="outline" full icon={I.plus(16, TOKENS.text)} onClick={onNuevo} style={{ padding: '13px', fontSize: 15 }}>Nueva recogida</Button>
          <Button variant="outline" full icon={I.dash(16, TOKENS.text)} onClick={onMenu} style={{ padding: '13px', fontSize: 15 }}>Volver al inicio</Button>
        </div>
        {enCurso &&
        <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 16, lineHeight: 1.5 }}>
            Si terminaste en {enCurso.taller}, recuerda tocar <b style={{ color: TOKENS.text }}>Finalizar</b> en Mi ruta.
          </div>}
      </div>
    </div>);
}

// ─── Editar list (select an item to edit) ───────────────────────────────
function EditarScreen({ ticket, onEdit, onDelete, onBack }) {
  const items = ticket.items || [];
  const totalUnits = items.reduce((s, it) => s + Number(it.cantidad), 0);
  const rines = items.filter((i) => i.tipo === 'rin');
  const llantas = items.filter((i) => i.tipo === 'llanta');
  const valvulas = items.filter((i) => i.tipo === 'valvula');
  const [confirmDelete, setConfirmDelete] = React.useState(null);
  const itemToDelete = confirmDelete ? items.find((i) => i.id === confirmDelete) : null;

  return (
    <div style={{ background: TOKENS.bg, display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
      <AppHeader title="Editar Registro" onBack={onBack} bell={false} />
      <div style={{ padding: 16 }}>

        {/* Placa hero (same style as Grabar) */}
        <div style={{
          background: TOKENS.heroGradient, color: '#fff', borderRadius: 14,
          padding: '16px 18px', display: 'flex', alignItems: 'center', gap: 14, marginBottom: 14
        }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 11, opacity: 0.65, letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 600 }}>
              {ticket.idType === 'vin' ? 'VIN del vehículo' : 'Placa del vehículo'}
            </div>
            <div style={{ fontSize: 26, fontWeight: 700, letterSpacing: '0.04em', marginTop: 2, wordBreak: 'break-all' }}>
              {ticket.placa || '—'}
            </div>
            <div style={{ fontSize: 12, opacity: 0.75, marginTop: 4 }}>
              {ticket.taller || '—'} · {ticket.sede || '—'} · {ticket.aseguradora || '—'}
            </div>
          </div>
          <div style={{
            width: 52, height: 52, borderRadius: 12,
            background: 'rgba(255,255,255,0.1)',
            display: 'flex', alignItems: 'center', justifyContent: 'center'
          }}>{I.pencil(26, '#fff')}</div>
        </div>

        {/* Fecha + Código row */}
        <Card style={{ marginBottom: 14, padding: '12px 16px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
            <div>
              <div style={{ color: TOKENS.textMuted, fontSize: 11, fontWeight: 600, letterSpacing: '0.05em', textTransform: 'uppercase' }}>Fecha</div>
              <div style={{ fontWeight: 700, color: TOKENS.text, marginTop: 2 }}>{ticket.fecha}</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ color: TOKENS.textMuted, fontSize: 11, fontWeight: 600, letterSpacing: '0.05em', textTransform: 'uppercase' }}>Orden</div>
              <div style={{ fontWeight: 700, color: TOKENS.text, marginTop: 2, fontFamily: 'monospace' }}>{ticket.codigo}</div>
            </div>
          </div>
        </Card>

        {/* Items header */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8, padding: '0 4px' }}>
          <div style={{ fontSize: 15, fontWeight: 700, color: TOKENS.text, display: 'flex', alignItems: 'center', gap: 8 }}>
            {I.pencil(18, TOKENS.primary)}
            Items a editar
          </div>
          <Chip tone="dark">Total: {totalUnits}</Chip>
        </div>

        <div style={{ fontSize: 12, color: TOKENS.textMuted, marginBottom: 12, padding: '0 4px' }}>
          Toca el item que deseas modificar.
        </div>

        {rines.length > 0 && <EditGroup title="RINES" items={rines} allItems={items} onEdit={onEdit} onDelete={setConfirmDelete} />}
        {llantas.length > 0 && <EditGroup title="LLANTAS" items={llantas} allItems={items} onEdit={onEdit} onDelete={setConfirmDelete} />}
        {valvulas.length > 0 && <EditGroup title="VÁLVULAS" items={valvulas} allItems={items} onEdit={onEdit} onDelete={setConfirmDelete} />}

        {items.length === 0 &&
        <div style={{
          padding: 32, textAlign: 'center', color: TOKENS.textMuted, fontSize: 13,
          background: TOKENS.surfaceLow, borderRadius: 12, border: `1px dashed ${TOKENS.border}`
        }}>No hay items para editar todavía.</div>
        }
      </div>
      <div style={{ padding: '12px 16px 16px', borderTop: `1px solid ${TOKENS.border}`, background: TOKENS.bg, position: 'sticky', bottom: 0, zIndex: 10 }}>
        <Button variant="dark" full onClick={onBack} icon={I.check(16, '#fff')}>Terminar</Button>
      </div>

      {itemToDelete &&
      <DeleteItemModal
        item={itemToDelete}
        onConfirm={() => {onDelete(itemToDelete.id);setConfirmDelete(null);}}
        onDismiss={() => setConfirmDelete(null)} />

      }
    </div>);

}

function EditGroup({ title, items, allItems, onEdit, onDelete }) {
  return (
    <Card style={{ marginBottom: 12, padding: '14px 16px' }}>
      <div style={{ fontSize: 11, fontWeight: 700, color: TOKENS.primary, letterSpacing: '0.08em', marginBottom: 10 }}>
        {title} · {items.reduce((s, i) => s + Number(i.cantidad), 0)} und
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {items.map((it) => <EditRow key={it.id} item={it} idx={allItems.indexOf(it)} onEdit={onEdit} onDelete={onDelete} />)}
      </div>
    </Card>);

}

function EditRow({ item, idx, onEdit, onDelete }) {
  const isRin = item.tipo === 'rin';
  const isLlanta = item.tipo === 'llanta';
  const isValvula = item.tipo === 'valvula';
  const icon = isRin ? I.rin : isLlanta ? I.llanta : I.ajustes;

  return (
    <div onClick={() => onEdit(item.id)} style={{
      background: TOKENS.surfaceLow, borderRadius: 12, padding: '14px 14px',
      display: 'flex', alignItems: 'flex-start', gap: 12, cursor: 'pointer'
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: 10, background: '#fff',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: TOKENS.primary, border: `1px solid ${TOKENS.border}`, flexShrink: 0, marginTop: 2
      }}>{icon(20, TOKENS.primary)}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 10, fontWeight: 700, color: TOKENS.navy, letterSpacing: '0.08em',
          marginBottom: 3
        }}>ITEM {String(idx + 1).padStart(2, '0')}</div>
        <div style={{ fontSize: 14, fontWeight: 700, color: TOKENS.text }}>
          {isRin && `Rin ${item.tamano}″`}
          {isLlanta && (item.referencia || 'Llanta')}
          {isValvula && `Válvula ${item.valvulaSensor === 'Sí' ? 'TPMS' : 'estándar'}`}
        </div>
        <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 4, display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 4, lineHeight: 1.5 }}>
          {isRin && <>
            <span>{item.material}</span>
            <span>·</span>
            <span>{item.huecos}</span>
            <span>·</span>
            <span>Tapa</span>
            <Chip tone={item.tapa === 'Sí' ? 'success' : 'danger'}>{item.tapa === 'Sí' ? 'SÍ' : 'NO'}</Chip>
            <span>·</span>
            <span>T. Válvula</span>
            <Chip tone={item.tapaValvula === 'Sí' ? 'success' : 'danger'}>{item.tapaValvula === 'Sí' ? 'SÍ' : 'NO'}</Chip>
          </>}
          {isLlanta && <span>{item.marca || 'sin marca'} · DOT {item.dot || '—'}</span>}
          {isValvula && <span>{item.valvulaSensor === 'Sí' ? 'Con sensor TPMS' : 'Sin sensor'}</span>}
        </div>
        {item.observaciones &&
        <div style={{
          fontSize: 11, color: TOKENS.textMuted, marginTop: 8, padding: '6px 10px',
          background: '#fff', borderRadius: 6, border: `1px dashed ${TOKENS.border}`,
          fontStyle: 'italic'
        }}>
            <b style={{ color: TOKENS.text, fontStyle: 'normal' }}>Obs:</b> {item.observaciones}
          </div>
        }
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 8, flexShrink: 0 }}>
        {isLlanta &&
        <Chip tone={item.calidad === 'Nueva' ? 'success' : item.calidad === 'Usada' ? 'warn' : 'danger'}>
            {item.calidad}
          </Chip>
        }
        <div style={{
          fontSize: 13, fontWeight: 700, color: TOKENS.primary,
          background: '#fff', padding: '4px 10px', borderRadius: 6,
          border: `1px solid ${TOKENS.border}`, minWidth: 30, textAlign: 'center', fontFamily: 'monospace'
        }}>×{item.cantidad}</div>
        <div style={{ display: 'flex', gap: 6 }}>
          <button onClick={(e) => {e.stopPropagation();onDelete && onDelete(item.id);}} style={{
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            width: 30, height: 30, borderRadius: 8,
            background: '#fff', color: TOKENS.danger,
            border: `1px solid ${TOKENS.border}`,
            cursor: 'pointer', fontFamily: 'inherit'
          }} aria-label="Eliminar item">
            {I.trash(14, TOKENS.danger)}
          </button>
          <button onClick={(e) => {e.stopPropagation();onEdit(item.id);}} style={{
            display: 'inline-flex', alignItems: 'center', gap: 4,
            padding: '6px 10px', borderRadius: 8, fontSize: 11, fontWeight: 700,
            background: TOKENS.primary, color: '#fff', border: 'none',
            cursor: 'pointer', fontFamily: 'inherit', letterSpacing: '0.02em'
          }}>
            {I.pencil(12, '#fff')} Editar
          </button>
        </div>
      </div>
    </div>);

}

// ─── Delete item confirmation modal ─────────────────────────────────────
function DeleteItemModal({ item, onConfirm, onDismiss }) {
  const label =
  item.tipo === 'rin' ? `Rin ${item.tamano}″` :
  item.tipo === 'llanta' ? item.referencia || 'Llanta' :
  `Válvula ${item.valvulaSensor === 'Sí' ? 'TPMS' : 'estándar'}`;
  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(11,28,48,0.5)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000,
      padding: 16
    }}>
      <div style={{
        background: TOKENS.surface, borderRadius: 18, padding: 22, width: '100%', maxWidth: 380,
        boxShadow: '0 16px 40px rgba(0,0,0,0.2)'
      }}>
        <div style={{
          width: 56, height: 56, borderRadius: 999, background: TOKENS.dangerBg,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          margin: '0 auto 14px'
        }}>{I.trash(28, TOKENS.danger)}</div>
        <div style={{ fontSize: 17, fontWeight: 700, color: TOKENS.text, textAlign: 'center' }}>
          ¿Eliminar este item?
        </div>
        <div style={{ fontSize: 13, color: TOKENS.textMuted, textAlign: 'center', marginTop: 6, lineHeight: 1.5 }}>
          Se eliminará <b style={{ color: TOKENS.text }}>{label}</b> ({`×${item.cantidad}`}) del registro. Esta acción no se puede deshacer.
        </div>
        <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
          <Button variant="outline" full onClick={onDismiss}>Cancelar</Button>
          <Button variant="primary" full onClick={onConfirm} style={{ background: TOKENS.danger, borderColor: TOKENS.danger }}>
            Sí, eliminar
          </Button>
        </div>
      </div>
    </div>);

}

// ─── Cancel confirmation modal ──────────────────────────────────────────
function CancelModal({ onConfirm, onDismiss }) {
  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(11,28,48,0.5)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000,
      padding: 16
    }}>
      <div style={{
        background: TOKENS.surface, borderRadius: 18, padding: 22, width: '100%', maxWidth: 380,
        boxShadow: '0 16px 40px rgba(0,0,0,0.2)'
      }}>
        <div style={{
          width: 56, height: 56, borderRadius: 999, background: TOKENS.dangerBg,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          margin: '0 auto 14px'
        }}>{I.x(28, TOKENS.danger)}</div>
        <div style={{ fontSize: 17, fontWeight: 700, color: TOKENS.text, textAlign: 'center' }}>
          ¿Seguro quieres cancelar?
        </div>
        <div style={{ fontSize: 13, color: TOKENS.textMuted, textAlign: 'center', marginTop: 6, lineHeight: 1.5 }}>
          Esta acción borrará todos los datos que has escrito y te llevará de vuelta al menú.
        </div>
        <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
          <Button variant="outline" full onClick={onDismiss}>No, continuar</Button>
          <Button variant="primary" full onClick={onConfirm} style={{ background: TOKENS.danger, borderColor: TOKENS.danger }}>
            Sí, cancelar
          </Button>
        </div>
      </div>
    </div>);

}

Object.assign(window, { ENC_COLOR, EncEtiquetas, loadEncargos, saveEncargos, crearEncargo, actualizarEncargo, marcarEncargoHecho, reabrirEncargo, quitarEncargo, encargosDe, encargosPendientesDe, encParaTxt, encDonde, ENC_TIPO, useEncargos, EncargosOficina, EncargosYNotas, EncargoHechoSheet, migrarEncargos, encHoyIso, encDeIso, estadoProcesos, usuarioActual, mensajerosApp, nombreDeUsuario, RODANDO_USUARIOS, loadUsuarios, saveUsuarios, saveChecklist, loadSesion, saveSesion, MisNotas, loadChecklist,
  LoginScreen, DashboardScreen, ImprimirScreen, CerrarTicketScreen, EditarScreen, CancelModal
});