// Catálogos (13/11/2026): talleres/sedes y aseguradoras, editables por el admin.
// Semilla: pestaña TALLERES de Control Subastas (173 filas → talleres + sedes + cómo llegan).
const CAT_SEED_TALLERES = [["100% Car Service", [["Norte", "Norte", "Cali", ["100% CAR SERVICE"]]]], ["Ab Autopartes", [["Norte", "Norte", "Cali", ["AB AUTOPARTES"]]]], ["Agricola Automotriz", [["Norte", "Norte", "Cali", ["AGRICOLA AUTOMOTRIZ"]]]], ["Alborautos Popayán", [["Popayán", null, "Popayán", ["ALBORAUTOS POPAYAN"]]]], ["Alia2 Automotriz", [["Norte", "Norte", "Cali", ["ALIA2 AUTOMOTRIZ"]]]], ["Alianza Automotora", [["Sur", "Sur", "Cali", ["ALIANZA AUTOMOTORA", "ALIANZA AUTOMOTORA DE OCCIDENTE S.A.S"]]]], ["Almotores", [["Kia", "Norte", "Cali", ["ALMOTORES", "ALMOTORES KIA", "ALMOTORES S.A"]], ["Volkswagen", "Sur", "Cali", ["ALMOTORES", "ALMOTORES WOLKSWAGUEN"]], ["Renault", "Norte", "Cali", ["ALMOTORES RENAULT", "Almotores Renault Calle 26"]]]], ["Arautos", [["Norte", "Norte", "Cali", ["ARAUTOS", "ARAUTOS SEDE NORTE (PREFERENCIAL)"]], ["Sur", "Sur", "Cali", ["ARAUTOS", "ARAUTOS SEDE SUR (PREFERENCIAL)"]]]], ["Autama", [["Norte", "Norte", "Cali", ["AUTAMA"]]]], ["Auteco", [["Norte", "Norte", "Cali", ["AUTECO NORTE"]]]], ["Auto Expres", [["Norte", "Norte", "Cali", ["AUTO EXPRES"]]]], ["Auto Orion", []], ["Autobon", [["Norte", "Norte", "Cali", ["AUTOBON"]], ["Sur", "Sur", "Cali", ["AUTOBON", "COLEGAS S.A.S - SUR"]]]], ["Automarcali", [["Norte", "Norte", "Cali", ["AUTOMARCALI"]], ["Sur", "Sur", "Cali", ["AUTOMARCALI", "AUTOMARCALI S.A TODO TIPO", "AUTOMARCALI S.A.S - CHEVROLET", "AUTOMARCALI S.A.S. - (MITSUBISHI Y BYD)", "Automarcali Sa Cali"]]]], ["Automotor Co", [["Norte", "Norte", "Cali", ["AUTOMOTOR. CO"]]]], ["Automotora Norte y Sur", [["Acopi", "Norte", "Cali", ["AUTOMOTORA ACOPI", "AUTOMOTORA NORTE Y SUR", "AUTOMOTORA NORTE Y SUR SEDE NORTE", "Automotora Norte Y Sur Acopi Renault", "TOYOTA ACOPI"]], ["Sur", "Sur", "Cali", ["AUTOMOTORA NORTE Y SUR", "AUTOMOTORA NORTE Y SUR AV PASOANCHO", "AUTOMOTORA NORTE Y SUR LTDA  ZONASUR"]], ["Carrera 1", "Norte", "Cali", ["AUTOMOTORA NORTE Y SUR CARRERA 1"]]]], ["Automotores Sanpel", [["Sur", "Sur", "Cali", ["AUTOMOTORES SANPEL (PREFERENCIAL)", "COCHES DEL PACIFICO", "SAMPEL", "SANPEL", "SANTIAGO DE CALI"]]]], ["Automotriz del Sur Pasto", [["Pasto", null, "Pasto", ["AUTOMOTRIZ DEL SUR PASTO"]]]], ["Autoniza", [["Norte", "Norte", "Cali", ["AUTONIZA"]]]], ["Autopacífico", [["Norte", "Norte", "Cali", ["AUTOPACIFICO", "AUTOPACIFICO LTDA", "AUTOPACIFICO S.A - NORTE"]], ["Sur", "Sur", "Cali", ["AUTOPACIFICO"]], ["Palmira", null, "Palmira", ["AUTOPACIFICO PALMIRA"]], ["Popayán", null, "Popayán", ["AUTOPACIFICO POPAYAN"]], ["Tuluá", null, "Tuluá", ["AUTOPACIFICO TULUA"]]]], ["Autorion", [["Norte", "Norte", "Cali", ["AUTORION"]]]], ["Autosuperior", [["Norte", "Norte", "Cali", ["AUTOSUPERIOR", "AUTOSUPERIOR (PREFERENCIAL)", "AUTOSUPERIOR LTDA. SAS", "AUTOSUPERIOR S.A.S"]], ["Sur", "Sur", "Cali", ["AUTOSUPERIOR"]]]], ["Bavarian Collitions Auto Parts", [["Sur", "Sur", "Cali", ["BAVARIAN COLLITIONS AUTO PARTS (PREFERENCIAL)", "BAVARIAN COLLITIONS AUTO PARTS TT (PREFERENCIAL)", "BAVARIAN SUR"]]]], ["Caldas Motor", []], ["Caminos Pereira", [["Pereira", null, "Pereira", ["CAMINOS PEREIRA"]]]], ["Caribe", [["Norte", "Norte", "Cali", ["CARIBE", "CARIBE S.A.S"]], ["Sur", "Sur", "Cali", ["CARIBE", "CARIBE S.A.S", "CARIBE SAS"]]]], ["Centro de Colisión del Norte", [["Norte", "Norte", "Cali", ["CENTRO DE COLISION", "CENTRO DE COLISION DEL NORTE S.A.S"]]]], ["Cliente Particular", [["Norte", "Norte", "Cali", ["CLIENTE", "CLIENTE PARTICULAR"]], ["Sur", "Sur", "Cali", ["CLIENTE"]]]], ["Clinipartes", [["Norte", "Norte", "Cali", ["CLINIPARTES"]]]], ["Clínica Golpes y Rayones", [["Norte", "Norte", "Cali", ["CLÍNICA GOLPES Y RAYONES"]]]], ["Coches de la Sabana", [["1ra", "Norte", "Cali", ["COCHES DE LA SABANA (PRIMERA)", "LOS COCHES S.A.S. - (GRUPO PORSCHE)"]], ["8va", "Norte", "Cali", ["COCHES DE LA SABANA 8A", "LOS COCHES DE LA SABANA CALI CRA 8"]]]], ["Coches del Sur", [["Norte", "Norte", "Cali", ["COCHES DEL SUR"]]]], ["Colmotores", [["Sur", "Sur", "Cali", ["COLMOTORES"]]]], ["Derco", [["Norte", "Norte", "Cali", ["DERCO"]]]], ["Distoyota", []], ["Fanalca Autoceiba", [["Norte", "Norte", "Cali", ["FANALCA", "FANALCA AUTOCEIBA", "FANALCA S.A (AUTOCEIBA)"]]]], ["Farallones", [["Norte", "Norte", "Cali", ["FARALLONES"]]]], ["Fawtracks", [["Norte", "Norte", "Cali", ["FAWTRACKS"]]]], ["Golpes y Rayones", [["Norte", "Norte", "Cali", ["GOLPES Y RAYONES"]]]], ["Honda", [["Norte", "Norte", "Cali", ["HONDA"]]]], ["Hyundai", [["Norte", "Norte", "Cali", ["HYUNDAI"]]]], ["Importadora Renault Servicios", [["Norte", "Norte", "Cali", ["IMPORTADORA RENAULT SERVICIOS."]]]], ["Incolmotos Yamaha", [["Norte", "Norte", "Cali", ["INCOLMOTOS YAMAHA"]]]], ["Inversiones Ob Motul", [["Norte", "Norte", "Cali", ["INVERSIONES OB  MOTUL"]]]], ["Kenworth", [["Norte", "Norte", "Cali", ["KENWORTH"]]]], ["Llanteca", [["Norte", "Norte", "Cali", ["LLANTECA"]]]], ["Los Pits Plaza Automotriz", [["Norte", "Norte", "Cali", ["LOS PITS PLAZA AUTOMOTRIZ."]]]], ["Mazko", [["Norte", "Norte", "Cali", ["MAZKO", "MAZKO S.A - Sede Norte"]], ["Sur", "Sur", "Cali", ["MAZKO", "MAZKO SUR"]]]], ["Mercedes", [["Norte", "Norte", "Cali", ["MERCEDES"]]]], ["Mercedes Massy Motors", [["Norte", "Norte", "Cali", ["MASSY MOTORS PREMIUM"]], ["Sur", "Sur", "Cali", ["MASSY MOTORS PREMIUM"]]]], ["Motor K", []], ["Motorwagen", [["Sur", "Sur", "Cali", ["MOTORWAGEN"]]]], ["Nelcar", [["Norte", "Norte", "Cali", ["NELCAR"]]]], ["Nextcolor", [["Norte", "Norte", "Cali", ["NEXTCOLOR"]]]], ["Pasto Motors", [["Pasto", null, "Pasto", ["PASTO MOTORS"]]]], ["Pinteco", [["Norte", "Norte", "Cali", ["PINTECO"]]]], ["Pracodidacol", [["Norte", "Norte", "Cali", ["PRACODIDACOL"]]]], ["Quality Cars", [["Norte", "Norte", "Cali", ["QUALITY CARS"]]]], ["Renovautos", [["Norte", "Norte", "Cali", ["RENOVAUTOS"]], ["Sur", "Sur", "Cali", ["RENOVAUTOS", "RENOVAUTOS SAS (PREFERENCIAL)"]]]], ["Sao Wilmer", [["Norte", "Norte", "Cali", ["SAO WILMER"]]]], ["Segurautos Tuluá", [["Tuluá", null, "Tuluá", ["SEGURAUTOS TULUA"]]]], ["Serautovalle", [["Norte", "Norte", "Cali", ["SERAUTOVALLE", "SERAUTOVALLE MULTIMARCA", "SERAUTOVALLE S.A.S"]]]], ["Servicar", [["Norte", "Norte", "Cali", ["SERVICAR"]]]], ["Solo Estrellas", [["Norte", "Norte", "Cali", ["SOLO ESTRELLAS"]]]], ["Taller Arce Multimarca", [["Sur", "Sur", "Cali", ["TALLER ARCE", "TALLER ARCE MULTIMARCA", "TALLER ARCE TT (PREFERENCIAL)"]]]], ["Taller Daytona", [["Norte", "Norte", "Cali", ["TALLER DAYTONA"]]]], ["Taller Sttugart Julio Martinez", [["Norte", "Norte", "Cali", ["TALLER STTUGART JULIO MARTINEZ"]], ["Sur", "Sur", "Cali", ["TALLER STTUGART JULIO MARTINEZ"]]]], ["Talleres Autorizados Nissan", [["Sede 34", "Norte", "Cali", ["NISSAN 34"]], ["Sameco", "Norte", "Cali", ["NISSAN SAMECO", "TALLERES AUTORIZADOS NISSAN S.A. CALI", "TALLERES AUTORIZADOS NISSAN S.A. CALI TT CONVENIO", "TALLERES AUTORIZADOS NISSAN S.A. CALI TT NISSAN", "Talleres Autorizados Sa Cali"]]]], ["Tecnomotriz", [["Norte", "Norte", "Cali", ["TECNOMOTRIZ"]]]], ["Transmisiones Automáticas", [["Sur", "Sur", "Cali", ["TRANSMISIONES AUTOMATICAS"]]]], ["Volcali", [["Norte", "Norte", "Cali", ["VOLCALI"]]]]];
const CAT_SEED_REVISAR = [["Almotores Renault Calle 26", "Almotores", "Renault"], ["ALMOTORES S.A", "Almotores", ""], ["AUTO ORION S.A", "Auto Orion", ""], ["AUTOMARCALI S.A.S. - (MITSUBISHI Y BYD)", "Automarcali", "Sur"], ["Automarcali Sa Cali", "Automarcali", "Sur"], ["AUTOMOTORA NORTE Y SUR CARRERA 1", "Automotora Norte y Sur", "Carrera 1"], ["AUTOMOTORA NORTE Y SUR LTDA  ZONASUR", "Automotora Norte y Sur", "Sur"], ["AUTOMOTORES SANPEL (PREFERENCIAL)", "Automotores Sanpel", ""], ["AUTOPACIFICO PALMIRA", "Autopacífico", "Palmira"], ["AUTOSUPERIOR LTDA. SAS", "Autosuperior", "Norte"], ["BAVARIAN COLLITIONS AUTO PARTS (PREFERENCIAL)", "Bavarian Collitions Auto Parts", "Sur"], ["CALDAS MOTOR", "Caldas Motor", ""], ["CENTRO DE COLISION DEL NORTE S.A.S", "Centro de Colisión del Norte", "Norte"], ["DISTOYOTA S.A.S", "Distoyota", ""], ["FANALCA AUTOCEIBA", "Fanalca Autoceiba", "Norte"], ["FANALCA S.A (AUTOCEIBA)", "Fanalca Autoceiba", "Norte"], ["INCOLMOTOS YAMAHA S.A - CALI", "Incolmotos Yamaha", ""], ["MAZKO S.A - Sede Norte", "Mazko", "Norte"], ["MAZKO SUR", "Mazko", "Sur"], ["MOTOR K SAS", "Motor K", ""], ["PASTO MOTORS", "Pasto Motors", "Pasto"], ["SERAUTOVALLE MULTIMARCA", "Serautovalle", "Norte"], ["TALLER ARCE MULTIMARCA", "Taller Arce Multimarca", "Sur"], ["TALLERES AUTORIZADOS NISSAN S.A. CALI TT NISSAN", "Talleres Autorizados Nissan", "Sameco"]];

// Aseguradoras (13/11/2026): nombre corto + cómo llega en las órdenes. c = registros desde 2024
// (pestaña MENSAJERIA de Control Subastas). Liberty ahora es HDI: es un alias de HDI.
const CAT_SEED_ASEG = [
['Taller directo', ['TALLER'], 865], ['HDI', ['HDI SEGUROS S.A.', 'LIBERTY SEGUROS S.A', 'Liberty'], 975],
['Sura', ['SEGUROS GENERALES SURAMERICANA S.A'], 725], ['Mapfre', ['MAPFRE COLOMBIA'], 704],
['Axa', ['AXA COLPATRIA', 'AXA Colpatria'], 564], ['Allianz', ['ALLIANZ SEGUROS S.A.'], 370],
['Bolívar', ['SEGUROS COMERCIALES BOLÍVAR S.A'], 352], ['Equidad', ['LA EQUIDAD SEGUROS', 'La Equidad'], 111],
['SBS', ['SBS'], 99], ['Zurich', ['ZURICH'], 99], ['Renting', ['RENTING'], 96],
['Estado', ['SEGUROS DEL ESTADO', 'Seguros del Estado'], 75], ['Solidaria', ['SOLIDARIA'], 32], ['Previsora', ['PREVISORA'], 18]];

const CAT_KEY = 'rodando.catalogo.v1';
const CAT_CIUDADES = ['Cali', 'Palmira', 'Popayán', 'Tuluá', 'Pasto', 'Pereira', 'Manizales']; // Manizales: 25/11/2026
const catNorm = (s) => String(s || '').normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().trim();
const catId = (p) => p + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);

function catSeed() {
  let n = 0;
  return {
    talleres: CAT_SEED_TALLERES.filter(([nombre]) => !esParticular(nombre)).map(([nombre, sedes], i) => ({
      id: 't' + i, nombre, on: true,
      sedes: sedes.map(([sn, zona, ciudad, alias]) => ({ id: 's' + n++, nombre: sn, zona, ciudad, alias, dir: '', ubic: null, lat: null, lng: null }))
    })),
    aseguradoras: CAT_SEED_ASEG.map(([n2, a, c], i) => ({ id: 'a' + i, nombre: n2, alias: a, c, on: true })),
    revisar: CAT_SEED_REVISAR.map(([llega, taller, sede], i) => ({ id: 'r' + i, llega, taller, sede, motivo: sede ? 'hoja' : 'sinsede', createdAt: Date.now() }))
  };
}
let catCache = null; // se lee muchas veces por render (tarjetas): se guarda en memoria
function loadCatalogo() {
  if (catCache) return catCache;
  try { const c = JSON.parse(localStorage.getItem(CAT_KEY)); if (c && c.talleres) { if (c.talleres.some((t) => esParticular(t.nombre))) { c.talleres = c.talleres.filter((t) => !esParticular(t.nombre)); try { localStorage.setItem(CAT_KEY, JSON.stringify(c)); } catch (e) {} } return catCache = c; } } catch (e) {}
  const s = catSeed(); try { localStorage.setItem(CAT_KEY, JSON.stringify(s)); } catch (e) {}
  return catCache = s;
}
function saveCatalogo(c) {
  catCache = c;
  try { localStorage.setItem(CAT_KEY, JSON.stringify(c)); } catch (e) {}
  window.dispatchEvent(new Event('rodando-catalogo'));
}
function useCatalogo() {
  const [c, setC] = React.useState(loadCatalogo);
  React.useEffect(() => { const h = () => setC(loadCatalogo()); window.addEventListener('rodando-catalogo', h); return () => window.removeEventListener('rodando-catalogo', h); }, []);
  const update = (fn) => { const next = JSON.parse(JSON.stringify(loadCatalogo())); fn(next); saveCatalogo(next); setC(next); };
  return [c, update];
}
// ─── Consultas que usan Recoger, Rutas e Inicio ───
function catTalleresSedes() {
  return loadCatalogo().talleres.filter((t) => t.on).map((t) => ({ nombre: t.nombre, sedes: t.sedes.map((s) => s.nombre) }));
}
function catAseguradoras() {
  return loadCatalogo().aseguradoras.filter((a) => a.on).slice().sort((a, b) => b.c - a.c);
}
// Nombre corto de una aseguradora (registros viejos: "Liberty" → HDI, "AXA Colpatria" → Axa).
function catAseguradoraCorta(x) {
  const k = catNorm(x); if (!k) return x;
  const a = loadCatalogo().aseguradoras.find((z) => catNorm(z.nombre) === k || z.alias.some((y) => catNorm(y) === k));
  return a ? a.nombre : x;
}
function catUbicacion(taller, sede) {
  const t = loadCatalogo().talleres.find((z) => catNorm(z.nombre) === catNorm(taller)); if (!t) return null;
  const s = t.sedes.find((z) => catNorm(z.nombre) === catNorm(sede)); if (!s) return null;
  return { lat: s.lat, lng: s.lng, direccion: s.dir || '', ciudad: s.ciudad || 'Cali', ubic: s.ubic };
}
function catPendientesMensajero() {
  return loadCatalogo().revisar.filter((r) => r.motivo === 'mens');
}
function catAgregarRevision(r) {
  const c = loadCatalogo();
  c.revisar.unshift({ id: catId('r'), createdAt: Date.now(), ...r });
  saveCatalogo(c);
}
// Coordenadas desde un enlace de Google Maps (si las trae: @lat,lng o q=lat,lng).
function catCoordsDeEnlace(url) {
  const m = String(url).match(/@(-?\d+\.\d+),(-?\d+\.\d+)/) || String(url).match(/[?&](?:q|ll|query)=(-?\d+\.\d+),\s*(-?\d+\.\d+)/);
  return m ? { lat: +m[1], lng: +m[2] } : null;
}
const catSedeSub = (s) => s.ciudad && s.ciudad !== 'Cali' ? s.ciudad : (s.zona && s.zona !== s.nombre ? s.zona : 'Cali');
function catSubTaller(t) {
  if (!t.sedes.length) return 'Sin sede';
  if (t.sedes.length === 1) { const s = t.sedes[0]; return s.zona && s.zona !== s.nombre && s.ciudad === 'Cali' ? `${s.nombre} · ${s.zona}` : s.nombre; }
  return `${t.sedes.length} sedes · ${t.sedes.map((s) => s.nombre).join(', ')}`;
}

// ─── Piezas de UI compartidas ───
const catLbl = { fontSize: 10.5, fontWeight: 800, letterSpacing: '0.06em', color: TOKENS.textMuted, textTransform: 'uppercase' };
const catYellow = { bg: '#fff2cc', text: '#7f6000', border: '#ecd98f' };
function CatHoja({ title, onClose, children, alto }) {
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(11,28,48,0.5)', zIndex: 1000, display: 'flex', alignItems: 'flex-end', justifyContent: 'center' }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: TOKENS.bg, width: '100%', maxWidth: 440, height: alto ? '86vh' : 'auto', maxHeight: '86vh', borderRadius: '18px 18px 0 0', display: 'flex', flexDirection: 'column' }}>
        <div style={{ display: 'flex', alignItems: 'center', padding: '14px 16px 10px', borderBottom: `1px solid ${TOKENS.border}` }}>
          <b style={{ flex: 1, fontSize: 16, color: TOKENS.text }}>{title}</b>
          <button type="button" onClick={onClose} aria-label="Cerrar" style={{ border: 0, background: 'none', cursor: 'pointer', display: 'flex', padding: 4 }}>{I.x(18, TOKENS.textMuted)}</button>
        </div>
        <div style={{ overflowY: 'auto', padding: '6px 16px 20px' }}>{children}</div>
      </div>
    </div>);
}
function CatBuscar({ value, onChange, placeholder, autoFocus }) {
  return (
    <div style={{ position: 'relative', marginTop: 10 }}>
      <div style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', display: 'flex', pointerEvents: 'none' }}>{I.consultar(16, TOKENS.textMuted)}</div>
      <input autoFocus={autoFocus} value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} style={{ width: '100%', boxSizing: 'border-box', border: `1px solid ${TOKENS.borderInput}`, background: TOKENS.surface, borderRadius: 12, padding: '11px 12px 11px 36px', fontSize: 14, color: TOKENS.text, fontFamily: 'inherit', outline: 'none' }} />
    </div>);
}
function CatResultado({ titulo, sub, onClick }) {
  return (
    <button type="button" onClick={onClick} style={{ display: 'block', width: '100%', textAlign: 'left', border: 0, borderBottom: `1px solid ${TOKENS.border}`, background: 'none', padding: '11px 2px', fontFamily: 'inherit', cursor: 'pointer', color: TOKENS.text }}>
      <b style={{ fontSize: 14, fontWeight: 700 }}>{titulo}</b>
      {sub && <span style={{ display: 'block', fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>{sub}</span>}
    </button>);
}
const catChip = (on) => ({ border: `1px solid ${on ? TOKENS.primary : TOKENS.borderInput}`, background: on ? TOKENS.primary : TOKENS.surface, color: on ? '#fff' : TOKENS.text, borderRadius: 9, padding: '9px 12px', fontFamily: 'inherit', fontSize: 13, fontWeight: 700, cursor: 'pointer' });
const catInput = { width: '100%', boxSizing: 'border-box', border: `1px solid ${TOKENS.borderInput}`, background: TOKENS.surfaceLow, borderRadius: 10, padding: '10px 11px', fontSize: 14, fontWeight: 600, color: TOKENS.text, fontFamily: 'inherit', outline: 'none' };
function CatTag({ children, y }) {
  return <span style={{ display: 'inline-block', fontSize: 10.5, fontWeight: 600, borderRadius: 999, padding: '2px 8px', marginLeft: 4, verticalAlign: 1, background: y ? catYellow.bg : TOKENS.surfaceLow, color: y ? catYellow.text : TOKENS.textMuted, border: `1px solid ${y ? catYellow.border : TOKENS.border}` }}>{children}</span>;
}

// ─── Recoger (13/11/2026): Placa | Aseguradora y Taller | Sede como antes, con listas del catálogo ───
// 23/11/2026: "Cliente particular" es un taller fijo, sin sedes ni aseguradora. Pide nombre, teléfono y dirección.
const CLIENTE_PARTICULAR = 'Cliente particular';
// 26/11/2026: "Cliente particular" no lleva sede (ni Norte ni Sur). Vale cualquier forma de escribirlo (CLIENTE, Cliente Particular…).
const esParticular = (taller) => { const k = catNorm(taller); return k === 'cliente particular' || k === 'cliente'; };
function catTallerOpciones() {
  return [...loadCatalogo().talleres.filter((t) => t.on && t.sedes.length).map((t) => ({ value: t.nombre, label: t.nombre, alias: [...new Set(t.sedes.flatMap((s) => s.alias))] })), { value: CLIENTE_PARTICULAR, label: CLIENTE_PARTICULAR, alias: ['particular', 'cliente'] }];
}
function catSedesDe(taller) {
  if (esParticular(taller)) return [];
  const t = loadCatalogo().talleres.find((z) => z.nombre === taller);
  return t ? t.sedes.map((s) => s.nombre) : [];
}
// ─── Ciudades (25/11/2026): cobertura (se cotiza y repara el rin) y si el mensajero recoge allí ───
function catCiudades() {
  const c = loadCatalogo();
  const out = (c.ciudades || CAT_CIUDADES.map((n) => ({ n, cob: true, men: n === 'Cali' }))).map((x) => ({ ...x }));
  c.talleres.forEach((t) => t.sedes.forEach((s) => { if (s.ciudad && !out.some((x) => catNorm(x.n) === catNorm(s.ciudad))) out.push({ n: s.ciudad, cob: false, men: false }); }));
  return out;
}
function catCiudadInfo(n) { const k = catNorm(n || 'Cali'); return catCiudades().find((x) => catNorm(x.n) === k) || { n, cob: false, men: false }; }
function catGuardarCiudades(lista) { const c = JSON.parse(JSON.stringify(loadCatalogo())); c.ciudades = lista; saveCatalogo(c); }
// ¿El mensajero recoge en la ciudad de esta sede? (sin ubicación conocida: sí, como hasta ahora)
function catMensajeroRecoge(taller, sede) { if (esParticular(taller)) return true; const u = catUbicacion(taller, sede); return !u || catCiudadInfo(u.ciudad).men !== false; }
function catSedesRuta(taller) { return catSedesDe(taller).filter((s) => catMensajeroRecoge(taller, s)); }
function catTallerOpcionesRuta() { return catTallerOpciones().filter((o) => esParticular(o.value) || catSedesRuta(o.value).length); }
// Ubicación de una sede (25/11/2026): "Estoy aquí" desde la ruta y la plantilla de Excel.
function catGuardarUbicacion(taller, sede, lat, lng) {
  const c = JSON.parse(JSON.stringify(loadCatalogo()));
  const t = c.talleres.find((z) => catNorm(z.nombre) === catNorm(taller)); if (!t) return false;
  const s = t.sedes.find((z) => catNorm(z.nombre) === catNorm(sede)); if (!s) return false;
  s.lat = lat; s.lng = lng; s.ubic = `https://maps.google.com/?q=${lat},${lng}`; saveCatalogo(c); return true;
}
// "3.4516, -76.5320" · "3,4516; -76,5320" → {lat, lng} si cae en Colombia
function catCoordsDeTexto(txt) {
  const n = String(txt || '').match(/-?\d+(?:[.,]\d+)?/g); if (!n || n.length < 2) return null;
  const lat = +n[0].replace(',', '.'), lng = +n[1].replace(',', '.');
  return lat > -5 && lat < 14 && lng > -82 && lng < -66 ? { lat: +lat.toFixed(6), lng: +lng.toFixed(6) } : null;
}
// ─── Unir talleres (26/11/2026): un taller que en realidad es otro (Honda → Fanalca Autoceiba) ───
// c.unidos = [{ id, fecha, src: <taller completo>, destId, pares: [{ de: {t, s}, a: {t, s}, destSedeId, alias: [añadidos] }] }]
// Los registros viejos no se reescriben: se muestran con el nombre nuevo (catCanonObj) y se puede deshacer.
function catCanon(taller, sede) {
  const u = loadCatalogo().unidos; if (!u || !u.length || !taller) return null;
  const kt = catNorm(taller), ks = catNorm(sede || '');
  // Sede unida dentro del mismo taller (Renovautos Norte → Sur): solo si coincide la sede.
  for (const x of u) { if (x.tipo !== 'sede') continue; const p = x.pares[0]; if (catNorm(p.de.t) === kt && catNorm(p.de.s) === ks) return { taller: p.a.t, sede: p.a.s }; }
  for (const x of u) { if (x.tipo === 'sede') continue; const ps = x.pares.filter((p) => catNorm(p.de.t) === kt); if (!ps.length) continue; const p = ps.find((y) => catNorm(y.de.s) === ks) || ps[0]; return { taller: p.a.t, sede: p.a.s }; }
  return null;
}
function catCanonObj(o) { if (!o || !o.taller) return o; if (esParticular(o.taller)) return o.taller === CLIENTE_PARTICULAR && !o.sede ? o : { ...o, taller: CLIENTE_PARTICULAR, sede: '' }; const c = catCanon(o.taller, o.sede); return c ? { ...o, taller: c.taller, sede: c.sede } : o; }
function catUnirTaller(srcId, destId, mapa) { // mapa: { idSedeOrigen: idSedeDestino }
  const c = JSON.parse(JSON.stringify(loadCatalogo()));
  const src = c.talleres.find((t) => t.id === srcId), dest = c.talleres.find((t) => t.id === destId); if (!src || !dest || src === dest) return false;
  const pares = (src.sedes.length ? src.sedes : [{ id: null, nombre: '', alias: [] }]).map((ss) => {
    const ds = dest.sedes.find((z) => z.id === mapa[ss.id]) || dest.sedes[0];
    const nuevos = [...new Set([...(ss.alias || []), src.nombre.toUpperCase()])].filter((x) => !ds.alias.includes(x));
    ds.alias.push(...nuevos);
    if (ds.lat == null && ss.lat != null) { ds.lat = ss.lat; ds.lng = ss.lng; ds.ubic = ss.ubic; }
    if (!ds.dir && ss.dir) ds.dir = ss.dir;
    return { de: { t: src.nombre, s: ss.nombre }, a: { t: dest.nombre, s: ds.nombre }, destSedeId: ds.id, alias: nuevos };
  });
  c.revisar = (c.revisar || []).map((r) => catNorm(r.taller) === catNorm(src.nombre) ? { ...r, taller: dest.nombre, sede: (pares.find((p) => catNorm(p.de.s) === catNorm(r.sede)) || pares[0]).a.s } : r);
  c.talleres = c.talleres.filter((t) => t.id !== srcId);
  c.unidos = [...(c.unidos || []), { id: catId('u'), fecha: Date.now(), src, destId, pares }];
  saveCatalogo(c); return true;
}
function catUnirSede(tallerId, srcSedeId, destSedeId) {
  const c = JSON.parse(JSON.stringify(loadCatalogo()));
  const t = c.talleres.find((z) => z.id === tallerId); if (!t) return false;
  const ss = t.sedes.find((z) => z.id === srcSedeId), ds = t.sedes.find((z) => z.id === destSedeId); if (!ss || !ds || ss === ds) return false;
  const nuevos = [...new Set(ss.alias || [])].filter((x) => !ds.alias.includes(x)); ds.alias.push(...nuevos);
  if (ds.lat == null && ss.lat != null) { ds.lat = ss.lat; ds.lng = ss.lng; ds.ubic = ss.ubic; }
  if (!ds.dir && ss.dir) ds.dir = ss.dir;
  t.sedes = t.sedes.filter((z) => z.id !== srcSedeId);
  c.revisar = (c.revisar || []).map((r) => catNorm(r.taller) === catNorm(t.nombre) && catNorm(r.sede) === catNorm(ss.nombre) ? { ...r, sede: ds.nombre } : r);
  c.unidos = [...(c.unidos || []), { id: catId('u'), fecha: Date.now(), tipo: 'sede', src: ss, destId: tallerId, pares: [{ de: { t: t.nombre, s: ss.nombre }, a: { t: t.nombre, s: ds.nombre }, destSedeId: ds.id, alias: nuevos }] }];
  saveCatalogo(c); return true;
}
function catDeshacerUnion(id) {
  const c = JSON.parse(JSON.stringify(loadCatalogo())); const u = (c.unidos || []).find((x) => x.id === id); if (!u) return false;
  const dest = c.talleres.find((t) => t.id === u.destId);
  if (dest) u.pares.forEach((p) => { const ds = dest.sedes.find((z) => z.id === p.destSedeId); if (ds) ds.alias = ds.alias.filter((x) => !p.alias.includes(x)); });
  if (u.tipo === 'sede') { if (dest && !dest.sedes.some((z) => catNorm(z.nombre) === catNorm(u.src.nombre))) dest.sedes.push(u.src); }
  else if (!c.talleres.some((t) => catNorm(t.nombre) === catNorm(u.src.nombre))) c.talleres.push(u.src);
  c.talleres.sort((x, y) => x.nombre.localeCompare(y.nombre, 'es'));
  c.unidos = c.unidos.filter((x) => x.id !== id);
  saveCatalogo(c); return true;
}
// 27/11/2026: datos que le faltan a un taller activo (para los filtros de Catálogos)
const catSinUbic = (s) => s.lat == null || s.lng == null;
const catSinDir = (s) => !String(s.dir || '').trim();
const catFaltaUbic = (t) => t.on !== false && !esParticular(t.nombre) && t.sedes.some(catSinUbic);
const catFaltaDir = (t) => t.on !== false && !esParticular(t.nombre) && t.sedes.some(catSinDir);
const CAT_FALTA = { bg: '#fdf0d5', fg: '#8a5a00', bd: '#f0d9a8' };
function CatTagFalta({ txt }) { return <span style={{ fontSize: 10.5, fontWeight: 700, borderRadius: 999, padding: '2px 8px', whiteSpace: 'nowrap', background: CAT_FALTA.bg, color: CAT_FALTA.fg, border: `1px solid ${CAT_FALTA.bd}` }}>{txt}</span>; }
function catTagsTaller(t, sinDir) {
  if (t.on === false || esParticular(t.nombre)) return [];
  const nU = t.sedes.filter(catSinUbic).length, nD = t.sedes.filter(catSinDir).length; const out = [];
  if (nU) out.push(t.sedes.length > 1 ? `${nU} sin ubicación` : 'Sin ubicación');
  if (nD && sinDir !== false) out.push(t.sedes.length > 1 ? `${nD} sin dirección` : 'Sin dirección');
  return out;
}
function CatValorSede({ s, activo, k }) {
  const falta = (txt) => <b style={{ fontWeight: 700, color: activo ? CAT_FALTA.fg : TOKENS.textSubtle }}>{activo ? txt : (k === 'dir' ? 'Sin dirección' : 'Sin ubicación')}</b>;
  if (k === 'dir') return s.dir ? <b style={{ fontWeight: 600, color: TOKENS.text }}>{s.dir}</b> : falta('Falta');
  if (!catSinUbic(s)) return <a href={s.ubic || `https://maps.google.com/?q=${s.lat},${s.lng}`} target="_blank" rel="noopener noreferrer" style={{ color: TOKENS.primary, fontWeight: 700, textDecoration: 'none' }}>Abrir en Maps ›</a>;
  return <span>{falta(s.ubic ? 'Falta · el enlace no trae coordenadas' : 'Falta · pega el enlace de Maps o usa "Estoy aquí"')}{s.ubic && <> · <a href={s.ubic} target="_blank" rel="noopener noreferrer" style={{ color: TOKENS.primary, fontWeight: 700, textDecoration: 'none' }}>Abrir enlace ›</a></>}</span>;
}
const CAT_CIUDADES_CO = ['Armenia', 'Barranquilla', 'Bogotá', 'Bucaramanga', 'Buenaventura', 'Buga', 'Cartagena', 'Cartago', 'Cúcuta', 'Florencia', 'Girardot', 'Ibagué', 'Ipiales', 'Jamundí', 'Manizales', 'Medellín', 'Montería', 'Neiva', 'Palmira', 'Pasto', 'Pereira', 'Popayán', 'Quibdó', 'Riohacha', 'Santa Marta', 'Sincelejo', 'Tuluá', 'Tunja', 'Valledupar', 'Villavicencio', 'Yumbo', 'Zarzal'];

// ─── Admin: Mi perfil › Catálogos ───
function CatalogosScreen({ onBack, inicial }) {
  const [cat, update] = useCatalogo();
  const [v, setV] = React.useState(inicial === 'revisar' ? { s: 'rev' } : { s: 'list' });
  const [tab, setTab] = React.useState('t');
  const [q, setQ] = React.useState('');
  const [fT, setFT] = React.useState('todos'); // todos | ub | dir | off · 27/11/2026
  const [form, setForm] = React.useState(null);
  const [confirmar, setConfirmar] = React.useState(null); // { tone, title, message, label, fn }
  const [pedir, setPedir] = React.useState(null); // { title, label, value, fn }
  const [pick, setPick] = React.useState(null); // { r, q }
  const [toast, setToast] = React.useState(null);
  const scrollRef = React.useRef(null);
  const ir = (x) => { setV(x); if (scrollRef.current) scrollRef.current.scrollTop = 0; window.scrollTo && window.scrollTo(0, 0); };
  const avisar = (msg, rojo) => { setToast({ msg, rojo }); clearTimeout(avisar.t); avisar.t = setTimeout(() => setToast(null), 2200); };
  const ask = (tone, title, message, label, fn) => setConfirmar({ tone, title, message, label, fn });
  const Modal = window.ConfirmActionModal;
  const t = v.ti != null ? cat.talleres.find((x) => x.id === v.ti) : null;
  const a = v.ai != null ? cat.aseguradoras.find((x) => x.id === v.ai) : null;
  const k = catNorm(q);
  const card = { background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 14 };
  const sl = (txt, n) => <div style={{ ...catLbl, display: 'flex', justifyContent: 'space-between', margin: '16px 2px 8px' }}><span>{txt}</span>{n != null && <span style={{ letterSpacing: 0, textTransform: 'none', fontSize: 11.5, color: TOKENS.textSubtle }}>{n}</span>}</div>;
  const fila = (key, titulo, sub, off, onClick) =>
  <button key={key} type="button" onClick={onClick} style={{ ...card, display: 'flex', alignItems: 'center', gap: 10, width: '100%', textAlign: 'left', fontFamily: 'inherit', padding: '12px 13px', marginBottom: 8, cursor: 'pointer', background: off ? TOKENS.surfaceLow : TOKENS.surface }}>
      <span style={{ flex: 1, minWidth: 0 }}>
        <b style={{ display: 'block', fontSize: 14.5, color: off ? TOKENS.textMuted : TOKENS.text }}>{titulo}{off && <CatTag>Inactivo</CatTag>}</b>
        <span style={{ display: 'block', fontSize: 12.5, color: TOKENS.textMuted, marginTop: 3 }}>{sub}</span>
      </span>
      {I.chevRight(16, TOKENS.primary)}
    </button>;
  const btnAdd = (txt, onClick) => <button type="button" onClick={onClick} style={{ display: 'block', width: '100%', marginTop: 10, border: `1px dashed ${TOKENS.borderInput}`, background: TOKENS.surface, borderRadius: 12, padding: 11, fontFamily: 'inherit', fontSize: 13.5, fontWeight: 800, color: TOKENS.primary, cursor: 'pointer' }}>＋ {txt}</button>;
  const editBtn = (onClick, txt = 'Editar') => <button type="button" onClick={onClick} style={{ border: `1px solid ${TOKENS.border}`, background: TOKENS.surface, borderRadius: 8, padding: '4px 9px', fontFamily: 'inherit', fontSize: 11.5, fontWeight: 700, color: TOKENS.primary, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 4 }}>{I.pencil(12, TOKENS.primary)} {txt}</button>;
  const aliasChips = (list, onX) => <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5, marginTop: 6 }}>{list.map((x, i) => <span key={i} style={{ fontSize: 11, fontWeight: 600, background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, color: TOKENS.textMuted, borderRadius: 7, padding: '3px 7px' }}>{x}{onX && <button type="button" onClick={() => onX(i)} aria-label="Quitar" style={{ border: 0, background: 'none', color: TOKENS.textMuted, cursor: 'pointer', padding: '0 0 0 4px', fontSize: 11 }}>✕</button>}</span>)}</div>;
  const ordenar = (c) => c.talleres.sort((x, y) => x.nombre.localeCompare(y.nombre, 'es'));
  const quitarRev = (c, id) => { c.revisar = c.revisar.filter((z) => z.id !== id); };
  const sumarAlias = (c, tn, sn, llega) => { const s = c.talleres.find((z) => z.nombre === tn)?.sedes.find((z) => z.nombre === sn); if (s && !s.alias.includes(llega)) s.alias.push(llega); };

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

  let titulo = 'Catálogos', back = onBack, body = null;
  if (v.s === 'list') {
    if (tab === 'c') {
      const l = ciuL.filter((x) => !k || catNorm(x.n).includes(k));
      body = <>
        {btnAdd('Agregar ciudad', () => pedirCiudad((n) => ir({ s: 'ciudad', cn: n })))}
        {sl('Ciudades', l.length)}
        {l.map((x) => <button key={x.n} type="button" onClick={() => ir({ s: 'ciudad', cn: x.n })} style={{ ...card, display: 'flex', alignItems: 'center', gap: 10, width: '100%', textAlign: 'left', fontFamily: 'inherit', padding: '12px 13px', marginBottom: 8, cursor: 'pointer' }}>
          <span style={{ flex: 1, minWidth: 0 }}><b style={{ display: 'block', fontSize: 14.5, color: TOKENS.text }}>{x.n}</b><span style={{ display: 'block', fontSize: 12.5, color: TOKENS.textMuted, marginTop: 3 }}>{tallCiu(x.n).length} {tallCiu(x.n).length === 1 ? 'sede' : 'sedes'}</span></span>
          <span style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 4 }}>{chipCiu(x.cob ? 'Cobertura' : 'Sin cobertura', x.cob)}{x.men && chipCiu('Mensajero', true)}</span>
          {I.chevRight(16, TOKENS.primary)}
        </button>)}
      </>;
    } else if (tab === 't') {
      const l = cat.talleres.filter((x) => !k || catNorm(x.nombre).includes(k) || x.sedes.some((s) => catNorm(s.nombre).includes(k) || s.alias.some((y) => catNorm(y).includes(k))));
      const lf = fT === 'ub' ? l.filter(catFaltaUbic) : fT === 'dir' ? l.filter(catFaltaDir) : fT === 'off' ? l.filter((x) => !x.on) : l;
      const on = lf.filter((x) => x.on), off = lf.filter((x) => !x.on);
      const tagsDe = (x) => { const tg = catTagsTaller(x, fT !== 'ub'); return tg.length ? <span style={{ display: 'flex', gap: 4, flexWrap: 'wrap', marginTop: 5 }}>{tg.map((z) => <CatTagFalta key={z} txt={z} />)}</span> : null; };
      body = <>
        {cat.revisar.length > 0 && !k &&
        <div style={{ background: catYellow.bg, border: `1px solid ${catYellow.border}`, color: catYellow.text, borderRadius: 12, padding: '11px 12px', display: 'flex', alignItems: 'center', gap: 10, marginTop: 12 }}>
            <div style={{ flex: 1, fontSize: 12.5, lineHeight: 1.4 }}><b style={{ display: 'block', fontSize: 13.5 }}>{cat.revisar.length} {cat.revisar.length === 1 ? 'nombre por revisar' : 'nombres por revisar'}</b>Llegaron en órdenes o los escribió el mensajero.</div>
            <Button style={{ padding: '9px 14px' }} onClick={() => ir({ s: 'rev' })}>Revisar</Button>
          </div>
        }
        {btnAdd('Agregar taller', () => setPedir({ title: 'Agregar taller', label: 'Nombre del taller', value: '', fn: (n) => ask('primary', 'Agregar taller', `Se agrega ${n} al catálogo. Luego le agregas sus sedes.`, 'Guardar', () => { const id = catId('t'); update((c) => { c.talleres.push({ id, nombre: n, on: true, sedes: [] }); ordenar(c); }); ir({ s: 'taller', ti: id }); avisar('Taller agregado'); }) }))}
        {fT !== 'off' && <>{sl(fT === 'ub' ? 'Con sedes sin ubicación' : fT === 'dir' ? 'Con sedes sin dirección' : 'Talleres activos', on.length)}
        {on.map((x) => fila(x.id, x.nombre, <>{catSubTaller(x)}{tagsDe(x)}</>, false, () => ir({ s: 'taller', ti: x.id })))}
        {(fT === 'ub' || fT === 'dir') && !on.length && <div style={{ padding: '18px 12px', textAlign: 'center', color: TOKENS.textMuted, fontSize: 13, background: TOKENS.surfaceLow, border: `1px dashed ${TOKENS.border}`, borderRadius: 12 }}>✓ Ningún taller pendiente.</div>}</>}
        {!l.length && <div style={{ padding: '18px 12px', textAlign: 'center', color: TOKENS.textMuted, fontSize: 13, background: TOKENS.surfaceLow, border: `1px dashed ${TOKENS.border}`, borderRadius: 12 }}>Ningún taller coincide.</div>}
        {off.length > 0 && (fT === 'todos' || fT === 'off') && <>{sl('Inactivos', off.length)}{off.map((x) => fila(x.id, x.nombre, catSubTaller(x), true, () => ir({ s: 'taller', ti: x.id })))}</>}
      </>;
    } else {
      const l = cat.aseguradoras.filter((x) => !k || catNorm(x.nombre).includes(k) || x.alias.some((y) => catNorm(y).includes(k))).slice().sort((x, y) => (y.on - x.on) || (y.c - x.c));
      body = <>
        {btnAdd('Agregar aseguradora', () => setPedir({ title: 'Agregar aseguradora', label: 'Nombre corto', value: '', fn: (n) => ask('primary', 'Agregar aseguradora', `Se agrega ${n}.`, 'Guardar', () => { update((c) => c.aseguradoras.push({ id: catId('a'), nombre: n, alias: [n.toUpperCase()], c: 0, on: true })); avisar('Aseguradora agregada'); }) }))}
        {sl('Aseguradoras', l.length)}
        {l.map((x) => fila(x.id, x.nombre, `${x.c.toLocaleString('es-CO')} registros desde 2024${x.alias.length > 1 ? ` · ${x.alias.length} nombres` : ''}`, !x.on, () => ir({ s: 'aseg', ai: x.id })))}
      </>;
    }
    body = <>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 4, background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 12, padding: 4 }}>
        {[['t', 'Talleres'], ['a', 'Aseguradoras'], ['c', 'Ciudades']].map(([id, l]) => <button key={id} type="button" onClick={() => { setTab(id); setQ(''); }} style={{ border: 0, borderRadius: 9, padding: '9px 4px', fontFamily: 'inherit', fontSize: 13.5, fontWeight: 700, cursor: 'pointer', background: tab === id ? TOKENS.primary : 'transparent', color: tab === id ? '#fff' : TOKENS.textMuted }}>{l}</button>)}
      </div>
      <CatBuscar value={q} onChange={setQ} placeholder={tab === 't' ? 'Buscar taller, sede o como llega' : tab === 'c' ? 'Buscar ciudad' : 'Buscar aseguradora'} />
      {tab === 't' && (() => { const act = cat.talleres.filter((x) => x.on && !esParticular(x.nombre)); const n = { todos: act.length, ub: act.filter(catFaltaUbic).length, dir: act.filter(catFaltaDir).length, off: cat.talleres.filter((x) => !x.on).length };
        return <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 10 }}>{[['todos', 'Todos'], ['ub', 'Sin ubicación'], ['dir', 'Sin dirección'], ['off', 'Inactivos']].map(([k2, l2]) => <button key={k2} type="button" onClick={() => setFT(k2)} style={{ border: `1px solid ${fT === k2 ? TOKENS.primary : TOKENS.borderInput}`, background: fT === k2 ? TOKENS.primary : TOKENS.surface, color: fT === k2 ? '#fff' : TOKENS.text, borderRadius: 99, padding: '6px 11px', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 700, cursor: 'pointer' }}>{l2} <span style={{ opacity: 0.7 }}>{n[k2]}</span></button>)}</div>; })()}
      {body}
    </>;
  } else if (v.s === 'ciudad') {
    const x = ciuL.find((z) => catNorm(z.n) === catNorm(v.cn)) || { n: v.cn, cob: false, men: false };
    const ts = tallCiu(x.n);
    titulo = x.n; back = () => ir({ s: 'list' });
    body = <>
      {[['cob', 'Cobertura', 'Aquí se cotiza y se repara el rin (subastas y Orbika).'], ['men', 'El mensajero recoge', 'César va en persona a los talleres de esta ciudad. Si no, los rines llegan por transportadora o los trae el taller, y al entregar se despachan por transportadora.']].map(([kk, t2, d2]) =>
      <div key={kk} style={{ ...card, display: 'flex', gap: 12, alignItems: 'flex-start', padding: '12px 13px', marginBottom: 8 }}>
          <div style={{ flex: 1 }}><b style={{ fontSize: 14, color: TOKENS.text }}>{t2} · {x[kk] ? 'Sí' : 'No'}</b><div style={{ fontSize: 12.5, color: TOKENS.textMuted, marginTop: 3, lineHeight: 1.45 }}>{d2}</div></div>
          {swCiu(!!x[kk], () => ask('primary', `${t2} · ${x.n}`, x[kk] ? `Se quita "${t2.toLowerCase()}" en ${x.n}.` : `Se activa "${t2.toLowerCase()}" en ${x.n}.`, 'Guardar', () => { cambiarCiudad(x.n, { [kk]: !x[kk] }); avisar('Ciudad actualizada'); }))}
        </div>)}
      {sl(`Sedes en ${x.n}`, ts.length)}
      {ts.map(({ x: tt, s: ss }) => fila(ss.id, `${tt.nombre} · ${ss.nombre}`, ss.dir || 'Sin dirección', false, () => ir({ s: 'taller', ti: tt.id })))}
      {!ts.length && <div style={{ padding: '18px 12px', textAlign: 'center', color: TOKENS.textMuted, fontSize: 13, background: TOKENS.surfaceLow, border: `1px dashed ${TOKENS.border}`, borderRadius: 12 }}>Ninguna sede tiene esta ciudad todavía. Se la pones al editar la sede del taller.</div>}
    </>;
  } else if (v.s === 'taller' && t) {
    titulo = t.nombre; back = () => ir({ s: 'list' });
    const upT = (fn) => update((c) => fn(c.talleres.find((x) => x.id === t.id), c));
    body = <>
      {!t.on && <div style={{ background: catYellow.bg, border: `1px solid ${catYellow.border}`, color: catYellow.text, borderRadius: 12, padding: '11px 12px', fontSize: 12.5, lineHeight: 1.4, marginBottom: 10 }}><b style={{ display: 'block', fontSize: 13.5 }}>Taller inactivo</b>No le aparece al mensajero. Los registros viejos lo conservan.</div>}
      <div style={{ ...card, padding: 12, display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ flex: 1 }}><div style={catLbl}>Taller</div><div style={{ fontSize: 16, fontWeight: 800, marginTop: 2, color: TOKENS.text }}>{t.nombre}</div></div>
        {editBtn(() => setPedir({ title: 'Nombre del taller', label: 'Nombre', value: t.nombre, fn: (n) => { if (n !== t.nombre) ask('primary', 'Guardar cambio', `El taller pasa a llamarse ${n}.`, 'Guardar', () => { upT((x, c) => { x.nombre = n; ordenar(c); }); avisar('Cambios guardados'); }); } }))}
      </div>
      {sl('Sedes', t.sedes.length)}
      {!t.sedes.length && <div style={{ padding: '18px 12px', textAlign: 'center', color: TOKENS.textMuted, fontSize: 13, background: TOKENS.surfaceLow, border: `1px dashed ${TOKENS.border}`, borderRadius: 12 }}>Este taller aún no tiene sedes.</div>}
      {t.sedes.map((s) =>
      <div key={s.id} style={{ ...card, padding: '12px 13px', marginBottom: 8, ...(t.on && !esParticular(t.nombre) && (catSinUbic(s) || catSinDir(s)) ? { borderColor: CAT_FALTA.bd } : {}) }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><b style={{ flex: 1, fontSize: 14.5, color: TOKENS.text }}>{s.nombre}</b>{editBtn(() => { setForm({ id: s.id, nombre: s.nombre, ciudad: s.ciudad || 'Cali', zona: s.zona || 'Norte', dir: s.dir || '', ubic: s.ubic, lat: s.lat, lng: s.lng, alias: [...s.alias] }); ir({ s: 'sede', ti: t.id }); })}</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'auto 1fr', gap: '5px 10px', fontSize: 12.5, marginTop: 8 }}>
            <span style={{ color: TOKENS.textMuted }}>{s.ciudad === 'Cali' ? 'Zona' : 'Ciudad'}</span><b style={{ fontWeight: 600, color: TOKENS.text }}>{s.ciudad === 'Cali' ? s.zona || '—' : s.ciudad}</b>
            <span style={{ color: TOKENS.textMuted }}>Dirección</span><CatValorSede s={s} activo={t.on} k="dir" />
            <span style={{ color: TOKENS.textMuted }}>Ubicación</span><CatValorSede s={s} activo={t.on} k="ub" />
          </div>
          {s.alias.length > 0 && <><div style={{ ...catLbl, marginTop: 10 }}>Así llega en las órdenes</div>{aliasChips(s.alias)}</>}
        </div>
      )}
      {btnAdd('Agregar sede', () => { setForm({ id: null, nombre: '', ciudad: 'Cali', zona: 'Norte', dir: '', ubic: null, lat: null, lng: null, alias: [] }); ir({ s: 'sede', ti: t.id }); })}
      <div style={{ marginTop: 22 }}>
        {t.on ?
        <Button variant="danger" full onClick={() => ask('danger', 'Desactivar taller', `${t.nombre} deja de aparecerle al mensajero. Los registros viejos lo conservan y puedes reactivarlo cuando quieras.`, 'Desactivar', () => { upT((x) => { x.on = false; }); avisar('Taller desactivado', true); })}>Desactivar taller</Button> :
        <Button full onClick={() => ask('primary', 'Reactivar taller', `${t.nombre} vuelve a aparecerle al mensajero.`, 'Reactivar', () => { upT((x) => { x.on = true; }); avisar('Taller reactivado'); })}>Reactivar taller</Button>}
      </div>
    </>;
  } else if (v.s === 'sede' && t && form) {
    titulo = form.id ? 'Editar sede' : 'Nueva sede'; back = () => ir({ s: 'taller', ti: t.id });
    const f = form, setF = (p) => setForm({ ...f, ...p });
    const estoyAqui = () => {
      if (!navigator.geolocation) { avisar('Este celular no comparte la ubicación', true); return; }
      navigator.geolocation.getCurrentPosition((p) => { const lat = +p.coords.latitude.toFixed(6), lng = +p.coords.longitude.toFixed(6); setForm((x) => ({ ...x, lat, lng, ubic: `https://maps.google.com/?q=${lat},${lng}`, ubicTipo: 'aqui', pegar: false })); },
      () => avisar('No se pudo tomar la ubicación', true), { enableHighAccuracy: true, timeout: 12000 });
    };
    const usarEnlace = () => {
      const l = (f.enlace || '').trim();
      if (!/^https?:\/\//.test(l)) { avisar('Pega un enlace que empiece por https://', true); return; }
      const co = catCoordsDeEnlace(l); setF({ ubic: l, lat: co ? co.lat : null, lng: co ? co.lng : null, ubicTipo: 'link', pegar: false, enlace: '' });
    };
    body = <>
      <div style={{ fontSize: 12.5, color: TOKENS.textMuted }}>{t.nombre}</div>
      <div style={{ marginTop: 12 }}><div style={{ ...catLbl, marginBottom: 5 }}>Nombre de la sede</div><input value={f.nombre} onChange={(e) => setF({ nombre: e.target.value })} placeholder="Ej: Norte, Kia, Calle 26" style={catInput} /></div>
      <div style={{ marginTop: 12 }}><div style={{ ...catLbl, marginBottom: 5 }}>Ciudad</div><div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>{catCiudades().map((x) => x.n).map((c) => <button key={c} type="button" onClick={() => setF({ ciudad: c })} style={catChip(f.ciudad === c)}>{c}</button>)}<button type="button" onClick={() => pedirCiudad((n) => setF({ ciudad: n }))} style={{ ...catChip(false), borderStyle: 'dashed', color: TOKENS.primary }}>＋ Otra ciudad</button></div></div>
      {f.ciudad === 'Cali' && <div style={{ marginTop: 12 }}><div style={{ ...catLbl, marginBottom: 5 }}>Zona</div><div style={{ display: 'flex', gap: 6 }}>{['Norte', 'Sur'].map((z) => <button key={z} type="button" onClick={() => setF({ zona: z })} style={catChip(f.zona === z)}>{z}</button>)}</div></div>}
      <div style={{ marginTop: 12 }}><div style={{ ...catLbl, marginBottom: 5 }}>Dirección</div><input value={f.dir} onChange={(e) => setF({ dir: e.target.value })} placeholder="Ej: Av. 3N #44-90" style={catInput} /></div>
      <div style={{ marginTop: 12 }}><div style={{ ...catLbl, marginBottom: 5 }}>Ubicación</div>
        {f.ubic ?
        <div style={{ ...card, display: 'flex', alignItems: 'center', gap: 8, padding: '10px 12px' }}><span style={{ flex: 1, fontSize: 13, fontWeight: 700, color: TOKENS.text, display: 'flex', alignItems: 'center', gap: 6 }}>{I.pin(15, TOKENS.primary)} {f.ubicTipo === 'aqui' ? 'Tomada aquí con el celular' : 'Enlace de Google Maps'}</span>{editBtn(() => setF({ ubic: null, lat: null, lng: null }), 'Cambiar')}</div> :
        f.pegar ?
        <><input autoFocus value={f.enlace || ''} onChange={(e) => setF({ enlace: e.target.value })} placeholder="Pega el enlace de Google Maps" style={catInput} />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 8 }}><Button variant="outline" onClick={() => setF({ pegar: false })}>Cancelar</Button><Button onClick={usarEnlace}>Usar enlace</Button></div></> :
        <><div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}><Button variant="outline" style={{ color: TOKENS.primary, padding: '11px 8px', fontSize: 13 }} onClick={() => setF({ pegar: true })}>Pegar enlace de Maps</Button><Button variant="outline" style={{ color: TOKENS.primary, padding: '11px 8px', fontSize: 13 }} icon={I.pin(15, TOKENS.primary)} onClick={estoyAqui}>Estoy aquí</Button></div>
            <div style={{ fontSize: 11.5, color: TOKENS.textMuted, marginTop: 6, lineHeight: 1.4 }}>"Estoy aquí" toma la ubicación del celular; úsalo parado en el taller.</div></>
        }
      </div>
      {f.alias.length > 0 && <div style={{ marginTop: 12 }}><div style={catLbl}>Así llega en las órdenes</div>{aliasChips(f.alias, (i) => setF({ alias: f.alias.filter((_, j) => j !== i) }))}</div>}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 22 }}>
        <Button variant="outline" full onClick={back}>Cancelar</Button>
        <Button full disabled={!f.nombre.trim()} onClick={() => ask('primary', 'Guardar sede', `${t.nombre} · ${f.nombre.trim()} (${f.ciudad === 'Cali' ? f.zona : f.ciudad})`, 'Guardar', () => {
          const o = { id: f.id || catId('s'), nombre: f.nombre.trim(), ciudad: f.ciudad, zona: f.ciudad === 'Cali' ? f.zona : null, dir: f.dir.trim(), ubic: f.ubic, lat: f.lat, lng: f.lng, alias: f.alias };
          update((c) => { const x = c.talleres.find((z) => z.id === t.id); const i = x.sedes.findIndex((z) => z.id === o.id); if (i >= 0) x.sedes[i] = o; else x.sedes.push(o); if (f.rv) quitarRev(c, f.rv); });
          ir({ s: 'taller', ti: t.id }); avisar('Sede guardada');
        })}>Guardar</Button>
      </div>
      {f.id && <div style={{ marginTop: 14 }}><Button variant="danger" full onClick={() => ask('danger', 'Quitar sede', `Se quita ${f.nombre} de ${t.nombre}. Los registros viejos la conservan.`, 'Quitar', () => { update((c) => { const x = c.talleres.find((z) => z.id === t.id); x.sedes = x.sedes.filter((z) => z.id !== f.id); }); ir({ s: 'taller', ti: t.id }); avisar('Sede quitada', true); })}>Quitar sede</Button></div>}
    </>;
  } else if (v.s === 'aseg' && a) {
    titulo = a.nombre; back = () => ir({ s: 'list' });
    const f = form && form.aid === a.id ? form : { aid: a.id, nombre: a.nombre, alias: [...a.alias], nuevo: '' };
    const setF = (p) => setForm({ ...f, ...p });
    body = <>
      <div style={{ ...card, padding: 12 }}>
        <div style={{ ...catLbl, marginBottom: 5 }}>Nombre corto</div><input value={f.nombre} onChange={(e) => setF({ nombre: e.target.value })} style={catInput} />
        <div style={{ ...catLbl, marginTop: 12 }}>Así llega en las órdenes</div>
        {aliasChips(f.alias, f.alias.length > 1 ? (i) => setF({ alias: f.alias.filter((_, j) => j !== i) }) : null)}
        <div style={{ display: 'flex', gap: 8, marginTop: 8 }}><input value={f.nuevo} onChange={(e) => setF({ nuevo: e.target.value })} placeholder="Agregar otro nombre" style={catInput} /><Button variant="outline" style={{ color: TOKENS.primary, padding: '0 14px' }} onClick={() => { const x = f.nuevo.trim(); if (x) setF({ alias: [...f.alias, x.toUpperCase()], nuevo: '' }); }}>＋</Button></div>
        {a.alias.some((x) => /liberty/i.test(x)) && <div style={{ fontSize: 11.5, color: TOKENS.textMuted, marginTop: 6 }}>Liberty ahora es HDI: sus registros viejos se ven como HDI.</div>}
      </div>
      <div style={{ fontSize: 12.5, color: TOKENS.textMuted, marginTop: 10 }}>{a.c.toLocaleString('es-CO')} registros desde 2024</div>
      <div style={{ marginTop: 18 }}><Button full disabled={!f.nombre.trim()} onClick={() => ask('primary', 'Guardar aseguradora', `${f.nombre.trim()} · ${f.alias.length} ${f.alias.length === 1 ? 'nombre' : 'nombres'} como llega.`, 'Guardar', () => { update((c) => { const x = c.aseguradoras.find((z) => z.id === a.id); x.nombre = f.nombre.trim(); x.alias = f.alias; }); setForm(null); avisar('Cambios guardados'); })}>Guardar</Button></div>
      <div style={{ marginTop: 12 }}>
        {a.on ?
        <Button variant="danger" full onClick={() => ask('danger', 'Desactivar aseguradora', `${a.nombre} deja de aparecer al registrar. Los registros viejos la conservan.`, 'Desactivar', () => { update((c) => { c.aseguradoras.find((z) => z.id === a.id).on = false; }); avisar('Aseguradora desactivada', true); })}>Desactivar aseguradora</Button> :
        <Button full onClick={() => ask('primary', 'Reactivar aseguradora', `${a.nombre} vuelve a aparecer al registrar.`, 'Reactivar', () => { update((c) => { c.aseguradoras.find((z) => z.id === a.id).on = true; }); avisar('Aseguradora reactivada'); })}>Reactivar aseguradora</Button>}
      </div>
    </>;
  } else if (v.s === 'rev') {
    titulo = 'Por revisar'; back = inicial === 'revisar' ? onBack : () => ir({ s: 'list' });
    const tallerExiste = (n) => cat.talleres.find((z) => z.nombre === n);
    body = <>
      <div style={{ fontSize: 12.5, color: TOKENS.textMuted, lineHeight: 1.45, marginBottom: 10 }}>Al confirmar, ese nombre queda guardado en "Así llega en las órdenes" de la sede.</div>
      {!cat.revisar.length && <div style={{ padding: '18px 12px', textAlign: 'center', color: TOKENS.textMuted, fontSize: 13, background: TOKENS.surfaceLow, border: `1px dashed ${TOKENS.border}`, borderRadius: 12 }}>✓ No hay nada por revisar.</div>}
      {cat.revisar.map((r) => {
        const tx = tallerExiste(r.taller);
        const sinSede = r.motivo === 'sinsede';
        const nuevaSede = () => { setForm({ id: null, rv: r.id, nombre: '', ciudad: 'Cali', zona: 'Norte', dir: '', ubic: null, lat: null, lng: null, alias: [r.llega] }); ir({ s: 'sede', ti: tx.id }); };
        return (
          <div key={r.id} style={{ ...card, padding: '12px 13px', marginBottom: 8 }}>
            <div style={catLbl}>{r.motivo === 'mens' ? `Escrito por ${r.porNombre || 'el mensajero'}` : 'Llega como'}</div>
            <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 12.5, marginTop: 3, wordBreak: 'break-word', color: TOKENS.text }}>{r.llega}</div>
            {r.placa && <div style={{ fontSize: 11.5, color: TOKENS.textMuted, marginTop: 3 }}>En la recogida de <b style={{ fontFamily: "'JetBrains Mono', monospace", color: TOKENS.text }}>{r.placa}</b></div>}
            <div style={{ fontSize: 13.5, fontWeight: 700, marginTop: 8, color: TOKENS.text }}>
              <span style={{ color: TOKENS.textMuted, fontWeight: 600 }}>{r.motivo === 'mens' ? 'Taller nuevo' : sinSede ? 'Taller' : 'Se asigna a'}: </span>
              {r.taller}{r.sede && !sinSede ? ' · ' + r.sede : ''}{sinSede && <CatTag y>Falta sede</CatTag>}
            </div>
            <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
              {r.motivo === 'mens' ? <>
                  <Button variant="outline" style={{ flex: 1, color: TOKENS.primary, padding: '10px 6px', fontSize: 13 }} onClick={() => setPick({ r, q: '' })}>Asignar a uno existente</Button>
                  <Button style={{ flex: 1, padding: '10px 6px', fontSize: 13 }} onClick={() => ask('primary', 'Crear taller', `Se agrega ${r.taller}${r.sede && r.sede !== 'Sin sede' ? ' · ' + r.sede : ''} al catálogo. Luego le completas zona y ubicación.`, 'Guardar', () => { const id = catId('t'); update((c) => { c.talleres.push({ id, nombre: r.taller, on: true, sedes: [{ id: catId('s'), nombre: r.sede && r.sede !== 'Sin sede' ? r.sede : 'Principal', ciudad: 'Cali', zona: null, dir: '', ubic: null, lat: null, lng: null, alias: [r.llega] }] }); ordenar(c); quitarRev(c, r.id); }); ir({ s: 'taller', ti: id }); avisar('Taller creado'); })}>Crear taller</Button>
                </> :
              !sinSede ? <>
                  <Button variant="outline" style={{ flex: 1, color: TOKENS.primary, padding: '10px 6px', fontSize: 13 }} onClick={() => setPick({ r, q: '' })}>Cambiar</Button>
                  <Button style={{ flex: 1, padding: '10px 6px', fontSize: 13 }} onClick={() => ask('primary', 'Confirmar', `${r.llega} se guarda como ${r.taller} · ${r.sede}.`, 'Confirmar', () => { update((c) => { sumarAlias(c, r.taller, r.sede, r.llega); quitarRev(c, r.id); }); avisar('Guardado'); })}>Confirmar</Button>
                </> : <>
                  {tx && tx.sedes.length > 0 && <Button variant="outline" style={{ flex: 1, color: TOKENS.primary, padding: '10px 6px', fontSize: 13 }} onClick={() => setPick({ r, q: r.taller })}>Asignar sede</Button>}
                  {tx && <Button style={{ flex: 1, padding: '10px 6px', fontSize: 13 }} onClick={nuevaSede}>Crear sede</Button>}
                </>}
            </div>
            <button type="button" onClick={() => ask('danger', 'Descartar', 'Se quita de Por revisar y no se agrega al catálogo. Los registros que lo usan no cambian. Si vuelve a llegar en una orden o recogida nueva, aparece otra vez.', 'Descartar', () => { update((c) => quitarRev(c, r.id)); avisar('Descartado'); })} style={{ marginTop: 8, border: 0, background: 'none', color: TOKENS.danger, fontFamily: 'inherit', fontSize: 12.5, fontWeight: 700, cursor: 'pointer', padding: 0 }}>Descartar</button>
          </div>);
      })}
    </>;
  }

  const pickRes = [];
  if (pick) { const pk = catNorm(pick.q); cat.talleres.forEach((x) => { if (!x.on) return; x.sedes.forEach((s) => { if (!pk || catNorm(x.nombre + ' ' + s.nombre).includes(pk)) pickRes.push({ x, s }); }); }); }

  return (
    <div style={{ background: TOKENS.bg, display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
      <AppHeader title={titulo} onBack={back} right={null} bell={false} />
      <div ref={scrollRef} style={{ flex: 1, padding: '12px 16px 28px', overflow: 'auto' }}>{body}</div>
      {pick &&
      <CatHoja title="Asignar a…" onClose={() => setPick(null)} alto>
          <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 12, color: TOKENS.textMuted, marginTop: 8 }}>{pick.r.llega}</div>
          <CatBuscar value={pick.q} onChange={(x) => setPick({ ...pick, q: x })} placeholder="Buscar taller o sede" />
          {pickRes.slice(0, 40).map(({ x, s }) => <CatResultado key={s.id} titulo={`${x.nombre} · ${s.nombre}`} sub={catSedeSub(s)} onClick={() => { const r = pick.r; setPick(null); ask('primary', 'Asignar', `${r.llega} se guarda como ${x.nombre} · ${s.nombre}.`, 'Guardar', () => { update((c) => { sumarAlias(c, x.nombre, s.nombre, r.llega); quitarRev(c, r.id); }); avisar('Guardado'); }); }} />)}
        </CatHoja>
      }
      {pedir &&
      <div onClick={() => setPedir(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(11,28,48,0.5)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }}>
          <div onClick={(e) => e.stopPropagation()} style={{ background: TOKENS.surface, borderRadius: 16, padding: '20px 18px', width: '100%', maxWidth: 340 }}>
            <div style={{ fontSize: 17, fontWeight: 700, color: TOKENS.text }}>{pedir.title}</div>
            <div style={{ ...catLbl, margin: '14px 0 5px' }}>{pedir.label}</div>
            <input autoFocus list={pedir.sug ? 'cat-ciudades-co' : undefined} value={pedir.value} onChange={(e) => setPedir({ ...pedir, value: e.target.value })} style={catInput} />{pedir.sug && <datalist id="cat-ciudades-co">{CAT_CIUDADES_CO.filter((n) => !ciuL.some((z) => catNorm(z.n) === catNorm(n))).map((n) => <option key={n} value={n} />)}</datalist>}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 16 }}>
              <Button variant="outline" full onClick={() => setPedir(null)}>Cancelar</Button>
              <Button full disabled={!pedir.value.trim()} onClick={() => { const n = pedir.value.trim(), fn = pedir.fn; setPedir(null); fn(n); }}>Seguir</Button>
            </div>
          </div>
        </div>
      }
      {confirmar && Modal &&
      <Modal tone={confirmar.tone} title={confirmar.title} message={confirmar.message} confirmLabel={confirmar.label}
      icon={confirmar.tone === 'danger' ? I.alert(24, TOKENS.danger) : I.check(24, TOKENS.primary)}
      onDismiss={() => setConfirmar(null)} onConfirm={() => { const fn = confirmar.fn; setConfirmar(null); fn(); }} />
      }
      {toast &&
      <div style={{ position: 'fixed', left: 16, right: 16, bottom: 20, maxWidth: 408, margin: '0 auto', background: toast.rojo ? TOKENS.dangerText : TOKENS.primary, color: '#fff', borderRadius: 12, padding: '11px 14px', fontSize: 13, fontWeight: 700, zIndex: 1100, boxShadow: '0 8px 20px rgba(11,28,48,.25)' }}>{toast.msg}</div>
      }
    </div>);
}

// Migración única (13/11/2026): los datos de prueba usaban talleres inventados; pasan a talleres reales.
(function catMigrarDemo() {
  const FLAG = 'rodando.migr.talleresReales';
  try { if (localStorage.getItem(FLAG)) return; } catch (e) { return; }
  const M = { 'almotor|norte': ['Almotores', 'Kia'], 'almotor|sur': ['Almotores', 'Volkswagen'], 'almotor|centro': ['Almotores', 'Renault'],
    'servitire|sur': ['Mazko', 'Sur'], 'servitire|norte': ['Mazko', 'Norte'], 'tecnirin|centro': ['Autopacífico', 'Norte'],
    'llantamax|calle 80': ['Autosuperior', 'Norte'], 'auto centro|norte': ['Coches de la Sabana', '8va'],
    'arautos sur|sur': ['Arautos', 'Sur'], 'renovautos|los cambulos': ['Renovautos', 'Sur'] };
  const fix = (o) => {
    if (Array.isArray(o)) { o.forEach(fix); return; }
    if (!o || typeof o !== 'object') return;
    if (typeof o.taller === 'string') { const m = M[(o.taller + '|' + (o.sede || '')).toLowerCase()]; if (m) { o.taller = m[0]; o.sede = m[1]; } }
    Object.values(o).forEach((v) => { if (v && typeof v === 'object') fix(v); });
  };
  ['rodando.paradas.v2', 'rodando.pendientes', 'rodando.entregados', 'rodando.recogidos', 'rodando.tiempos', 'rodando.notificaciones', 'rodando.solicitudesAnulacion', 'rodando.anulaciones'].forEach((k) => {
    try { const raw = localStorage.getItem(k); if (!raw) return; const v = JSON.parse(raw); fix(v); localStorage.setItem(k, JSON.stringify(v)); } catch (e) {}
  });
  try { localStorage.setItem(FLAG, '1'); } catch (e) {}
})();

Object.assign(window, { CLIENTE_PARTICULAR, esParticular,
  loadCatalogo, saveCatalogo, useCatalogo, catTalleresSedes, catAseguradoras, catAseguradoraCorta,
  catUbicacion, catPendientesMensajero, catAgregarRevision, catCoordsDeEnlace,
  catTallerOpciones, catSedesDe, CatalogosScreen, catSinUbic, catSinDir, catFaltaUbic, catFaltaDir, catTagsTaller, CatTagFalta, CatValorSede, CAT_FALTA,
  catCiudades, catCiudadInfo, catGuardarCiudades, catGuardarUbicacion, catCoordsDeTexto, catCanon, catCanonObj, catUnirTaller, catUnirSede, catDeshacerUnion, catMensajeroRecoge, catSedesRuta, catTallerOpcionesRuta, CAT_CIUDADES_CO
});
