// Shared primitives, tokens, icons
// Industrial corporate-modern system: deep navy + corporate blue + cool grays

const TOKENS = {
  bg: '#f3f6fc',
  surface: '#ffffff',
  surfaceLow: '#eef2fa',
  surfaceContainer: '#e6edf8',
  surfaceHigh: '#dbe5f4',
  border: '#dde5f1',
  borderInput: '#c6d2e6',
  text: '#16233f',
  textMuted: '#5a6781',
  textSubtle: '#8c97ad',

  primary: '#1f3d77',
  primaryDark: '#16294f',
  primaryBg: '#e8effb',
  primaryBorder: '#c3d3ef',
  primaryText: '#1f3d77',

  // Estado "Pendiente" — azul claro (paleta única de estados, 11/11/2026: se quitó el dorado)
  pendiente: '#3a6aa8',
  pendienteBg: '#e7f0fa',
  pendienteBorder: '#c3d3ef',
  pendienteText: '#2f6aa8',
  pendienteOnDark: '#c9d6ee',

  navy: '#1c3669',
  navyDark: '#11234a',
  heroGradient: '#1f3d77',

  blueLite: '#3a6aa8',
  blueLiteBg: '#e7f0fa',
  blueLiteText: '#2f6aa8',

  danger: '#d32f2f',
  dangerStrong: '#b04a40',
  dangerBg: '#f7ddd6',
  dangerBorder: '#ecc7c0',
  dangerText: '#9c443c',

  warning: '#f28c28',
  warningBg: '#ffe0bd',
  warningBorder: '#f2d3a8',
  warningText: '#8f5e20',
  warningOnDark: '#e0a44e',

  caution: '#6f8fc0',
  cautionBg: '#eef4fb',
  cautionBorder: '#d3e0f1',
  cautionText: '#3f6498',

  success: '#3a6650',
  successBg: '#e9f1ec',
  successBorder: '#cadbd1',
  successText: '#3a6650',
  successOnDark: '#8fc7aa',

  // Estado "Anulado" — morado neutro (fuera de circulación, ni alerta ni éxito)
  anulado: '#6c4aa6',
  anuladoBg: '#efeaf8',
  anuladoBorder: '#ddd0ef',
  anuladoText: '#583b8a',
  anuladoOnDark: '#bda3e2',

  enCurso: '#e67c0a',
  otro: '#64748b'
};

// ─── Icons (stroke-based, 1.75 width, line-cap round) ─────────────────────
const I = {
  cash: (s = 20, c = 'currentColor') =>
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <rect x="2.5" y="6" width="19" height="13" rx="2" />
      <path d="M2.5 10h19" />
      <circle cx="17" cy="14.5" r="1.5" />
    </svg>,
  tag: (s = 20, c = 'currentColor') =>
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <path d="M20.6 13.4 13.4 20.6a2 2 0 0 1-2.8 0l-7.2-7.2A2 2 0 0 1 2.8 12V4.5A1.5 1.5 0 0 1 4.3 3h7.5a2 2 0 0 1 1.4.6l7.4 7.4a2 2 0 0 1 0 2.4z" />
      <circle cx="7.5" cy="7.5" r="1.4" />
    </svg>,
  building: (s = 20, c = 'currentColor') =>
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <rect x="4" y="3" width="16" height="18" rx="1.5" />
      <path d="M9 21v-5h6v5" />
      <path d="M8 7h2M14 7h2M8 11h2M14 11h2" />
    </svg>,
  wrench: (s = 20, c = 'currentColor') =>
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <path d="M14.7 6.3a4 4 0 0 0 5 5l-9.4 9.4a2.1 2.1 0 0 1-3-3l9.4-9.4a4 4 0 0 0-5-5l3 3-2 2-2-2z" />
    </svg>,
  shield: (s = 20, c = 'currentColor') =>
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
      <path d="m9 12 2 2 4-4" />
    </svg>,
  pin: (s = 20, c = 'currentColor') =>
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 21s-7-6.7-7-12a7 7 0 0 1 14 0c0 5.3-7 12-7 12z" />
      <circle cx="12" cy="9" r="2.5" />
    </svg>,
  users: (s = 20, c = 'currentColor') =>
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="9" cy="8" r="3.2" />
      <path d="M2.5 20a6.5 6.5 0 0 1 13 0" />
      <path d="M16 5.5a3.2 3.2 0 0 1 0 6.2" />
      <path d="M18 14.5a6.5 6.5 0 0 1 3.5 5.5" />
    </svg>,
  bell: (s = 18, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9" />
      <path d="M10.3 21a1.94 1.94 0 0 0 3.4 0" />
    </svg>,

  back: (s = 22, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M19 12H5M12 19l-7-7 7-7" />
    </svg>,

  chev: (s = 16, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M6 9l6 6 6-6" />
    </svg>,

  chevRight: (s = 16, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M9 18l6-6-6-6" />
    </svg>,

  chevLeft: (s = 16, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M15 18l-6-6 6-6" />
    </svg>,

  cal: (s = 18, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="4.5" width="18" height="16.5" rx="2" />
      <path d="M3 9.5h18M8 2.5v4M16 2.5v4" />
    </svg>,

  cam: (s = 22, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <path d="M23 19V8a2 2 0 0 0-2-2h-3.2l-1.7-2.5A1 1 0 0 0 15.3 3H8.7a1 1 0 0 0-.8.5L6.2 6H3a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h18a2 2 0 0 0 2-2z" />
      <circle cx="12" cy="13" r="4" />
      <path d="M16 6.5h2" strokeWidth="1.5" />
    </svg>,

  plus: (s = 18, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2.25" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 5v14M5 12h14" />
    </svg>,

  minus: (s = 18, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2.25" strokeLinecap="round" strokeLinejoin="round">
      <path d="M5 12h14" />
    </svg>,

  x: (s = 18, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="10" />
      <path d="M15 9l-6 6M9 9l6 6" />
    </svg>,

  pencil: (s = 18, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <path d="M16.5 3.5a2.121 2.121 0 1 1 3 3L7 19l-4 1 1-4 12.5-12.5z" />
    </svg>,

  save: (s = 18, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z" />
      <path d="M17 21v-8H7v8M7 3v5h8" />
    </svg>,

  print: (s = 18, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <path d="M6 9V2h12v7M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2" />
      <path d="M6 14h12v8H6z" />
    </svg>,

  check: (s = 18, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M20 6L9 17l-5-5" />
    </svg>,

  checkCircle: (s = 18, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" style={{ stroke: "rgb(255, 255, 255)" }} />
      <path d="M22 4L12 14.01l-3-3" />
    </svg>,

  dash: (s = 20, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="3" width="7" height="7" rx="1.5" />
      <rect x="14" y="3" width="7" height="7" rx="1.5" />
      <rect x="3" y="14" width="7" height="7" rx="1.5" />
      <rect x="14" y="14" width="7" height="7" rx="1.5" />
    </svg>,

  chart: (s = 20, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <path d="M3 3v18h18" />
      <rect x="7" y="11" width="3" height="6" rx="0.8" />
      <rect x="12.5" y="7" width="3" height="10" rx="0.8" />
      <rect x="18" y="13" width="3" height="4" rx="0.8" />
    </svg>,

  // Barra inferior (19/11/2026): Recoger = caja con solapas abiertas y flecha que entra.
  recoger: (s = 20, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M4.5 12v7a1.5 1.5 0 0 0 1.5 1.5h12a1.5 1.5 0 0 0 1.5-1.5v-7" />
      <path d="M4.5 12 2.5 9M19.5 12l2-3" />
      <path d="M12 2.5v12" />
      <path d="M8 10.5 12 14.5l4-4" />
    </svg>,

  seguimiento: (s = 20, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="4" width="5" height="16" rx="1.3" />
      <rect x="9.5" y="4" width="5" height="10" rx="1.3" />
      <rect x="16" y="4" width="5" height="13" rx="1.3" />
    </svg>,

  consultar: (s = 20, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="11" cy="11" r="7" />
      <path d="M21 21l-4.35-4.35" />
    </svg>,

  ajustes: (s = 20, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="3" />
      <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
    </svg>,

  rin: (s = 20, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="9" />
      <circle cx="12" cy="12" r="2.5" />
      <path d="M12 5v3M12 16v3M5 12h3M16 12h3M7 7l2.1 2.1M14.9 14.9L17 17M7 17l2.1-2.1M14.9 9.1L17 7" />
    </svg>,

  llanta: (s = 20, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="9" />
      <circle cx="12" cy="12" r="4" />
      <path d="M12 3v3M12 18v3M3 12h3M18 12h3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1" />
    </svg>,

  // Entregar = camión en movimiento (19/11/2026).
  truck: (s = 22, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <rect x="7" y="6" width="10.5" height="9" rx="1" />
      <path d="M17.5 9h3l2.5 3v3h-5.5z" />
      <circle cx="10.5" cy="17.5" r="1.9" />
      <circle cx="19.5" cy="17.5" r="1.9" />
      <path d="M1.5 9.5h3.5M2.5 12.5H5" />
    </svg>,
  // Inicio = casa · Rutas = pin de Rodando (19/11/2026).
  home: (s = 20, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M3.5 10.5 12 3.5l8.5 7" />
      <path d="M5.5 9v10.5a1 1 0 0 0 1 1H10v-5.5h4v5.5h3.5a1 1 0 0 0 1-1V9" />
    </svg>,
  pin: (s = 20, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 21.5 18.06 11A7 7 0 1 0 5.94 11Z" />
      <circle cx="12" cy="9.5" r="2.6" />
    </svg>,

  map: (s = 20, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <path d="M9 3l-6 3v15l6-3 6 3 6-3V3l-6 3z" />
      <path d="M9 3v15M15 6v15" />
    </svg>,

  logout: (s = 20, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
      <path d="M16 17l5-5-5-5M21 12H9" />
    </svg>,

  crop: (s = 18, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <path d="M6 2v14a2 2 0 0 0 2 2h14" />
      <path d="M2 6h14a2 2 0 0 1 2 2v14" />
    </svg>,

  trash: (s = 18, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2m2 0v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6" />
      <path d="M10 11v6M14 11v6" />
    </svg>,

  user: (s = 18, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
      <circle cx="12" cy="7" r="4" />
    </svg>,

  lock: (s = 18, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="11" width="18" height="11" rx="2" />
      <path d="M7 11V7a5 5 0 0 1 10 0v4" />
    </svg>,

  eye: (s = 18, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12z" />
      <circle cx="12" cy="12" r="3" />
    </svg>,

  doc: (s = 20, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
      <path d="M14 2v6h6M9 13h6M9 17h6M9 9h2" />
    </svg>,

  trash: (s = 18, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2m3 0v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6h14zM10 11v6M14 11v6" />
    </svg>,

  pkg: (s = 20, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" />
      <path d="M3.27 6.96L12 12l8.73-5.04M12 22V12" />
    </svg>,

  alert: (s = 20, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round">
      <path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
      <path d="M12 9v4M12 17h.01" />
    </svg>,

  clock: (s = 20, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.85" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="9" />
      <path d="M12 7v5l3 2" />
    </svg>,

  route: (s = 20, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.85" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="6" cy="19" r="3" />
      <circle cx="18" cy="5" r="3" />
      <path d="M9 19h6a3 3 0 0 0 3-3V8" />
      <path d="M6 16V8a3 3 0 0 1 3-3h6" />
    </svg>,

  arrowR: (s = 18, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M5 12h14M13 6l6 6-6 6" />
    </svg>,

  gear: (s = 20, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="3" />
      <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
    </svg>,

  ban: (s = 20, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.85" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="9" />
      <path d="M5.6 5.6l12.8 12.8" />
    </svg>,

  reactivar: (s = 20, c = 'currentColor') =>
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.85" strokeLinecap="round" strokeLinejoin="round">
      <path d="M3 12a9 9 0 1 0 2.64-6.36L3 8" />
      <path d="M3 3v5h5" />
    </svg>

};

// ─── Generic UI primitives ────────────────────────────────────────────────

// Foto de perfil personalizable (el mensajero sube su propia foto) ─────────
const LS_AVATAR_KEY = 'rodando.avatar';
// Foto por usuario (13/11/2026): cada usuario de la sesión tiene la suya.
function avatarKey() {const u = window.usuarioActual ? window.usuarioActual() : null;return u && u.usuario ? LS_AVATAR_KEY + '.' + u.usuario : LS_AVATAR_KEY;}
function loadAvatar() {try {return localStorage.getItem(avatarKey()) || '';} catch {return '';}}
function saveAvatar(d) {
  try {d ? localStorage.setItem(avatarKey(), d) : localStorage.removeItem(avatarKey());} catch (e) {}
  window.dispatchEvent(new Event('rodando-avatar'));
}
function useAvatar() {
  const [a, setA] = React.useState(loadAvatar);
  React.useEffect(() => {
    const h = () => setA(loadAvatar());
    window.addEventListener('rodando-avatar', h);
    window.addEventListener('storage', h);
    return () => {window.removeEventListener('rodando-avatar', h);window.removeEventListener('storage', h);};
  }, []);
  return a;
}

// ── Identidad del usuario (nombre + iniciales) desde el perfil ────────────
// El nombre vive en el perfil (rodando.perfil) y puede editarse en Mi perfil.
// Estos helpers lo leen en vivo para que TODOS los lugares (saludo, avatares,
// resúmenes) muestren el nombre actual y se actualicen al cambiarlo.
function userName() {
  try {const p = window.loadPerfil && window.loadPerfil();if (p && p.nombre) return p.nombre;} catch (e) {}
  return 'Usuario';
}
function deriveInitials(name) {
  // Sin tildes en las iniciales (César → CE)
  const parts = String(name || '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').trim().split(/\s+/).filter(Boolean);
  if (!parts.length) return '··';
  if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
  return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}
// Normaliza nombres a Title Case (corrige entradas en MAYÚSCULA que rompen la estética).
// Respeta partículas (de, del, la, los, y…), siglas cortas (JD) y apellidos con apóstrofo/guion.
const CAP_MINUS = new Set(['de', 'del', 'la', 'las', 'los', 'y', 'e', 'da', 'do', 'dos', 'van', 'von']);
function capName(s) {
  const str = String(s == null ? '' : s).trim().replace(/\s+/g, ' ');
  if (!str) return '';
  return str.toLowerCase().split(' ').map((w, i) => {
    if (i > 0 && CAP_MINUS.has(w)) return w;
    return w.replace(/[a-záéíóúñü]+/gi, (seg, off) => off === 0 ? seg.charAt(0).toUpperCase() + seg.slice(1) : seg)
            .replace(/(^|[-'’])([a-záéíóúñü])/gi, (m, sep, ch) => sep + ch.toUpperCase());
  }).join(' ');
}
// Variante para escritura en vivo (onChange): solo cambia mayúsculas/minúsculas, PRESERVA los espacios
// tal cual (no hace trim ni colapsa), para no borrar el espacio recién tecleado ni mover el cursor.
function capNameLive(s) {
  var seen = false;
  return String(s == null ? '' : s).replace(/\S+/g, function (w) {
    var first = !seen; seen = true;
    var lw = w.toLowerCase();
    if (!first && CAP_MINUS.has(lw)) return lw;
    return lw.replace(/[a-záéíóúñü]+/gi, function (seg, off) { return off === 0 ? seg.charAt(0).toUpperCase() + seg.slice(1) : seg; })
             .replace(/(^|[-'’])([a-záéíóúñü])/gi, function (m, sep, ch) { return sep + ch.toUpperCase(); });
  });
}
function userInitials() {return deriveInitials(userName());}
function usePerfilName() {
  const [n, setN] = React.useState(userName);
  React.useEffect(() => {
    const h = () => setN(userName());
    window.addEventListener('rodando-perfil', h);
    window.addEventListener('storage', h);
    return () => {window.removeEventListener('rodando-perfil', h);window.removeEventListener('storage', h);};
  }, []);
  return n;
}

// Contador de notificaciones pendientes para la campana del encabezado.
// Reactivo a cambios; usa el rol actual global.
function useHeaderNotif() {
  const [n, setN] = React.useState(0);
  React.useEffect(() => {
    const calc = () => {
      try {
        const role = window.__role || 'mensajero';
        setN(window.unreadCountFor ? window.unreadCountFor(role) : 0);
      } catch (e) {setN(0);}
    };
    calc();
    window.addEventListener('rodando-notifs', calc);
    window.addEventListener('storage', calc);
    window.addEventListener('focus', calc);
    return () => {
      window.removeEventListener('rodando-notifs', calc);
      window.removeEventListener('storage', calc);
      window.removeEventListener('focus', calc);
    };
  }, []);
  return n;
}
function pickAvatarFile() {
  // Si el recortador está disponible, abrirlo (elegir → encuadrar → guardar).
  if (window.pickAvatarFileToCrop) {window.pickAvatarFileToCrop();return;}
  const inp = document.createElement('input');
  inp.type = 'file';inp.accept = 'image/*';
  inp.onchange = () => {
    const f = inp.files && inp.files[0];
    if (!f) return;
    const r = new FileReader();
    r.onload = () => saveAvatar(r.result);
    r.readAsDataURL(f);
  };
  inp.click();
}
function ProfileAvatar({ size = 32, editable = false, onClick, initials, ring = false, forceInitials = false }) {
  const photo = useAvatar();
  const perfilName = usePerfilName();
  const ini = deriveInitials(perfilName);
  const showPhoto = photo && !forceInitials;
  const [menu, setMenu] = React.useState(false);
  const handle = (e) => {
    if (editable) {
      e.stopPropagation();
      if (photo) setMenu((m) => !m); // ya hay foto → menú; si no, elegir directo
      else pickAvatarFile();
    } else
    if (onClick) onClick(e);
  };
  const closeMenu = () => setMenu(false);
  return (
    <button onClick={handle} aria-label={editable ? 'Cambiar foto de perfil' : 'Perfil'} style={{
      position: 'relative', width: size, height: size, padding: 0,
      border: 'none', cursor: 'pointer', background: 'transparent', flexShrink: 0,
      fontFamily: 'inherit'
    }}>
      <div style={{
        width: size, height: size, borderRadius: 999, overflow: 'hidden',
        background: editable ? TOKENS.primaryBg : TOKENS.primary, color: editable ? TOKENS.primary : '#fff',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: Math.round(size * 0.36), fontWeight: 700,
        boxShadow: ring ? `0 0 0 3px ${TOKENS.bg}, 0 0 0 4px ${TOKENS.border}` : 'none'
      }}>
        {showPhoto ?
        <img src={photo} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} /> :
        <span>{ini}</span>}
      </div>
      {editable &&
      <span style={{
        position: 'absolute', right: -2, bottom: -2,
        width: Math.round(size * 0.42), height: Math.round(size * 0.42),
        borderRadius: 999, background: '#fff', border: `1px solid ${TOKENS.border}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: '0 1px 3px rgba(11,28,48,0.18)'
      }}>{I.cam(Math.round(size * 0.24), TOKENS.primary)}</span>
      }
      {editable && menu &&
      <React.Fragment>
        <span onClick={(e) => {e.stopPropagation();closeMenu();}} style={{ position: 'fixed', inset: 0, zIndex: 40 }} />
        <div onClick={(e) => e.stopPropagation()} style={{
          position: 'absolute', top: size + 8, left: 0, zIndex: 41, minWidth: 188,
          background: '#fff', borderRadius: 12, border: `1px solid ${TOKENS.border}`,
          boxShadow: '0 12px 32px rgba(11,28,48,0.22)', overflow: 'hidden', textAlign: 'left'
        }}>
          <AvatarMenuItem icon={I.cam(16, TOKENS.text)} label="Reemplazar foto"
          onClick={() => {closeMenu();pickAvatarFile();}} />
          <AvatarMenuItem icon={I.crop ? I.crop(16, TOKENS.text) : I.cam(16, TOKENS.text)} label="Reencuadrar"
          onClick={() => {closeMenu();window.reencuadrarAvatar && window.reencuadrarAvatar();}} />
          <AvatarMenuItem icon={I.trash ? I.trash(16, TOKENS.danger) : I.x(16, TOKENS.danger)} label="Quitar foto" danger
          onClick={() => {closeMenu();window.removeAvatar ? window.removeAvatar() : saveAvatar('');}} last />
        </div>
      </React.Fragment>
      }
    </button>);
}

function AvatarMenuItem({ icon, label, onClick, danger, last }) {
  return (
    <button onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 10, width: '100%', padding: '11px 13px',
      background: 'transparent', border: 'none', borderBottom: last ? 'none' : `1px solid ${TOKENS.border}`,
      cursor: 'pointer', fontFamily: 'inherit', fontSize: 13.5, fontWeight: 600,
      color: danger ? TOKENS.danger : TOKENS.text, textAlign: 'left'
    }}>
      <span style={{ display: 'flex', flexShrink: 0 }}>{icon}</span>{label}
    </button>);
}

function RutaEnCursoPill({ hidden }) {
  const [info, setInfo] = React.useState(() => window.getRutaEnCurso ? window.getRutaEnCurso() : null);
  React.useEffect(() => {
    const id = setInterval(() => setInfo(window.getRutaEnCurso ? window.getRutaEnCurso() : null), 1000);
    return () => clearInterval(id);
  }, []);
  if (hidden || !info) return null;
  const secs = info.iniciadaEn ? Math.max(0, Math.floor((Date.now() - info.iniciadaEn) / 1000)) : 0;
  const pad = (n) => String(n).padStart(2, '0');
  const txt = `${pad(Math.floor(secs / 60))}:${pad(secs % 60)}`;
  return (
    <button onClick={() => window.__goToRutas && window.__goToRutas()} title={`Ruta en curso · ${info.taller}`} style={{
      display: 'inline-flex', alignItems: 'center', gap: 6, flexShrink: 0,
      background: TOKENS.cautionBg, border: `1px solid ${TOKENS.caution}`, borderRadius: 999,
      padding: '4px 10px', cursor: 'pointer', fontFamily: 'inherit', color: TOKENS.cautionText,
      fontWeight: 800, fontSize: 11, maxWidth: 150
    }}>
      <span style={{ width: 7, height: 7, borderRadius: 999, background: TOKENS.caution, animation: 'rdBlink 1.4s infinite', flexShrink: 0 }} />
      <span style={{ fontFamily: 'monospace' }}>{txt}</span>
      {(typeof window === 'undefined' || window.innerWidth >= 380) &&
      <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{info.taller}</span>}
    </button>);

}

// ── Mis notas en la barra de arriba (11/11/2026) ─────────────────────────
// Ícono de libreta al lado de la campana, en todas las pantallas. Número azul
// con las notas sin marcar (el rojo queda solo para notificaciones). Al tocarlo
// se abre un panel desde abajo con Mis notas.
function useNotasPendientes() {
  const leer = () => (typeof loadChecklist === 'function' ? loadChecklist() : []).filter((x) => !x.done).length + (window.encargosPendientesDe ? window.encargosPendientesDe(((window.usuarioActual && window.usuarioActual()) || {}).usuario).length : 0);
  const [n, setN] = React.useState(leer);
  React.useEffect(() => {
    const f = () => setN(leer());
    window.addEventListener('rodando-notas', f);
    window.addEventListener('storage', f);
    return () => { window.removeEventListener('rodando-notas', f); window.removeEventListener('storage', f); };
  }, []);
  return n;
}
const iconoLibreta = (s = 22, c = 'currentColor') =>
<svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round">
    <rect x="5" y="3.5" width="14" height="17" rx="2.2" />
    <path d="M9 8.5h6M9 12h6M9 15.5h3.5" />
  </svg>;

function NotasPanel({ onClose }) {
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(11,28,48,0.45)', zIndex: 1000, display: 'flex', alignItems: 'flex-end', justifyContent: 'center' }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: TOKENS.bg, borderRadius: '18px 18px 0 0', width: '100%', maxWidth: 440, padding: '12px 16px 22px', maxHeight: '80vh', overflow: 'auto' }}>
        <div style={{ width: 36, height: 4, borderRadius: 2, background: TOKENS.border, margin: '0 auto 12px' }} />
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
          <div style={{ fontSize: 18, fontWeight: 800, color: TOKENS.text }}>Tareas</div>
          <button onClick={onClose} aria-label="Cerrar" style={{ background: 'transparent', border: 'none', cursor: 'pointer', padding: 4, display: 'flex' }}>{I.x(20, TOKENS.textMuted)}</button>
        </div>
        {window.EncargosYNotas ? <window.EncargosYNotas /> : window.MisNotas ? <window.MisNotas /> : null}
      </div>
    </div>);
}

function NotasBoton() {
  const n = useNotasPendientes();
  const [open, setOpen] = React.useState(false);
  return (
    <React.Fragment>
      <button onClick={() => setOpen(true)} aria-label="Tareas y notas" style={{
        position: 'relative', background: 'transparent', border: 'none', cursor: 'pointer',
        padding: 6, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0
      }}>
        {iconoLibreta(22, TOKENS.text)}
        {n > 0 &&
        <span style={{
          position: 'absolute', top: -2, right: -2, minWidth: 17, height: 17,
          borderRadius: 999, background: TOKENS.primary, color: '#fff',
          fontSize: 10, fontWeight: 800, lineHeight: '17px', textAlign: 'center',
          border: `2px solid ${TOKENS.bg}`, boxSizing: 'content-box', padding: '0px 4px'
        }}>{n}</span>}
      </button>
      {open && ReactDOM.createPortal(<NotasPanel onClose={() => setOpen(false)} />, document.body)}
    </React.Fragment>);
}

// 27/11/2026: pendientes del admin → globito sobre el círculo del usuario y lista en Mi perfil.
//   nov = rines esperando autorización · anu = solicitudes de anulación · cor = correcciones pedidas
//   rev = talleres/sedes por revisar en Catálogos · rec = recogidas pedidas por los talleres que aún no se hacen
function adminPendientes() {
  const o = { nov: 0, anu: 0, cor: 0, rev: 0, rec: 0, total: 0 };
  const u = window.usuarioActual ? window.usuarioActual() : null;
  if (!u || u.rol !== 'admin') return o;
  try { const regs = window.pcRegistros ? window.pcRegistros() : []; o.nov = typeof servPendientes === 'function' ? servPendientes(regs).length : 0; } catch (e) {}
  try { o.anu = (window.loadSolicitudesAnulacion ? window.loadSolicitudesAnulacion() : []).filter((x) => x.estado === 'espera').length; } catch (e) {}
  try { o.cor = (window.loadCorrecciones ? window.loadCorrecciones() : []).filter((x) => x.estado === 'espera').length; } catch (e) {}
  try { o.rev = window.loadCatalogo ? (window.loadCatalogo().revisar || []).length : 0; } catch (e) {}
  try { const lp = typeof loadParadas === 'function' ? loadParadas : window.loadParadas; o.rec = (lp ? lp() : []).filter((p) => p.creadaPor === 'taller' && p.tipo === 'recoger' && (p.estado === 'solicitud' || p.estado === 'pendiente')).length; } catch (e) {}
  o.total = o.nov + o.anu + o.cor + o.rev + o.rec;
  return o;
}
function useAdminPendientes() {
  const [o, setO] = React.useState(adminPendientes);
  React.useEffect(() => {
    const h = () => setO(adminPendientes());
    const ev = ['rodando-servicios', 'rodando-anulaciones', 'rodando-catalogo', 'rodando-paradas', 'rodando-encargos', 'rodando-notifs', 'rodando-perfil', 'storage'];
    ev.forEach((e) => window.addEventListener(e, h));
    const t = setInterval(h, 20000);
    return () => { ev.forEach((e) => window.removeEventListener(e, h)); clearInterval(t); };
  }, []);
  return o;
}
function GlobitoPendientes({ n, style }) {
  if (!n) return null;
  return <span aria-label={`${n} pendientes`} style={{ position: 'absolute', top: -7, left: 20, minWidth: 18, height: 18, padding: '0 5px', borderRadius: 999, background: TOKENS.danger, color: '#fff', fontSize: 10.5, fontWeight: 800, lineHeight: '18px', textAlign: 'center', boxShadow: `0 0 0 2px ${TOKENS.bg}`, boxSizing: 'border-box', pointerEvents: 'none', ...style }}>{n > 99 ? '99+' : n}</span>;
}

function AppHeader({ title = 'Rodando', onBack, right, notif = 0, onBell, onAvatar, avatar = false, bell = true, hideRuta = false, notas = true }) {
  const autoNotif = useHeaderNotif();
  const badge = notif || autoNotif;
  const pend = useAdminPendientes();
  const bellClick = onBell || (() => window.__goToNotifs && window.__goToNotifs());
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 8,
      padding: '14px 16px 12px', background: TOKENS.bg,
      borderBottom: `1px solid ${TOKENS.border}`,
      position: 'sticky', top: 0, zIndex: 20
    }}>
      {onBack ?
      <button onClick={onBack} style={{
        background: 'transparent', border: 'none', padding: 4, cursor: 'pointer',
        color: TOKENS.primary, display: 'flex'
      }}>{I.back(22, TOKENS.primary)}</button> : null
      }
      {avatar &&
      <span style={{ position: 'relative', display: 'inline-flex', flexShrink: 0 }}><ProfileAvatar size={32} onClick={onAvatar} /><GlobitoPendientes n={pend.total} /></span>
      }
      <div style={{
        flex: 1, minWidth: 0, fontWeight: 700, fontSize: 18, color: TOKENS.primary,
        letterSpacing: '-0.01em', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'
      }}>{title}</div>
      <RutaEnCursoPill hidden={hideRuta || title === 'Rutas del día' || window.__role === 'admin'} />
      {notas && !window.rdPanelPC && <NotasBoton />}
      {bell && !window.rdPanelPC &&
      <button onClick={bellClick} style={{
        position: 'relative', background: 'transparent', border: 'none', cursor: 'pointer',
        padding: 6, marginRight: 2, display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0
      }}>
            {I.bell(22, TOKENS.text)}
            {badge > 0 &&
        <span style={{
          position: 'absolute', top: -2, right: -2, minWidth: 17, height: 17,
          borderRadius: 999, background: TOKENS.danger, color: '#fff',
          fontSize: 10, fontWeight: 800, lineHeight: '17px', textAlign: 'center',
          border: `2px solid ${TOKENS.bg}`, boxSizing: 'content-box', padding: "0px 4px"
        }}>{badge}</span>
        }
          </button>
      }
      {right}
    </div>);

}

const iconBtnStyle = {
  background: 'transparent', border: 'none', padding: 6, cursor: 'pointer',
  color: TOKENS.text, display: 'flex'
};

function BottomNav({ current, onNav }) {
  if (window.rdPanelPC) return null; // dentro del panel del PC manda el menú lateral
  const items = [
  { id: 'dashboard', label: 'Inicio', icon: I.home },
  { id: 'recoger', label: 'Recoger', icon: I.recoger },
  { id: 'entregar', label: 'Entregar', icon: I.truck },
  { id: 'consultar', label: 'Consultar', icon: I.consultar },
  { id: 'rutas', label: 'Rutas', icon: I.pin }];

  return (
    <div style={{
      display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)',
      borderTop: `1px solid ${TOKENS.border}`, background: TOKENS.bg,
      padding: '6px 2px 8px', flexShrink: 0,
      position: 'sticky', bottom: 0, zIndex: 20
    }}>
      {items.map((it) => {
        const active = it.id === current;
        return (
          <button key={it.id} onClick={() => onNav && onNav(it.id)} style={{
            background: 'transparent', border: 'none', cursor: 'pointer',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
            padding: '4px 0', color: active ? TOKENS.primary : TOKENS.textMuted
          }}>
            <div style={{
              background: active ? TOKENS.primary : 'transparent',
              color: active ? '#fff' : TOKENS.textMuted,
              padding: '6px 14px', borderRadius: 999
            }}>{it.icon(18, active ? '#fff' : TOKENS.textMuted)}</div>
            <div style={{ fontSize: 11, fontWeight: active ? 600 : 500 }}>{it.label}</div>
          </button>);

      })}
    </div>);

}

// Label + form controls ──────────────────────────────────────────────────
function FieldLabel({ children, upper = false }) {
  return <div style={{
    fontSize: upper ? 11 : 13, fontWeight: 600,
    color: upper ? TOKENS.textMuted : TOKENS.text,
    letterSpacing: upper ? '0.06em' : '0',
    textTransform: upper ? 'uppercase' : 'none',
    marginBottom: 6
  }}>{children}</div>;
}

// alias/footer (13/11/2026): una opción puede traer alias (también busca por ahí y muestra "llega como …");
// footer(query, cerrar) agrega una acción al final de la lista (ej. "¿No está? Escribir otro taller").
function Select({ value, onChange, options, placeholder, disabled = false, searchable = false, footer, popWidth, error = false }) {
  const [open, setOpen] = React.useState(false);
  const [query, setQuery] = React.useState('');
  const ref = React.useRef(null);
  const searchRef = React.useRef(null);
  // Buscador automático: aparece con 7+ opciones (canónico de la app), o si se fuerza con `searchable`.
  const showSearch = searchable || (Array.isArray(options) && options.length >= 7);
  React.useEffect(() => {
    if (!open) return;
    const handler = (e) => {if (ref.current && !ref.current.contains(e.target)) setOpen(false);};
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [open]);
  React.useEffect(() => {
    if (open && showSearch && searchRef.current) {
      searchRef.current.focus();
    }
    if (!open) setQuery('');
  }, [open, showSearch]);

  const norm = options.map((o) => ({
    value: o.value !== undefined ? o.value : o,
    label: o.label !== undefined ? o.label : o,
    alias: o.alias || []
  }));
  const current = norm.find((o) => o.value === value);
  const q = query.trim().toLowerCase();
  const sinTilde = (x) => String(x).normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase();
  const qq = sinTilde(q);
  const filtered = q ?
  norm.map((o) => sinTilde(o.label).includes(qq) ? o : (() => {const al = o.alias.find((a) => sinTilde(a).includes(qq));return al ? { ...o, via: al } : null;})()).filter(Boolean) :
  norm;

  // Auto-scale font + row padding by option count for readability
  const count = norm.length;
  const fontSize = count <= 5 ? 14 : count <= 8 ? 13 : count <= 12 ? 12 : 11;
  const rowPadY = count <= 5 ? 10 : count <= 8 ? 8 : 7;
  const rowPadX = 12;

  const triggerStyle = {
    width: '100%', boxSizing: 'border-box',
    appearance: 'none', WebkitAppearance: 'none',
    border: `1px solid ${error ? TOKENS.danger : TOKENS.borderInput}`,
    background: disabled ? TOKENS.surfaceContainer : error ? '#fdf3f1' : TOKENS.surfaceLow,
    boxShadow: error ? '0 0 0 3px rgba(192,88,79,.12)' : 'none',
    borderRadius: 10, padding: '12px 36px 12px 14px',
    fontSize: 14, color: disabled ? TOKENS.textSubtle : TOKENS.text,
    fontWeight: 500, fontFamily: 'inherit',
    outline: 'none', textAlign: 'left',
    cursor: disabled ? 'not-allowed' : 'pointer',
    display: 'flex', alignItems: 'center', justifyContent: 'space-between'
  };

  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button
        type="button"
        disabled={disabled}
        onClick={() => !disabled && setOpen((o) => !o)}
        style={triggerStyle}>
        
        <span style={{
          color: current ? TOKENS.text : TOKENS.textSubtle,
          fontWeight: current ? 600 : 500,
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap'
        }}>
          {current ? current.label : placeholder || 'Seleccionar'}
        </span>
      </button>
      <div style={{
        position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)',
        pointerEvents: 'none', color: TOKENS.textMuted
      }}>{I.chev(16, TOKENS.textMuted)}</div>

      {open && !disabled &&
      <div style={{
        position: 'absolute', top: 'calc(100% + 6px)', left: 0, right: popWidth ? 'auto' : 0, width: popWidth || 'auto', zIndex: 50,
        background: TOKENS.surface,
        border: `1px solid ${TOKENS.border}`, borderRadius: 12,
        padding: 6, boxShadow: '0 12px 28px rgba(11,28,48,0.16)',
        maxHeight: 320, overflow: 'hidden',
        display: 'flex', flexDirection: 'column'
      }}>
          {showSearch &&
        <div style={{ padding: '4px 4px 6px', borderBottom: `1px solid ${TOKENS.border}`, marginBottom: 4 }}>
              <div style={{ position: 'relative' }}>
                <div style={{
              position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)',
              color: TOKENS.textMuted, pointerEvents: 'none', display: 'flex'
            }}>{I.consultar(14, TOKENS.textMuted)}</div>
                <input
              ref={searchRef}
              type="text"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder="Buscar…"
              style={{
                width: '100%', boxSizing: 'border-box',
                border: `1px solid ${TOKENS.borderInput}`,
                background: TOKENS.surfaceLow,
                borderRadius: 8, padding: '8px 10px 8px 32px',
                fontSize: 13, color: TOKENS.text,
                fontFamily: 'inherit', outline: 'none'
              }} />
            
                {query &&
            <button type="button" onClick={() => {setQuery('');searchRef.current && searchRef.current.focus();}}
            style={{
              position: 'absolute', right: 6, top: '50%', transform: 'translateY(-50%)',
              background: 'transparent', border: 'none', padding: 4, cursor: 'pointer',
              display: 'flex', color: TOKENS.textMuted
            }} aria-label="Limpiar búsqueda">
                    {I.x(14, TOKENS.textMuted)}
                  </button>
            }
              </div>
            </div>
        }
          <div style={{
          display: 'flex', flexDirection: 'column', gap: 2,
          overflowY: 'auto', flex: 1, minHeight: 0
        }}>
            {filtered.length === 0 &&
          <div style={{
            padding: '14px 12px', textAlign: 'center', color: TOKENS.textMuted,
            fontSize: 13
          }}>Sin resultados</div>
          }
            {filtered.map((o) => {
            const selected = o.value === value;
            return (
              <button
                key={String(o.value)}
                type="button"
                onClick={() => {onChange && onChange(o.value);setOpen(false);}}
                onMouseEnter={(e) => {if (!selected) e.currentTarget.style.background = TOKENS.surfaceLow;}}
                onMouseLeave={(e) => {if (!selected) e.currentTarget.style.background = 'transparent';}}
                style={{
                  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                  width: '100%', padding: `${rowPadY}px ${rowPadX}px`,
                  background: selected ? TOKENS.surfaceLow : 'transparent',
                  color: selected ? TOKENS.primary : TOKENS.text,
                  border: 'none', borderRadius: 8,
                  fontSize, fontWeight: selected ? 700 : 500,
                  cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left',
                  lineHeight: 1.3, flexShrink: 0
                }}>
                
                  <span style={{ overflow: 'hidden', minWidth: 0 }}>
                    <span style={{ display: 'block', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{o.label}</span>
                    {o.via && <span style={{ display: 'block', fontSize: 11, fontWeight: 500, color: TOKENS.textMuted, marginTop: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>llega como {o.via}</span>}
                  </span>
                  {selected && <span style={{ flexShrink: 0, marginLeft: 8, display: 'flex' }}>{I.check(14, TOKENS.primary)}</span>}
                </button>);

          })}
          </div>
          {footer && footer(query, () => setOpen(false))}
        </div>
      }
    </div>);

}

function TextInput({ value, onChange, onBlur, placeholder, upper = false, icon, type = 'text', maxLength, transform, error, style = {} }) {
  const borderColor = error ? TOKENS.danger : TOKENS.borderInput;
  return (
    <div style={{ position: 'relative' }}>
      {icon && <div style={{
        position: 'absolute', left: 12, top: maxLength || error ? 22 : '50%',
        transform: maxLength || error ? 'none' : 'translateY(-50%)',
        color: TOKENS.textMuted, pointerEvents: 'none'
      }}>{icon}</div>}
      <input
        type={type}
        value={value || ''}
        maxLength={maxLength}
        onChange={(e) => {
          if (!onChange) return;
          let v = e.target.value;
          if (transform) v = transform(v);else
          if (upper) v = v.toUpperCase();
          onChange(v);
        }}
        onBlur={onBlur}
        placeholder={placeholder}
        style={{
          width: '100%',
          boxSizing: 'border-box',
          border: `1px solid ${borderColor}`,
          background: error ? TOKENS.dangerBg : TOKENS.surfaceLow,
          borderRadius: 10, padding: icon ? '12px 14px 12px 38px' : '12px 14px',
          fontSize: 14, color: TOKENS.text, fontWeight: upper ? 700 : 500,
          letterSpacing: upper ? '0.05em' : '0',
          fontFamily: 'inherit', outline: 'none',
          ...style
        }} />
      
      {error &&
      <div style={{
        fontSize: 11, color: TOKENS.danger, marginTop: 6, fontWeight: 600,
        display: 'flex', alignItems: 'center', gap: 5
      }}>
          <span style={{
          display: 'inline-flex', width: 14, height: 14, borderRadius: 999,
          background: TOKENS.danger, color: '#fff', alignItems: 'center', justifyContent: 'center',
          fontSize: 10, fontWeight: 700
        }}>!</span>
          {error}
        </div>
      }
    </div>);

}

function Stepper({ value, onChange, min = 1, max = 99 }) {
  const set = (v) => onChange && onChange(Math.max(min, Math.min(max, v)));
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      border: `1px solid ${TOKENS.borderInput}`, background: TOKENS.surfaceLow,
      borderRadius: 10, padding: '4px 4px'
    }}>
      <button onClick={() => set(value - 1)} style={{
        background: 'transparent', border: 'none', cursor: 'pointer',
        width: 34, height: 34, display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: TOKENS.primary, borderRadius: 8
      }}>{I.minus(18, TOKENS.primary)}</button>
      <div style={{
        flex: 1, textAlign: 'center', fontSize: 15, fontWeight: 700, color: TOKENS.text
      }}>{value}</div>
      <button onClick={() => set(value + 1)} style={{
        background: 'transparent', border: 'none', cursor: 'pointer',
        width: 34, height: 34, display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: TOKENS.primary, borderRadius: 8
      }}>{I.plus(18, TOKENS.primary)}</button>
    </div>);

}

function Toggle({ value, onChange }) {
  return (
    <button onClick={() => onChange && onChange(!value)} style={{
      width: 46, height: 26, borderRadius: 999,
      background: value ? TOKENS.primary : TOKENS.borderInput,
      border: 'none', cursor: 'pointer', position: 'relative',
      transition: 'background 0.18s', padding: 0, flexShrink: 0
    }}>
      <div style={{
        position: 'absolute', top: 3, left: value ? 23 : 3,
        width: 20, height: 20, borderRadius: 999, background: '#fff',
        transition: 'left 0.18s', boxShadow: '0 1px 3px rgba(0,0,0,0.2)'
      }} />
    </button>);

}

// Buttons ───────────────────────────────────────────────────────────────
// Selector Directo / Transportadora (18/11/2026): el mismo en el celular y en el PC.
// Tarjeta con ícono, nombre y qué se pide; la elegida con borde azul, fondo suave e ícono relleno.
function ModoEntregaTile({ on, icon, titulo, sub, onClick }) {
  return (
    <button type="button" onClick={onClick} aria-pressed={on} style={{
      display: 'flex', alignItems: 'center', gap: 10, textAlign: 'left', width: '100%', fontFamily: 'inherit', cursor: 'pointer',
      border: on ? `2px solid ${TOKENS.primary}` : `1px solid ${TOKENS.borderInput}`, background: on ? TOKENS.primaryBg : TOKENS.surface,
      borderRadius: 12, padding: on ? 11 : 12, color: TOKENS.text
    }}>
      <span style={{ width: 36, height: 36, borderRadius: 10, flexShrink: 0, display: 'grid', placeItems: 'center', background: on ? TOKENS.primary : TOKENS.surfaceLow }}>{icon(18, on ? '#fff' : TOKENS.primary)}</span>
      <span style={{ minWidth: 0 }}><b style={{ display: 'block', fontSize: 14 }}>{titulo}</b><span style={{ fontSize: 12, color: TOKENS.textMuted }}>{sub}</span></span>
    </button>);
}

const GRIS_DESACTIVADO = { background: '#e9edf3', color: '#9aa4b5', borderColor: '#e9edf3', cursor: 'not-allowed', boxShadow: 'none' };
// Texto bajo un botón desactivado: dice qué falta para poder usarlo.
const MotivoBloqueo = ({ children }) => <div style={{ fontSize: 12, color: TOKENS.textMuted, textAlign: 'center', marginTop: 6, lineHeight: 1.45 }}>{children}</div>;
function Button({ variant = 'primary', children, icon, onClick, full = false, style = {}, disabled = false }) {
  const base = {
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
    padding: '12px 16px', borderRadius: 10, fontSize: 14, fontWeight: 600,
    cursor: 'pointer', fontFamily: 'inherit', border: '1px solid transparent',
    width: full ? '100%' : 'auto', boxSizing: 'border-box',
    letterSpacing: '0.01em'
  };
  const styles = {
    primary: { background: TOKENS.primary, color: '#fff', borderColor: TOKENS.primary },
    dark: { background: TOKENS.navy, color: '#fff', borderColor: TOKENS.navy },
    secondary: { background: TOKENS.surfaceContainer, color: TOKENS.text, borderColor: TOKENS.border },
    outline: { background: TOKENS.surface, color: TOKENS.text, borderColor: TOKENS.borderInput },
    danger: { background: TOKENS.surface, color: TOKENS.danger, borderColor: TOKENS.borderInput, borderWidth: 1.5 },
    ghost: { background: 'transparent', color: TOKENS.primary, borderColor: 'transparent' }
  };
  // Desactivado (18/11/2026): los botones rellenos se ven gris normal (no azul/verde lavado).
  const relleno = variant === 'primary' || variant === 'dark';
  return (
    <button
      onClick={disabled ? undefined : onClick}
      disabled={disabled}
      style={{
        ...base, ...styles[variant], ...style,
        ...(disabled ? relleno ? GRIS_DESACTIVADO : { opacity: 0.45, cursor: 'not-allowed' } : {})
      }}>
      {disabled && relleno && icon ? <span style={{ display: 'inline-flex', filter: 'brightness(0.62)' }}>{icon}</span> : icon}{children}
    </button>);

}

// ── Reset de scroll al cambiar de pantalla ──────────────────────────────
// Las pantallas se intercambian dentro de un contenedor que conserva su
// posición de scroll; esto lo lleva al inicio en cada navegación.
window.rdScrollTop = function () {
  try {window.scrollTo(0, 0);} catch (e) {}
  try {document.documentElement.scrollTop = 0;document.body.scrollTop = 0;} catch (e) {}
  const pf = document.getElementById('rd-phone-frame');
  if (pf) {
    pf.scrollTop = 0;
    pf.querySelectorAll('*').forEach((el) => {if (el.scrollTop) el.scrollTop = 0;});
  }
};

function Chip({ children, tone = 'neutral' }) {
  const tones = {
    neutral: { bg: TOKENS.primaryBg, fg: TOKENS.primary, border: 'transparent' },
    pendiente: { bg: TOKENS.pendienteBg, fg: TOKENS.pendienteText, border: 'transparent' },
    dark: { bg: TOKENS.navy, fg: '#fff', border: 'transparent' },
    danger: { bg: TOKENS.dangerBg, fg: TOKENS.dangerText, border: 'transparent' },
    warn: { bg: TOKENS.warningBg, fg: TOKENS.warningText, border: 'transparent' },
    success: { bg: TOKENS.successBg, fg: TOKENS.successText, border: 'transparent' },
    anulado: { bg: TOKENS.anuladoBg, fg: TOKENS.anuladoText, border: 'transparent' },
    muted: { bg: TOKENS.surfaceContainer, fg: TOKENS.textMuted, border: 'transparent' },
    outline: { bg: 'transparent', fg: TOKENS.text, border: TOKENS.border }
  };
  const t = tones[tone];
  return <span style={{
    display: 'inline-flex', alignItems: 'center', padding: '4px 10px',
    background: t.bg, color: t.fg, fontSize: 11, fontWeight: 600,
    borderRadius: 999, letterSpacing: '0.06em', textTransform: 'uppercase',
    border: `1px solid ${t.border}`
  }}>{children}</span>;
}

// ── Severidad (SLA) para listas Consultas/Entregar ──────────────────────
// Estilo PROPIO de las tarjetas, independiente del widget de Inicio
// (SEVERITY_META). Se muestra en dos piezas: palabra (SeverityTag) + días.
const SEV_STYLE = {
  aldia: { label: 'Al día', get color() {return TOKENS.success;}, get soft() {return TOKENS.successBg;}, get text() {return TOKENS.successText;} },
  atrasado: { label: 'Atrasado', get color() {return TOKENS.warning;}, get soft() {return TOKENS.warningBg;}, get text() {return TOKENS.warningText;} },
  critico: { label: 'Crítico', get color() {return TOKENS.danger;}, get soft() {return TOKENS.dangerBg;}, get text() {return TOKENS.dangerText;} }
};
function SeverityTag({ level }) {
  const s = SEV_STYLE[level];
  if (!s) return null;
  return <div style={{
    display: 'inline-flex', alignItems: 'center', gap: 5,
    fontSize: 10.5, fontWeight: 800, letterSpacing: '0.04em', textTransform: 'uppercase',
    color: s.text, background: s.soft, padding: '3px 9px', borderRadius: 999, whiteSpace: 'nowrap'
  }}>
    <span style={{ width: 6, height: 6, borderRadius: 999, background: s.color }} />
    {s.label}
  </div>;
}
function DaysCount({ dias, level }) {
  const s = SEV_STYLE[level] || {};
  const txt = dias === 0 ? 'Hoy' : `${dias} ${dias === 1 ? 'día' : 'días'}`;
  return <div style={{
    display: 'inline-flex', alignItems: 'center',
    padding: '4px 11px', background: s.soft || TOKENS.surfaceLow,
    border: '1px solid transparent', borderRadius: 999,
    fontWeight: 800, letterSpacing: '0.04em', textTransform: 'uppercase',
    color: s.text || TOKENS.text, whiteSpace: 'nowrap', fontSize: "11px"
  }}>{txt}</div>;
}

function PhotoSlot({ n, filled = false, dashed = true, onClick }) {
  return (
    <button onClick={onClick} style={{
      flex: 1, aspectRatio: '1', minHeight: 64,
      background: filled ? TOKENS.surfaceHigh : TOKENS.surfaceLow,
      border: `${dashed ? '1.5px dashed' : '1px solid'} ${filled ? TOKENS.primary : TOKENS.borderInput}`,
      borderRadius: 12, display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center', gap: 2, cursor: 'pointer',
      color: filled ? TOKENS.primary : TOKENS.textMuted, padding: 0
    }}>
      {I.cam(22, filled ? TOKENS.primary : TOKENS.textMuted)}
      <div style={{ fontSize: 11, fontWeight: 600 }}>{n}</div>
    </button>);

}

// Card container ────────────────────────────────────────────────────────
function Card({ children, style = {}, padding = 16, forwardedRef }) {
  return <div ref={forwardedRef} style={{
    background: TOKENS.surface, border: `1px solid ${TOKENS.border}`,
    borderRadius: 14, padding, ...style
  }}>{children}</div>;
}

// Date helpers (sync with device) ───────────────────────────────────────
const MESES_CORTOS = ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'];
function fechaDDMMYYYY(d = new Date()) {
  const dd = String(d.getDate()).padStart(2, '0');
  const mm = String(d.getMonth() + 1).padStart(2, '0');
  return `${dd} / ${mm} / ${d.getFullYear()}`;
}
function fechaCorta(d = new Date()) {
  return `${d.getDate()} ${MESES_CORTOS[d.getMonth()]} ${d.getFullYear()}`;
}
function fechaHoraCorta(d = new Date()) {
  const hh = String(d.getHours()).padStart(2, '0');
  const mi = String(d.getMinutes()).padStart(2, '0');
  return `${fechaCorta(d)} · ${formatHora12(`${hh}:${mi}`)}`;
}

// Placa / VIN sanitization + validation (Colombia) ─────────────────────
function sanitizeAlnum(s) {
  // Uppercase, strip everything that's not A-Z or 0-9 (also strips Ñ, spaces, dashes)
  return String(s || '').toUpperCase().replace(/[^A-Z0-9]/g, '');
}
const PLACA_PATTERNS = [
/^[A-Z]{3}[0-9]{3}$/, // Particular/público/oficial: ABC123
/^[A-Z]{3}[0-9]{2}[A-Z]$/, // Moto: XYZ99A
/^[A-Z][0-9]{4}$/, // Maquinaria especial: A1234
/^[A-Z][0-9]{5}$/ // Remolque/semirremolque: R12345
];
function isPlacaValida(p) {
  const s = sanitizeAlnum(p);
  return PLACA_PATTERNS.some((rx) => rx.test(s));
}
function isVinValido(v) {
  // Cualquier longitud > 0, alfanumérico (Ñ ya removida por sanitize)
  return sanitizeAlnum(v).length > 0;
}
const PLACA_ERROR_MSG = 'El formato de la placa no es válido en Colombia.';

// ─── Llanta breakdown: "valor común + excepciones por cantidad" ──────────
// Returns an array of { count, value } groups for a given field ('dot' or
// 'calidad'), combining the default value (applied to the remainder) with
// any per-quantity exceptions. Used by every summary/ficha view so the
// display logic lives in one place.
function llantaBreakdown(item, field) {
  const total = Math.max(1, Number(item.cantidad) || 1);
  const exKey = field === 'dot' ? 'dotExceptions' : 'calidadExceptions';
  const exceptions = Array.isArray(item[exKey]) ? item[exKey] : [];
  const groups = [];
  let used = 0;
  for (const ex of exceptions) {
    const c = Number(ex.count) || 0;
    if (c > 0 && (ex.value || '') !== '') {groups.push({ count: c, value: ex.value });used += c;}
  }
  const remainder = Math.max(0, total - used);
  // Default value covers the remainder; show it first.
  if (remainder > 0 && (item[field] || '') !== '') {
    groups.unshift({ count: remainder, value: item[field] });
  }
  // Funde grupos con el mismo valor (p. ej. una excepción igual al valor común).
  const merged = [];
  for (const g of groups) {
    const hit = merged.find((x) => x.value === g.value);
    if (hit) {hit.count += g.count;} else {merged.push({ ...g });}
  }
  return merged;
}

// Visual: DOT value for a llanta item — single value or grouped "×N" chips.
function LlantaDotValue({ item, align = 'flex-end' }) {
  const groups = llantaBreakdown(item, 'dot');
  if (groups.length <= 1) {
    return <b style={{ fontFamily: 'monospace' }}>{groups[0] && groups[0].value || item.dot || '—'}</b>;
  }
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5, justifyContent: align }}>
      {groups.map((g, i) =>
      <span key={i} style={{
        display: 'inline-flex', alignItems: 'center', gap: 5,
        fontFamily: 'monospace', fontWeight: 700, fontSize: 12,
        background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`,
        borderRadius: 6, padding: '2px 7px', color: TOKENS.text
      }}>
          <span style={{ color: TOKENS.primary, fontWeight: 800 }}>×{g.count}</span>
          {g.value}
        </span>
      )}
    </div>);

}

function calidadTone(c) {
  return c === 'Nueva' ? 'success' : c === 'Usada' ? 'warn' : 'danger';
}

// Visual: Calidad value for a llanta item — single chip or grouped "×N" chips.
function LlantaCalidadValue({ item, align = 'flex-end' }) {
  const groups = llantaBreakdown(item, 'calidad');
  if (groups.length <= 1) {
    const v = groups[0] && groups[0].value || item.calidad;
    return <Chip tone={calidadTone(v)}>{v || '—'}</Chip>;
  }
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, justifyContent: align }}>
      {groups.map((g, i) =>
      <span key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
          <span style={{ fontSize: 12, fontWeight: 800, color: TOKENS.primary, fontFamily: 'monospace' }}>×{g.count}</span>
          <Chip tone={calidadTone(g.value)}>{g.value}</Chip>
        </span>
      )}
    </div>);

}

// ─── PhotoStrip: clickable thumbnails that open the shared lightbox ──────
// Reused across Recoger/Grabar summaries and the Ficha. Reads window.PhotoLightbox
// at render time (defined in screens-entregar, loaded after this file).
function PhotoStrip({ photos, title, size = 52, max }) {
  const list = (Array.isArray(photos) ? photos : []).filter(Boolean);
  const [open, setOpen] = React.useState(null); // index or null
  if (list.length === 0) return null;
  const shown = max ? list.slice(0, max) : list;
  const extra = list.length - shown.length;
  const LB = window.PhotoLightbox;
  return (
    <>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, justifyContent: "flex-start" }}>
        {shown.map((src, i) =>
        <button
          key={i}
          type="button"
          onClick={() => setOpen(i)}
          style={{
            width: size, height: size, borderRadius: 10, padding: 0,
            border: `1px solid ${TOKENS.border}`, background: '#000',
            overflow: 'hidden', flexShrink: 0, cursor: 'pointer',
            position: 'relative', boxShadow: '0 1px 4px rgba(11,28,48,0.14)'
          }}>
            <img src={src} alt={`Foto ${i + 1}`} style={{
            width: '100%', height: '100%', objectFit: 'cover', display: 'block'
          }} />
            {extra > 0 && i === shown.length - 1 &&
          <div style={{
            position: 'absolute', inset: 0, background: 'rgba(8,12,20,0.6)',
            color: '#fff', fontSize: 14, fontWeight: 700,
            display: 'flex', alignItems: 'center', justifyContent: 'center'
          }}>+{extra}</div>
          }
          </button>
        )}
      </div>
      {open != null && LB &&
      <LB
        photos={list}
        index={open}
        onIndex={setOpen}
        onClose={() => setOpen(null)}
        title={title} />

      }
    </>);

}

// ─── PhotoSlider: full-width swipeable carousel (one photo at a time) ────
// Used in the Recoger "Resumen items a recoger" dashboard so the captured
// photos read as a proper slide instead of tiny thumbnails. Tapping the
// zoom button (or the image) opens the shared lightbox.
function PhotoSlider({ photos, title = 'Fotos' }) {
  const list = (Array.isArray(photos) ? photos : []).filter(Boolean);
  const [idx, setIdx] = React.useState(0);
  const [open, setOpen] = React.useState(false);
  const touchRef = React.useRef(null);
  if (list.length === 0) return null;
  const total = list.length;
  const safe = Math.min(idx, total - 1);
  const go = (dir) => setIdx((safe + dir + total) % total);
  const LB = window.PhotoLightbox;

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

  return (
    <div>
      {/* Header: title + counter */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
        <div style={{
          fontSize: 11, fontWeight: 700, color: TOKENS.textMuted,
          letterSpacing: '0.06em', textTransform: 'uppercase',
          display: 'flex', alignItems: 'center', gap: 5
        }}>
          {I.cam(13, TOKENS.textMuted)}
          <span>{title}</span>
        </div>
        <div style={{ fontSize: 12, fontWeight: 700, color: TOKENS.textMuted, fontFamily: 'monospace' }}>
          {safe + 1} <span style={{ opacity: 0.5 }}>/ {total}</span>
        </div>
      </div>

      {/* Stage */}
      <div
        onTouchStart={onTouchStart}
        onTouchEnd={onTouchEnd}
        style={{
          position: 'relative', borderRadius: 14, overflow: 'hidden',
          background: '#000', aspectRatio: '16 / 10',
          border: `1px solid ${TOKENS.border}`
        }}>
        <img
          key={safe}
          src={list[safe]}
          alt={`Foto ${safe + 1}`}
          onClick={() => setOpen(true)}
          style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block', cursor: 'zoom-in' }} />
        

        {/* Zoom button */}
        <button
          type="button"
          onClick={() => setOpen(true)}
          aria-label="Ampliar foto"
          style={{
            position: 'absolute', top: 10, right: 10,
            width: 36, height: 36, borderRadius: 999, padding: 0,
            background: 'rgba(8,12,20,0.55)', border: '1px solid rgba(255,255,255,0.22)',
            color: '#fff', cursor: 'pointer', backdropFilter: 'blur(6px)',
            display: 'flex', alignItems: 'center', justifyContent: 'center'
          }}>
          {I.consultar(17, '#fff')}
        </button>

        {/* Prev / next */}
        {total > 1 &&
        <>
            <button type="button" onClick={() => go(-1)} aria-label="Foto anterior" style={sliderNavBtn('left')}>
              {I.chevLeft(20, '#fff')}
            </button>
            <button type="button" onClick={() => go(1)} aria-label="Foto siguiente" style={sliderNavBtn('right')}>
              {I.chevRight(20, '#fff')}
            </button>
          </>
        }
      </div>

      {/* Segmented progress */}
      {total > 1 &&
      <div style={{ display: 'flex', gap: 6, marginTop: 10 }}>
          {list.map((_, i) =>
        <button
          key={i}
          type="button"
          onClick={() => setIdx(i)}
          aria-label={`Ir a foto ${i + 1}`}
          style={{
            flex: 1, height: 5, borderRadius: 999, padding: 0, cursor: 'pointer',
            background: i === safe ? TOKENS.primary : TOKENS.border,
            border: 'none', transition: 'background 0.18s'
          }} />
        )}
        </div>
      }

      {open && LB &&
      <LB photos={list} index={safe} onIndex={setIdx} onClose={() => setOpen(false)} title={title} />
      }
    </div>);

}

// Downscale + compress a dataURL image so it doesn't blow the localStorage quota.
// Returns a JPEG dataURL (or the original on any failure). Async.
function downscaleDataURL(dataURL, maxDim, quality) {
  maxDim = maxDim || 1100;
  quality = quality || 0.6;
  return new Promise((resolve) => {
    if (!dataURL || typeof dataURL !== 'string') {resolve(dataURL);return;}
    try {
      const img = new Image();
      img.onload = () => {
        const w = img.naturalWidth,h = img.naturalHeight;
        if (!w || !h) {resolve(dataURL);return;}
        const scale = Math.min(1, maxDim / Math.max(w, h));
        const cw = Math.max(1, Math.round(w * scale));
        const ch = Math.max(1, Math.round(h * scale));
        const canvas = document.createElement('canvas');
        canvas.width = cw;canvas.height = ch;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0, cw, ch);
        try {resolve(canvas.toDataURL('image/jpeg', quality));}
        catch (e) {resolve(dataURL);}
      };
      img.onerror = () => resolve(dataURL);
      img.src = dataURL;
    } catch (e) {resolve(dataURL);}
  });
}

// localStorage.setItem that won't throw on quota; returns true/false.
function safeSetItem(key, value) {
  try {localStorage.setItem(key, value);return true;}
  catch (e) {return false;}
}

// "HH:MM" (24h) → "h:MM a. m./p. m." (12h). Passes through empty/invalid.
function formatHora12(hhmm) {
  if (!hhmm || typeof hhmm !== 'string') return hhmm || '';
  const m = hhmm.match(/^(\d{1,2}):(\d{2})/);
  if (!m) return hhmm;
  let h = parseInt(m[1], 10);
  const min = m[2];
  const ap = h >= 12 ? 'p.m.' : 'a.m.';
  h = h % 12;if (h === 0) h = 12;
  return `${h}:${min} ${ap}`;
}

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

// ─── Consecutivo global ascendente (mensajería + recepción, en tiempo real) ───
function svConsecutivoCurrent() {
  var v = parseInt(localStorage.getItem('sv.consecutivo'), 10);
  if (!isFinite(v)) { v = 6850; try { localStorage.setItem('sv.consecutivo', String(v)); } catch (e) {} }
  return v;
}
function peekConsecutivo() { return svConsecutivoCurrent(); }
function reserveConsecutivo() {
  var n = svConsecutivoCurrent();
  try { localStorage.setItem('sv.consecutivo', String(n + 1)); window.dispatchEvent(new Event('sv-consecutivo')); } catch (e) {}
  return n;
}

// ─── Base de clientes (recepción / walk-in) ───
function loadClientes() {
  try {
    var list = JSON.parse(localStorage.getItem('sv.clientes') || 'null');
    if (!Array.isArray(list)) {
      // Base de clientes vacía: walk-in se crea al registrar; sin demo ficticio.
      list = [];
      try { localStorage.setItem('sv.clientes', JSON.stringify(list)); } catch (e) {}
    }
    return cliMigrateNames(list);
  } catch (e) { return []; }
}
// Migración única: normaliza a Title Case nombres de clientes PERSONA ya guardados (no toca empresas).
function cliMigrateNames(list) {
  try {
    if (localStorage.getItem('sv.clientes.capver') === '1' || typeof capName !== 'function') return list;
    var changed = false;
    (list || []).forEach(function (c) {
      if (c && c.tipoCliente !== 'empresa') {
        var nn = capName(c.nombre || ''); var na = capName(c.apellido || '');
        if (nn !== (c.nombre || '')) { c.nombre = nn; changed = true; }
        if (na !== (c.apellido || '')) { c.apellido = na; changed = true; }
      }
    });
    if (changed) localStorage.setItem('sv.clientes', JSON.stringify(list));
    localStorage.setItem('sv.clientes.capver', '1');
  } catch (e) {}
  return list;
}
function saveCliente(c) {
  try {
    // Cuello de botella único: los nombres de PERSONA se guardan siempre en Title Case.
    if (c && c.tipoCliente !== 'empresa' && typeof capName === 'function') {
      c = Object.assign({}, c, { nombre: capName(c.nombre || ''), apellido: capName(c.apellido || '') });
    }
    var list = loadClientes();
    var i = list.findIndex(function (x) { return x.id === c.id; });
    if (i >= 0) {
      var prev = list[i] || {};
      var placas = (prev.placas || []).concat(c.placas || []).map(function (p) { return (p || '').toUpperCase(); }).filter(Boolean);
      placas = placas.filter(function (p, j) { return placas.indexOf(p) === j; });
      list[i] = Object.assign({}, prev, c, { placas: placas });
    } else {
      c.placas = (c.placas || []).map(function (p) { return (p || '').toUpperCase(); }).filter(Boolean);
      list.unshift(c);
    }
    localStorage.setItem('sv.clientes', JSON.stringify(list));
    window.dispatchEvent(new Event('sv-clientes'));
  } catch (e) {}
  return c;
}

// ─── Registros de recepción (walk-in) ───
// Migración única: normaliza a Title Case los nombres de clientes PERSONA ya guardados
// (no toca empresas/aseguradoras, cuyas razones sociales pueden ir en mayúscula).
function recMigrateNames(list) {
  try {
    if (localStorage.getItem('sv.recepcion.capver') === '1' || typeof capName !== 'function') return list;
    var changed = false;
    (list || []).forEach(function (r) {
      if (r && r.cliente && r.origen !== 'externo' && r.cliente.tipoCliente !== 'empresa') {
        var nn = capName(r.cliente.nombre || ''); var na = capName(r.cliente.apellido || '');
        if (nn !== (r.cliente.nombre || '')) { r.cliente.nombre = nn; changed = true; }
        if (na !== (r.cliente.apellido || '')) { r.cliente.apellido = na; changed = true; }
      }
    });
    if (changed) localStorage.setItem('sv.recepcion', JSON.stringify(list));
    localStorage.setItem('sv.recepcion.capver', '1');
  } catch (e) {}
  return list;
}
function loadRecepciones() { try { return recMigrateNames(JSON.parse(localStorage.getItem('sv.recepcion') || '[]')); } catch (e) { return []; } }
function saveRecepcion(reg) {
  try {
    var list = loadRecepciones();
    list.unshift(reg);
    localStorage.setItem('sv.recepcion', JSON.stringify(list));
    window.dispatchEvent(new Event('sv-recepcion'));
  } catch (e) {}
  return reg;
}
// Actualiza una orden existente en sitio (por id). Conserva el orden de la lista.
function updateRecepcion(reg) {
  try {
    var list = loadRecepciones().map(function (r) { return r.id === reg.id ? reg : r; });
    localStorage.setItem('sv.recepcion', JSON.stringify(list));
    window.dispatchEvent(new Event('sv-recepcion'));
  } catch (e) {}
  return reg;
}

// ─── Caja menor (libro diario del día) ───
function loadCajaAll() { try { return JSON.parse(localStorage.getItem('sv.caja') || '{}') || {}; } catch (e) { return {}; } }
function getCajaDia(fecha) { return loadCajaAll()[fecha] || null; }
function saveCajaDia(dia) {
  try { var all = loadCajaAll(); all[dia.fecha] = dia; localStorage.setItem('sv.caja', JSON.stringify(all)); window.dispatchEvent(new Event('sv-caja')); } catch (e) {}
  return dia;
}
function abrirCajaDia(fecha, base) {
  var now = new Date();
  var dia = { fecha: fecha, base: Number(base) || 0, abierta: true, abiertoPor: (typeof userName === 'function' ? userName() : 'Recepción'), abiertoHora: String(now.getHours()).padStart(2, '0') + ':' + String(now.getMinutes()).padStart(2, '0'), movimientos: [], cierre: null };
  return saveCajaDia(dia);
}
// Ingresos automáticos del día: abonos de las órdenes con esa fecha (no se redigitan).
function ingresosAutoDia(fecha) {
  var out = [];
  (typeof loadRecepciones === 'function' ? loadRecepciones() : []).forEach(function (r) {
    (r.abonos || []).forEach(function (a, i) {
      if ((a.fecha || r.fecha) === fecha) {
        out.push({ id: 'ia-' + r.id + '-' + i, origen: 'orden', codigo: r.codigo, cliente: (((r.cliente && r.cliente.nombre) || '') + ' ' + ((r.cliente && r.cliente.apellido) || '')).trim(), concepto: 'Orden ' + r.codigo, monto: Number(a.monto) || 0, metodo: a.metodo || 'Efectivo', hora: r.hora || '', tipo: 'ingreso', auto: true });
      }
    });
  });
  return out;
}
function seedDemoCajaIfEmpty() {
  try {
    if (Object.keys(loadCajaAll()).length > 0) return;
    var f = (typeof fechaDDMMYYYY === 'function') ? fechaDDMMYYYY() : '';
    var dia = { fecha: f, base: 250000, abierta: true, abiertoPor: 'Recepción', abiertoHora: '07:45', cierre: null, movimientos: [
      { id: 'cm1', tipo: 'egreso', categoria: 'Combustible', concepto: 'Combustible mensajero', monto: 40000, metodo: 'Efectivo', hora: '09:30', responsable: 'Mensajero', soporte: { requiere: true, estado: 'pendiente', label: 'Ticket de gasolina' } },
      { id: 'cm2', tipo: 'egreso', categoria: 'Préstamo', concepto: 'Préstamo a Carlos (operario)', monto: 100000, metodo: 'Efectivo', hora: '11:20', responsable: 'Carlos', soporte: { requiere: true, estado: 'pendiente', label: 'Vale firmado' } },
      { id: 'cm3', tipo: 'egreso', categoria: 'Alimentación', concepto: 'Almuerzos equipo', monto: 35000, metodo: 'Efectivo', hora: '12:40', responsable: 'Recepción', soporte: { estado: 'soportado' } },
      { id: 'cm4', tipo: 'egreso', categoria: 'Repuestos', concepto: 'Repuestos menores', monto: 60000, metodo: 'Efectivo', hora: '13:10', responsable: 'Recepción', soporte: { estado: 'soportado' } },
      { id: 'cm5', tipo: 'egreso', categoria: 'Papelería', concepto: 'Papelería', monto: 18000, metodo: 'Efectivo', hora: '13:30', responsable: 'Recepción', soporte: { estado: 'soportado' } },
      { id: 'cm6', tipo: 'ingreso', concepto: 'Venta mostrador · 1 válvula', monto: 20000, metodo: 'Efectivo', hora: '14:15', responsable: 'Recepción', manual: true }
    ] };
    saveCajaDia(dia);
    // Días pasados (cerrados) para el Historial: varios meses, con recurrencias buscables.
    var pastDefs = [
      { f: '02 / 06 / 2026', base: 250000, dif: 0, mov: [['ingreso','','Orden 5310 · Pedro Niño',380000,'Efectivo','08:50'],['egreso','Préstamo','Préstamo a Carlos (operario)',80000,'Efectivo','11:05','pend','Vale firmado'],['egreso','Combustible','Gasolina moto mensajero',35000,'Efectivo','14:20','ok']] },
      { f: '21 / 05 / 2026', base: 300000, dif: -3000, mov: [['ingreso','','Orden 5180 · María Lozano',640000,'Nequi','09:40'],['egreso','Papelería','Resma papel + tóner',62000,'Efectivo','10:10','ok'],['egreso','Alimentación','Almuerzo equipo (5)',45000,'Efectivo','12:30','ok']] },
      { f: '09 / 05 / 2026', base: 250000, dif: 0, mov: [['ingreso','','Orden 5121 · Jorge Vargas',210000,'Efectivo','09:00'],['egreso','Insumos','Insumos de pintura',90000,'Transferencia','11:40','ok'],['egreso','Combustible','Combustible mensajero',38000,'Efectivo','15:00','ok']] },
      { f: '28 / 04 / 2026', base: 250000, dif: 0, mov: [['ingreso','','Orden 5044 · Diego Cardona',295000,'TC/TD','10:20'],['egreso','Préstamo','Préstamo a Carlos (operario)',80000,'Efectivo','13:15','ok'],['egreso','Alimentación','Almuerzos equipo',40000,'Efectivo','12:45','ok']] },
      { f: '10 / 04 / 2026', base: 200000, dif: 5000, mov: [['ingreso','','Orden 4990 · Paola Suárez',150000,'Efectivo','08:30'],['egreso','Transporte','Taxi diligencia banco',18000,'Efectivo','11:00','ok']] },
      { f: '12 / 03 / 2026', base: 250000, dif: -5000, mov: [['ingreso','','Orden 4820 · Andrés Mejía',420000,'Transferencia','09:25'],['egreso','Préstamo','Préstamo a Carlos (operario)',100000,'Efectivo','11:20','ok'],['egreso','Combustible','Combustible mensajero',42000,'Efectivo','09:35','ok'],['egreso','Papelería','Facturas y talonarios',28000,'Efectivo','16:10','ok']] },
      { f: '19 / 02 / 2026', base: 250000, dif: 0, mov: [['ingreso','','Orden 4655 · Liliana Castro',310000,'Efectivo','10:00'],['egreso','Alimentación','Almuerzo equipo',38000,'Efectivo','12:35','ok'],['egreso','Insumos','Lija y disolvente',55000,'Efectivo','14:50','ok']] },
    ];
    pastDefs.forEach(function (pd, di) {
      var movs = pd.mov.map(function (m, i) {
        var mv = { id: 'cmp' + di + '-' + i, tipo: m[0], categoria: m[1], concepto: m[2], monto: m[3], metodo: m[4], hora: m[5], responsable: 'Recepción' };
        if (m[0] === 'ingreso') mv.manual = (m[2].indexOf('Orden') !== 0);
        else mv.soporte = m[6] === 'pend' ? { requiere: true, estado: 'pendiente', label: m[7] || 'Soporte' } : { estado: 'soportado' };
        return mv;
      });
      // saldo esperado solo efectivo
      var ingEf = movs.filter(function(m){return m.tipo==='ingreso' && /efectivo/i.test(m.metodo);}).reduce(function(a,m){return a+m.monto;},0);
      var egEf = movs.filter(function(m){return m.tipo==='egreso' && /efectivo/i.test(m.metodo);}).reduce(function(a,m){return a+m.monto;},0);
      var esperado = pd.base + ingEf - egEf;
      var pdia = { fecha: pd.f, base: pd.base, abierta: false, abiertoPor: 'Recepción', abiertoHora: '07:45', movimientos: movs, cierre: { conteoFisico: esperado + pd.dif, esperado: esperado, diferencia: pd.dif, motivo: pd.dif !== 0 ? (pd.dif < 0 ? 'Vuelto entregado de más' : 'Sobrante sin identificar') : '', cerradoPor: 'Recepción', cerradoHora: '18:20', fecha: pd.f } };
      saveCajaDia(pdia);
    });
  } catch (e) {}
}

// Clave estable de una aseguradora (para agrupar sus órdenes sin depender de la guía).
function asegKey(raw) { return String(raw || '').toUpperCase().replace(/[^A-Z0-9]/g, ''); }

// ─── Migración idempotente del modelo externo (corre en cada carga, no destructiva) ───
// 1) Consecutivos alfanuméricos heredados ("E-118") → numéricos en la misma línea.
// 2) La aseguradora deja de llevar placas y se llavea por su nombre (no por la guía).
// Sólo toca órdenes origen==='externo'; walk-in queda intacto.
function fixExternoModel() {
  try {
    var list = loadRecepciones();
    if (!list || !list.length) return;
    var maxNum = list.reduce(function (m, r) { var n = parseInt(String(r.codigo || '').replace(/\D/g, ''), 10); return (isFinite(n) && n > m) ? n : m; }, 0);
    var nextNum = Math.max(maxNum + 1, 5351);
    var changed = false;
    list.forEach(function (r) {
      if (r.origen !== 'externo') return;
      if (/\D/.test(String(r.codigo || ''))) { r.codigo = String(nextNum++); changed = true; }
      // La guía nace en la ENTREGA (despacho), no en el ingreso: si aún no se entrega, no debe tenerla.
      if (r.estado !== 'entregado' && r.externo && r.externo.guia) { r.externo.guia = ''; changed = true; }
      if (r.cliente && Array.isArray(r.cliente.placas) && r.cliente.placas.length) { r.cliente.placas = []; changed = true; }
      var aseg = (r.externo && r.externo.aseguradora) || (r.cliente && r.cliente.nombre) || '';
      var key = asegKey(aseg);
      if (r.cliente && key && r.cliente.id !== key) { r.cliente.id = key; r.cliente.tipoDoc = 'NIT'; r.cliente.tipoCliente = 'empresa'; changed = true; }
    });
    if (changed) { localStorage.setItem('sv.recepcion', JSON.stringify(list)); window.dispatchEvent(new Event('sv-recepcion')); }
  } catch (e) {}
}

// ─── Demo: órdenes walk-in pendientes de entrega (solo para el boceto) ───
function seedDemoRecepcionesIfEmpty() {
  try {
    if ((loadRecepciones() || []).length > 0) return;
    var hoy = (typeof fechaDDMMYYYY === 'function') ? fechaDDMMYYYY() : '';
    var base = [
      { cod: '5340', placa: 'GHK382', nom: 'Andrés', ape: 'Mejía', doc: '79456123', serv: [['Alineación', 1, 55000], ['Balanceo', 4, 18000]], abonos: [] },
      { cod: '5341', placa: 'JLM044', nom: 'Pedro', ape: 'Niño', doc: '16789234', serv: [['Rectificado de Rines', 4, 90000]], abonos: [[150000, 'Efectivo']] },
      { cod: '5342', placa: 'PTR928', nom: 'Laura', ape: 'Restrepo', doc: '31567890', serv: [['Pintura Electrostática', 4, 120000]], abonos: [[480000 + 91200, 'Transferencia Bancaria']] },
      { cod: '5343', placa: 'BNM114', nom: 'Carlos', ape: 'Gómez', doc: '94123567', serv: [['Vulcanizado de Llantas', 2, 25000]], abonos: [] },
      { cod: '5344', placa: 'WXR556', nom: 'María', ape: 'Lozano', doc: '38901234', serv: [['Maquinado de Rines', 4, 70000], ['Montaje', 4, 12000]], abonos: [[100000, 'Nequi']] },
      { cod: '5345', placa: 'KLT203', nom: 'Jorge', ape: 'Vargas', doc: '14567890', serv: [['Soldadura', 1, 40000]], abonos: [] },
      { cod: '5346', placa: 'DRS781', nom: 'Sandra', ape: 'Patiño', doc: '52678901', serv: [['Rotación', 4, 10000], ['Nitrógeno', 4, 8000]], abonos: [[85680, 'TC/TD']] },
      { cod: '5347', placa: 'FGH092', nom: 'Diego', ape: 'Cardona', doc: '16234890', serv: [['Pintura Líquida', 2, 95000]], abonos: [] },
      { cod: '5348', placa: 'MNB447', nom: 'Paola', ape: 'Suárez', doc: '29345678', serv: [['Extracción de Pernos', 2, 30000]], abonos: [[30000, 'Efectivo']] },
      { cod: '5349', placa: 'QWE318', nom: 'Andrés', ape: 'Ruiz', doc: '80456712', serv: [['Balanceo', 4, 18000]], abonos: [] },
      { cod: '5350', placa: 'ZXC665', nom: 'Liliana', ape: 'Castro', doc: '43789012', serv: [['Alineación', 1, 55000], ['Rotación', 4, 10000]], abonos: [] },
      // ── Externos (aseguradora / taller de otra ciudad) — antes iban en papel ──
      // Consecutivo NUMÉRICO en la misma línea que walk-in (sin prefijo "E-"; el origen lo marca el chip).
      // La guía NO nace aquí: se captura en la entrega (despacho por transportadora).
      { cod: '5351', org: 'externo', aseg: 'Mapfre', taller: 'Automarcali', sede: 'Sur', placa: 'MPF205', serv: [['Pintura Electrostática', 4, 120000], ['Montaje', 4, 12000]], abonos: [] },
      { cod: '5352', org: 'externo', aseg: 'Suramericana', taller: 'Almotores', sede: 'Norte', placa: 'SUR410', serv: [['Rectificado de Rines', 4, 90000]], abonos: [] },
      { cod: '5353', org: 'externo', aseg: 'Bolívar', taller: 'Arautos', sede: 'Norte', placa: 'BLV332', serv: [['Maquinado de Rines', 4, 70000]], abonos: [] },
    ];
    var list = base.map(function (b, i) {
      var esExterno = b.org === 'externo';
      var servicios = b.serv.map(function (s) { return { nombre: s[0], cantidad: s[1], precio: s[2] }; });
      var baseTotal = servicios.reduce(function (a, s) { return a + s.cantidad * s.precio; }, 0);
      var iva = Math.round(baseTotal * 0.19);
      var total = baseTotal + iva;
      var abonos = (b.abonos || []).map(function (a) { return { monto: a[0], metodo: a[1], fecha: hoy }; });
      var anticipo = abonos.reduce(function (a, x) { return a + x.monto; }, 0);
      // Externo: el pagador es la ASEGURADORA (no una persona, no lleva placas — maneja cientos).
      // La placa pertenece a la orden/vehículo (r.placa), no a la aseguradora. Se factura aparte.
      var cliente = esExterno
        ? { id: asegKey(b.aseg), tipoDoc: 'NIT', tipoCliente: 'empresa', nombre: b.aseg, apellido: '', correo: '', direccion: '', celular: '', placas: [] }
        : { id: b.doc, tipoDoc: 'CC', tipoCliente: 'persona', nombre: b.nom, apellido: b.ape, correo: '', direccion: '', celular: '3' + (100000000 + i * 11111111), placas: [b.placa] };
      return { id: 'rec-demo-' + i, codigo: b.cod, docType: 'orden', origen: esExterno ? 'externo' : 'cliente', externo: esExterno ? { aseguradora: b.aseg, taller: b.taller, sede: b.sede, guia: '' } : null, placa: b.placa, fecha: hoy, hora: ['08:12', '08:40', '09:05', '09:33', '10:01', '10:28', '11:14', '11:50', '12:20', '13:05', '13:40', '14:10', '14:35', '15:02'][i] || '09:00', cliente: cliente, recibe: 'Recepción', servicios: servicios, base: baseTotal, iva: iva, total: total, abonos: abonos, anticipo: anticipo, saldo: total - anticipo, observaciones: '', entregaEstimada: '', inspeccion: { deja: false, novedades: '' }, items: [], prestamos: [], estado: 'pendiente' };
    });
    localStorage.setItem('sv.recepcion', JSON.stringify(list));
  } catch (e) {}
}

// ─── Inferencia de acción (cambio / misma / sin repuesto / solo rin) ───
// Derivada y NO se guarda: función pura sobre los items de la orden
// (rines vs llantas + calidades). Sirve igual para órdenes importadas y nuevas.
// La calidad 'Mala' = la llanta no sirve para devolver montada.
function inferAccion(reg) {
  var items = (reg && reg.items) || [];
  var rines = items.filter(function (i) { return i && i.tipo === 'rin'; }).reduce(function (s, i) { return s + (Number(i.cantidad) || 1); }, 0);
  var llItems = items.filter(function (i) { return i && i.tipo === 'llanta'; });
  var llantas = llItems.reduce(function (s, i) { return s + (Number(i.cantidad) || 1); }, 0);
  if (llantas === 0) return { key: 'rin', tone: 'mut', short: 'Solo rin', label: 'Solo rin — se rectifica y se devuelve el rin' };
  var rota = 0;
  llItems.forEach(function (it) {
    var n = Number(it.cantidad) || 1, used = 0, counts = {};
    (it.calidadExceptions || []).forEach(function (e) { counts[e.value] = (counts[e.value] || 0) + (Number(e.count) || 0); used += (Number(e.count) || 0); });
    var base = Math.max(0, n - used); var bk = it.calidad || '?'; counts[bk] = (counts[bk] || 0) + base;
    Object.keys(counts).forEach(function (k) { if (k === 'Mala') rota += counts[k]; });
  });
  var surplus = llantas - rines;
  if (surplus > 0) return { key: 'cambio', tone: 'mount', short: 'Cambio', label: 'Cambio de llanta — montar ' + surplus + ' llanta(s) de cambio al entregar', mount: surplus };
  if (rota > 0) return { key: 'sinrep', tone: 'warn', short: 'Sin repuesto', label: 'Llanta mala y sin repuesto — se devuelve sin montar' };
  return { key: 'misma', tone: 'ok', short: 'Misma', label: 'Se devuelve la misma llanta montada' };
}

// ─── Seed REAL de mensajería · vía handoff PLAYA → RECEPCIÓN ───
// Las órdenes entran como si PLAYA las hubiera recibido y entregado a recepción
// (fuente: 'handoff-playa', viaPlaya: true). Servicios y precio se derivan de cada rin:
//   · Maquinado          → Rectificado + Maquinado + Pintura · $180.000/rin ($150.000 AXA)
//   · Aluminio / Hierro  → Rectificado + Pintura            · $150.000/rin ($130.000 AXA)
// Precio POR RIN (× cantidad). El monto es BASE gravable; el IVA 19% va por encima.
// Siembra UNA VEZ y purga el transaccional ficticio (conserva maestros y catálogo).
function seedMensajeriaReal() {
  try {
    if (localStorage.getItem('sv.menReal.seeded') === '3') return;
    // Purga UNA VEZ del transaccional ficticio (NO toca maestros ni catálogo).
    ['sv.recepcion', 'sv.handoff', 'sv.caja', 'sv.proceso', 'sv.notificaciones', 'sv.notifs', 'sv.paradas', 'sv.entregados', 'rodando.entregados', 'rodando.recogidos', 'sv.clientes'].forEach(function (k) { try { localStorage.removeItem(k); } catch (e) {} });
    try { localStorage.setItem('sv.consecutivo', '6850'); } catch (e) {}
    function mkItem(o) { return Object.assign({ tipo: 'rin', cantidad: 1, tamano: '', material: '', huecos: '', tapa: '', tapaValvula: '', marca: '', referencia: '', dot: '', calidad: '', valvulaSensor: '', sinLlanta: false, dotExceptions: [], calidadExceptions: [], observaciones: '' }, o); }
    // ── Tarifa y servicios por tipo de rin + aseguradora (AXA preferencial) ──
    function rinTipo(material) { var m = String(material || '').toLowerCase(); return (m.indexOf('maquin') >= 0 || m.indexOf('diam') >= 0) ? 'maquinado' : 'aluhierro'; }
    function svcSetFor(tipo) { return tipo === 'maquinado' ? ['Rectificado', 'Maquinado', 'Pintura Electrostática'] : ['Rectificado', 'Pintura Electrostática']; }
    function precioUnit(tipo, aseg) { var axa = /axa/i.test(String(aseg || '')); return tipo === 'maquinado' ? (axa ? 150000 : 180000) : (axa ? 130000 : 150000); }
    function costear(items, aseg) {
      var rines = (items || []).filter(function (it) { return it.tipo === 'rin'; });
      var tipo = rines.length ? rinTipo(rines[0].material) : 'aluhierro';
      var unit = precioUnit(tipo, aseg);
      var qty = rines.reduce(function (s, it) { return s + (Number(it.cantidad) || 1); }, 0) || 1;
      var base = unit * qty;
      // Precio del paquete sobre la línea base (Rectificado); las demás van incluidas (0).
      var servicios = svcSetFor(tipo).map(function (nombre, idx) { return { nombre: nombre, cantidad: qty, precio: idx === 0 ? unit : 0, cortesia: false }; });
      var iva = Math.round(base * 0.19);
      return { servicios: servicios, base: base, iva: iva, total: base + iva };
    }
    var ordenes = [
      { fecha: '11/06/2026', hora: '09:24', placa: 'LGP070', aseg: 'Mapfre', taller: 'Nissan Sameco', sede: 'Norte', items: [
        mkItem({ tipo: 'llanta', cantidad: 4, marca: 'Michelin', referencia: '235/45 R20', dot: 'HCAC 011X 4621', calidad: 'Mala', dotExceptions: [{ count: 1, value: 'HCAC 011X 4821' }, { count: 2, value: '1HC A0 011X 2125' }], calidadExceptions: [{ count: 2, value: 'Usada' }] }),
        mkItem({ tipo: 'rin', cantidad: 2, material: 'Maquinado', huecos: '5H', tapa: 'No', tapaValvula: 'No', tamano: '20' }),
      ] },
      { fecha: '11/06/2026', hora: '11:40', placa: 'ISQ560', aseg: 'HDI Seguros', taller: 'Nissan Sameco', sede: 'Norte', items: [
        mkItem({ tipo: 'llanta', cantidad: 2, marca: 'Maxxis', referencia: '175/60 R15', dot: '12U MBR001 2425', calidad: 'Nueva', dotExceptions: [{ count: 1, value: '2ULA ABC 5114' }], calidadExceptions: [{ count: 1, value: 'Mala' }] }),
        mkItem({ tipo: 'rin', cantidad: 1, material: 'Aluminio', huecos: '4H', tapa: 'No', tapaValvula: 'No', tamano: '15' }),
      ] },
      { fecha: '12/06/2026', hora: '08:50', placa: 'FZN844', aseg: 'HDI Seguros', taller: 'Renovautos', sede: 'Sur', items: [
        mkItem({ tipo: 'llanta', cantidad: 1, marca: 'Goodyear', referencia: '235/55 R18', dot: '1Y13L LB1R 5224', calidad: 'Nueva' }),
        mkItem({ tipo: 'llanta', cantidad: 1, marca: 'Aptany', referencia: '235/50 R18', dot: 'WPX1 1621', calidad: 'Usada' }),
        mkItem({ tipo: 'rin', cantidad: 1, material: 'Aluminio', huecos: '5H', tapa: 'No', tapaValvula: 'No', tamano: '18' }),
      ] },
      // Orden AXA (tarifa preferencial): 1 rin maquinado → $150.000 (vs $180.000 estándar).
      { fecha: '12/06/2026', hora: '10:15', placa: 'KTM330', aseg: 'AXA Colpatria', taller: 'Automarcali', sede: 'Sur', items: [
        mkItem({ tipo: 'rin', cantidad: 1, material: 'Maquinado', huecos: '5H', tapa: 'No', tapaValvula: 'No', tamano: '17', sinLlanta: true }),
      ] },
    ];
    var list = [];
    ordenes.forEach(function (o, i) {
      o.items.forEach(function (it, j) { it.id = 'mi-' + (i + 1) + '-' + j; });
      var cod = String(typeof reserveConsecutivo === 'function' ? reserveConsecutivo() : 6850 + i);
      var c = costear(o.items, o.aseg);
      list.push({
        id: 'men-real-' + (i + 1), codigo: cod, docType: 'orden', origen: 'externo',
        externo: { aseguradora: o.aseg, taller: o.taller, sede: o.sede, guia: '' },
        placa: o.placa, fecha: o.fecha, hora: o.hora,
        cliente: { id: (typeof asegKey === 'function' ? asegKey(o.aseg) : o.aseg), tipoDoc: 'NIT', tipoCliente: 'empresa', nombre: o.aseg, apellido: '', correo: '', direccion: '', celular: '', placas: [] },
        recibe: 'Mensajería', servicios: c.servicios, base: c.base, iva: c.iva, total: c.total, abonos: [], anticipo: 0, saldo: c.total,
        observaciones: 'Recogido en playa y entregado a recepción (handoff).', entregaEstimada: '', inspeccion: { deja: false, novedades: '' },
        items: o.items, prestamos: [], estado: 'pendiente', sinCostear: false, fuente: 'handoff-playa', viaPlaya: true
      });
    });
    localStorage.setItem('sv.recepcion', JSON.stringify(list));
    window.dispatchEvent(new Event('sv-recepcion'));
    localStorage.setItem('sv.menReal.seeded', '3');
  } catch (e) {}
}

// ─── Handoff de playa → recepción (turnos "Por asignar") ───
// Un turno es un pre-registro que crea playa desde el celular. Vive aparte de
// las recepciones; al grabarse la orden en recepción se elimina de aquí.
function loadHandoffs() { try { return JSON.parse(localStorage.getItem('sv.handoff') || '[]'); } catch (e) { return []; } }
function saveHandoff(turno) {
  try {
    var list = loadHandoffs();
    list.unshift(turno);
    localStorage.setItem('sv.handoff', JSON.stringify(list));
    window.dispatchEvent(new Event('sv-handoff'));
  } catch (e) {}
  return turno;
}
function removeHandoff(id) {
  try {
    var list = loadHandoffs().filter(function (t) { return t.id !== id; });
    localStorage.setItem('sv.handoff', JSON.stringify(list));
    window.dispatchEvent(new Event('sv-handoff'));
  } catch (e) {}
}

// ─── Costeo de mensajería (Aseguradora/Taller) ───
// Filas que aparecen en la tabla de Resumen pendientes de costear. Las alimenta
// el lado de mensajería (playa revisa → escribe la fila). Aquí recepción pone
// precio pactado y factura. Espeja el store de handoff del lado Cliente.
function DEFAULT_COSTEO() {
  if (typeof window !== 'undefined' && Array.isArray(window.COSTEO_ABRIL) && window.COSTEO_ABRIL.length) {
    return window.COSTEO_ABRIL.map(function (r) { return Object.assign({}, r); });
  }
  return [
    { id: 'co-5138', consec: '5138', placa: 'JFV058', ch: 'aseg', aseg: 'HDI Seguros', taller: 'Arautos', sede: 'Norte', piezas: [{ q: 1, t: 'rin', d: 'aluminio 5H · sin tapa' }, { q: 1, t: 'llanta', d: 'Toyo 235/60R17 · DOT 4021' }], svc: ['Rect.', 'Pint.'], precio: 240000, factura: '1C813', facturaTipo: 'factura', estado: 'lista' },
    { id: 'co-5140', consec: '5140', placa: 'LFK210', ch: 'aseg', aseg: 'Mapfre Colombia', taller: 'Almotores', sede: 'Norte', piezas: [{ q: 1, t: 'rin', d: 'maquinado 4H · Kumho 205/45R17 · DOT 0217' }], svc: ['Rect.', 'Maq.'], precio: 240000, factura: '', facturaTipo: '', estado: 'proceso' },
    { id: 'co-5141', consec: '5141', placa: 'PMZ994', ch: 'taller', aseg: 'Taller directo', taller: 'Almotores', sede: 'Norte', piezas: [{ q: 2, t: 'rin', d: 'maquinado 4H · Kumho 175/65R14 · DOT 4924' }], svc: [], precio: null, factura: '', facturaTipo: '', estado: 'costear' },
  ];
}
var COSTEO_VER = '8';
function loadCosteo() {
  try {
    var raw = localStorage.getItem('sv.costeo');
    var ver = localStorage.getItem('sv.costeo.ver');
    if (raw === null || ver !== COSTEO_VER) { var seed = DEFAULT_COSTEO(); localStorage.setItem('sv.costeo', JSON.stringify(seed)); localStorage.setItem('sv.costeo.ver', COSTEO_VER); return seed; }
    return JSON.parse(raw) || [];
  } catch (e) { return []; }
}
function saveCosteoList(list) {
  try { localStorage.setItem('sv.costeo', JSON.stringify(list || [])); window.dispatchEvent(new Event('sv-costeo')); } catch (e) {}
  return list;
}
function updateCosteo(id, patch) {
  var list = loadCosteo().map(function (r) { return r.id === id ? Object.assign({}, r, patch) : r; });
  saveCosteoList(list);
  return list;
}

// ─── Maestros: Aseguradoras / Talleres (normalización Cap + alias) ───
// Cada ficha: nombre (crudo de la base) → alias (corto, lo que muestra la tabla),
// sede, facturacion ('abierta'|'cerrada' → remisión por defecto), tarifa (opcional).
function MAESTRO_SEED() {
  return [
    { id: 'a1', tipo: 'aseg', nombre: 'HDI SEGUROS S.A.', alias: 'HDI Seguros', facturacion: 'abierta' },
    { id: 'a2', tipo: 'aseg', nombre: 'MAPFRE COLOMBIA', alias: 'Mapfre', facturacion: 'abierta' },
    { id: 'a3', tipo: 'aseg', nombre: 'SEGUROS GENERALES SURAMERICANA S.A', alias: 'Suramericana', facturacion: 'abierta' },
    { id: 'a4', tipo: 'aseg', nombre: 'SEGUROS COMERCIALES BOLÍVAR S.A', alias: 'Bolívar', facturacion: 'cerrada' },
    { id: 'a5', tipo: 'aseg', nombre: 'ALLIANZ SEGUROS S.A.', alias: 'Allianz', facturacion: 'cerrada' },
    { id: 'a6', tipo: 'aseg', nombre: 'SEGUROS DEL ESTADO', alias: 'Del Estado', facturacion: 'abierta' },
    { id: 'a7', tipo: 'aseg', nombre: 'AXA COLPATRIA', alias: 'AXA Colpatria', facturacion: 'abierta' },
    { id: 'a8', tipo: 'aseg', nombre: 'LIBERTY SEGUROS S.A', alias: 'Liberty', facturacion: 'abierta' },
    { id: 'a9', tipo: 'aseg', nombre: 'LA EQUIDAD SEGUROS', alias: 'La Equidad', facturacion: 'abierta' },
    { id: 'a10', tipo: 'aseg', nombre: 'ZURICH', alias: 'Zurich', facturacion: 'abierta' },
    { id: 'a11', tipo: 'aseg', nombre: 'RENTING', alias: 'Renting', facturacion: 'abierta' },
    { id: 't1', tipo: 'taller', nombre: 'ARAUTOS', alias: 'Arautos', sede: 'Norte' },
    { id: 't2', tipo: 'taller', nombre: 'AUTAMA', alias: 'Autama', sede: 'Norte' },
    { id: 't3', tipo: 'taller', nombre: 'ALMOTORES', alias: 'Almotores', sede: 'Norte' },
    { id: 't4', tipo: 'taller', nombre: 'COCHES DE LA SABANA', alias: 'Coches de la Sabana', sede: 'Norte' },
    { id: 't5', tipo: 'taller', nombre: 'AUTOMARCALI', alias: 'Automarcali', sede: 'Sur' },
    { id: 't6', tipo: 'taller', nombre: 'CARIBE', alias: 'Caribe', sede: 'Norte' },
    { id: 't7', tipo: 'taller', nombre: 'BAVARIAN', alias: 'Bavarian', sede: 'Sur' },
    { id: 't8', tipo: 'taller', nombre: 'NISSAN SAMECO', alias: 'Nissan Sameco', sede: 'Norte' },
    { id: 't9', tipo: 'taller', nombre: 'TALLER', alias: 'Taller directo', sede: '' },
  ];
}
function loadMaestros() {
  try { var raw = localStorage.getItem('sv.maestros'); if (raw === null) { var s = MAESTRO_SEED(); localStorage.setItem('sv.maestros', JSON.stringify(s)); return s; } return JSON.parse(raw) || []; } catch (e) { return MAESTRO_SEED(); }
}
function saveMaestrosList(list) { try { localStorage.setItem('sv.maestros', JSON.stringify(list || [])); window.dispatchEvent(new Event('sv-maestros')); } catch (e) {} return list; }
function updateMaestro(id, patch) { var list = loadMaestros().map(function (m) { return m.id === id ? Object.assign({}, m, patch) : m; }); saveMaestrosList(list); return list; }
// Asegura que todo taller/aseguradora referenciado en costeo+recepción exista en Maestros
// (idempotente: agrega solo los que falten) para que sean editables y resuelvan alias/sede.
function ensureMaestrosFromDataset() {
  try {
    var list = loadMaestros();
    var have = {}; list.forEach(function (m) { have[maestroKey(m.nombre)] = true; });
    var add = [];
    function consider(tipo, nombre, sede) {
      var raw = String(nombre || '').trim(); if (!raw || /^TALLER$/i.test(raw)) return;
      var k = maestroKey(raw); if (!k || have[k]) return;
      have[k] = true;
      var entry = { id: tipo.charAt(0) + '-ds-' + k.slice(0, 12) + '-' + (list.length + add.length), tipo: tipo, nombre: raw, alias: normNombre(raw) };
      if (tipo === 'taller') entry.sede = sede || ''; else entry.facturacion = 'abierta';
      add.push(entry);
    }
    var cos = (typeof loadCosteo === 'function') ? loadCosteo() : [];
    cos.forEach(function (r) { if (r && r.taller) consider('taller', r.taller, r.sede); if (r && r.aseg) consider('aseg', r.aseg); });
    var rec = (typeof loadRecepciones === 'function') ? loadRecepciones() : [];
    rec.forEach(function (r) { var ext = (r && r.externo) || {}; if (ext.taller) consider('taller', ext.taller, ext.sede); if (ext.aseguradora) consider('aseg', ext.aseguradora); });
    if (add.length) saveMaestrosList(list.concat(add));
  } catch (e) {}
}
// Consolida fichas de taller duplicadas por mismo nombre base (p.ej. "COCHES DE LA SABANA"
// vs "Coches De La Sabana (Primera)"): conserva la que referencian los registros y elimina la otra.
function consolidateTalleresMaestros() {
  try {
    var list = loadMaestros();
    var key = function (s) { return String(s || '').toUpperCase().replace(/[^A-Z0-9]/g, ''); };
    var baseKey = function (s) { return key(String(s || '').replace(/\([^)]*\)/g, '')); };
    var ref = {};
    var cos = (typeof loadCosteo === 'function') ? loadCosteo() : [];
    cos.forEach(function (r) { if (r && r.taller) ref[key(r.taller)] = true; });
    var rec = (typeof loadRecepciones === 'function') ? loadRecepciones() : [];
    rec.forEach(function (r) { var e = (r && r.externo) || {}; if (e.taller) ref[key(e.taller)] = true; });
    var groups = {};
    list.forEach(function (m) { if (m.tipo !== 'taller' || key(m.nombre) === 'TALLER') return; var b = baseKey(m.nombre); (groups[b] = groups[b] || []).push(m); });
    var drop = {};
    Object.keys(groups).forEach(function (b) {
      var g = groups[b]; if (g.length < 2) return;
      var keep = g.find(function (m) { return ref[key(m.nombre)]; }) || g[0];
      g.forEach(function (m) { if (m.id !== keep.id) drop[m.id] = true; });
    });
    var n = Object.keys(drop).length;
    if (n) saveMaestrosList(list.filter(function (m) { return !drop[m.id]; }));
    return n;
  } catch (e) { return 0; }
}
// Migración puntual de talleres mal nombrados por el catálogo legacy → nombre + sede correctos,
// y eliminación de las fichas duplicadas. Idempotente.
function migrateTalleres() {
  try {
    var key = function (s) { return String(s || '').toUpperCase().replace(/[^A-Z0-9]/g, ''); };
    var MAP = {
      NISSANSAMECO: { taller: 'Talleres Autorizados Nissan', sede: 'Sameco' },
      COCHESDELASABANAPRIMERA: { taller: 'Coches de la Sabana', sede: 'Primera' },
      ALMOTORESRENAULT: { taller: 'Almotores', sede: 'Renault' },
    };
    if (typeof loadCosteo === 'function') {
      var cos = loadCosteo(); var ch = false;
      cos.forEach(function (r) { var m = r && MAP[key(r.taller)]; if (m) { r.taller = m.taller; r.sede = m.sede; ch = true; } });
      if (ch && typeof saveCosteoList === 'function') saveCosteoList(cos);
    }
    try {
      var rec = JSON.parse(localStorage.getItem('sv.recepcion') || '[]'); var ch2 = false;
      rec.forEach(function (r) { var e = r && r.externo; var m = e && MAP[key(e.taller)]; if (m) { e.taller = m.taller; e.sede = m.sede; ch2 = true; } });
      if (ch2) { localStorage.setItem('sv.recepcion', JSON.stringify(rec)); window.dispatchEvent(new Event('sv-recepcion')); }
    } catch (e) {}
    var ms = loadMaestros();
    var ms2 = ms.filter(function (x) { return !(x.tipo === 'taller' && MAP[key(x.nombre)]); });
    if (ms2.length !== ms.length) saveMaestrosList(ms2);
  } catch (e) {}
}
function maestroKey(raw) { return String(raw || '').toUpperCase().replace(/[^A-Z0-9]/g, ''); }
var _SMALL_W = { de: 1, del: 1, la: 1, las: 1, los: 1, y: 1, en: 1 };
function normNombre(raw) {
  var s = String(raw || '').trim().replace(/\s+/g, ' ');
  if (!s) return '';
  s = s.replace(/\s+(S\.?A\.?S?\.?|LTDA\.?|& ?CIA\.?|Y ?CIA\.?)\s*$/i, '');
  return s.toLowerCase().split(' ').map(function (w, i) { if (i > 0 && _SMALL_W[w]) return w; return w.charAt(0).toUpperCase() + w.slice(1); }).join(' ');
}
function aliasNombre(raw) {
  var key = maestroKey(raw);
  var m = (loadMaestros() || []).find(function (x) { return maestroKey(x.nombre) === key || (x.alias && maestroKey(x.alias) === key); });
  if (m && m.alias) return m.alias;
  return normNombre(raw);
}
function facturacionDe(raw) { var key = maestroKey(raw); var m = (loadMaestros() || []).find(function (x) { return maestroKey(x.nombre) === key; }); return m ? (m.facturacion || 'abierta') : 'abierta'; }
var SVC_ABREV = { 'rectificado': 'Rect', 'rectificado de rines': 'Rect', 'maquinado': 'Maq', 'maquinado de rines': 'Maq', 'diamantado': 'Maq', 'diamantado de rines': 'Maq', 'pintura electrostática': 'Elect', 'pintura electrostatica': 'Elect', 'pintura líquida': 'Pint', 'pintura liquida': 'Pint', 'soldadura': 'Sold', 'balanceo': 'Bal', 'vulcanizado': 'Vulc', 'vulcanizado de llantas': 'Vulc', 'parche': 'Parche', 'parche en frío': 'Parche', 'parche en frio': 'Parche' };
function abrevSvc(s) { var k = String(s || '').trim().toLowerCase(); return SVC_ABREV[k] || s; }

// Make available globally for cross-file usage
Object.assign(window, { adminPendientes, useAdminPendientes, GlobitoPendientes, ModoEntregaTile, GRIS_DESACTIVADO, MotivoBloqueo,
  TOKENS, I, AppHeader, BottomNav, FieldLabel, Select, TextInput,
  Stepper, Toggle, Button, Chip, PhotoSlot, Card,
  fechaDDMMYYYY, fechaCorta, fechaHoraCorta,
  sanitizeAlnum, isPlacaValida, isVinValido, PLACA_ERROR_MSG,
  llantaBreakdown, calidadTone, LlantaDotValue, LlantaCalidadValue, PhotoStrip, PhotoSlider,
  ProfileAvatar, loadAvatar, saveAvatar, useAvatar, pickAvatarFile,
  userName, userInitials, deriveInitials, capName, capNameLive, usePerfilName,
  downscaleDataURL, safeSetItem, formatHora12,
  peekConsecutivo, reserveConsecutivo,
  loadClientes, saveCliente, loadRecepciones, saveRecepcion, updateRecepcion,
  loadCajaAll, getCajaDia, saveCajaDia, abrirCajaDia, ingresosAutoDia, seedDemoCajaIfEmpty,
  loadHandoffs, saveHandoff, removeHandoff, asegKey, fixExternoModel,
  inferAccion, seedMensajeriaReal,
  loadCosteo, saveCosteoList, updateCosteo, DEFAULT_COSTEO,
  loadMaestros, saveMaestrosList, updateMaestro, MAESTRO_SEED, ensureMaestrosFromDataset, consolidateTalleresMaestros, migrateTalleres,
  normNombre, aliasNombre, facturacionDe, maestroKey, abrevSvc
});