// Recoger (main capture form) + Grabar (review before save)

// ─── Catálogos ───────────────────────────────────────────────────────────
// Talleres/sedes y aseguradoras viven en catalogo.jsx (13/11/2026), editables en Mi perfil › Catálogos.
// Taller escrito por el mensajero (13/11/2026): al guardar la recogida le llega al admin en Catálogos › Por revisar.
function avisarTallerNuevo(state) {
  if (!state.tallerNuevo || !window.catAgregarRevision) return;
  const u = window.usuarioActual ? window.usuarioActual() : null;
  window.catAgregarRevision({ llega: state.taller + (state.sede ? ' · ' + state.sede : ''), taller: state.taller, sede: state.sede, motivo: 'mens', por: u && u.usuario, porNombre: u && (u.nombre || u.usuario), placa: state.placa });
}
// Tamaños 12 a 22 (solo número)
const RIN_TAMANOS = Array.from({ length: 11 }, (_, i) => String(i + 12));
const RIN_MATERIALES = ['Aluminio', 'Maquinado', 'Hierro', 'Acero', 'Cromado']; // orden pedido 14/11/2026
const RIN_HUECOS = ['3H', '4H', '5H', '6H', '8H', '10H'];

// Máscara de DOT: mayúsculas + solo alfanumérico, tope 13 caracteres.
// Sin espacios salvo uno antes de los últimos 4 dígitos (la fecha de fab.):
// "1P50326B3 0620".
const DOT_MAXLEN = 13;
function maskDot(v) {
  // DOT en formato LIBRE: solo forzamos mayúsculas (el mensajero escribe tal cual).
  return String(v || '').toUpperCase();
}
// Marca de llanta: Capitalize (Title Case) — "MICHELIN"/"michelin" → "Michelin".
function capWords(s) { return String(s || '').toLowerCase().replace(/\b\w/g, function (c) { return c.toUpperCase(); }); }

// ─── Excepciones por cantidad (12/11/2026) ──────────────────────────────
// Valor común + "Algunas tienen otro DOT / otra calidad". Reglas:
//  · Una diferencia igual al valor común no es diferencia: avisa y no deja confirmar.
//  · Siempre queda al menos 1 llanta con el valor común (diferencias ≤ cantidad − 1).
//  · Al confirmar (Listo) se unen filas con el mismo valor y el panel se pliega en el
//    mismo recuadro de la ficha ("DOT por llanta"), que incluye el valor común.
//  · DOT nuevo: llega pre-escrito con el común (suele cambiar 1–2 dígitos) y una ✕ para borrarlo.
const normEx = (v) => (v || '').trim().toUpperCase();
const AMARILLO = { bg: '#fff2cc', fg: '#7f6000' };
function exUsed(exceptions) { return exceptions.reduce((s, e) => s + (Number(e.count) || 0), 0); }
function repartoEx(total, comun, exceptions) {
  const n = Math.max(1, Number(total) || 1);
  const out = [];
  const add = (v, c) => {if (!normEx(v) || !c) return;const f = out.find((x) => normEx(x[0]) === normEx(v));if (f) f[1] += c;else out.push([v, c]);};
  add(comun, n - exUsed(exceptions));
  exceptions.forEach((e) => add(e.value, Number(e.count) || 0));
  return out;
}
function ExceptionsEditor({ kind, total, comun, exceptions, onChange, open, setOpen, titulo }) {
  const n = Math.max(1, Number(total) || 1);
  const used = exUsed(exceptions);
  const rem = n - used;
  const libre = rem - 1; // siempre queda ≥1 con el valor común
  const isDot = kind === 'dot';

  // Si baja la cantidad, recorta las diferencias para que siempre quede 1 con el común.
  React.useEffect(() => {
    if (used > n - 1 && exceptions.length) {
      const next = exceptions.map((e) => ({ ...e }));
      let extra = used - (n - 1);
      for (let i = next.length - 1; i >= 0 && extra > 0; i--) {
        const quita = Math.min(extra, next[i].count);next[i].count -= quita;extra -= quita;
      }
      onChange(next.filter((e) => e.count > 0));
    }
  }, [n]);

  const add = () => {if (libre <= 0) return;onChange([...exceptions, { count: 1, value: isDot ? comun || '' : '', touched: false }]);setOpen(true);};
  const update = (i, patch) => onChange(exceptions.map((e, j) => j === i ? { ...e, ...patch } : e));
  const remove = (i) => {const next = exceptions.filter((_, j) => j !== i);onChange(next);if (!next.length) setOpen(false);};
  const igual = (e) => normEx(e.value) && normEx(e.value) === normEx(comun);
  const ok = exceptions.length > 0 && exceptions.every((e) => normEx(e.value) && !igual(e));
  const confirmar = () => {
    if (!ok) return;
    const out = [];
    exceptions.forEach((e) => {const f = out.find((x) => normEx(x.value) === normEx(e.value));if (f) f.count += e.count;else out.push({ count: e.count, value: e.value.trim() });});
    onChange(out);setOpen(false);
  };

  if (exceptions.length === 0) {
    return (
      <button type="button" onClick={add} disabled={libre <= 0} style={{
        display: 'inline-flex', alignItems: 'center', gap: 6, background: 'transparent', border: 'none', padding: '2px 0',
        color: TOKENS.primary, fontSize: 12.5, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit'
      }}>{I.plus(14, TOKENS.primary)}<span>{isDot ? 'Algunas tienen otro DOT' : 'Algunas tienen otra calidad'}</span></button>);
  }

  // Plegado: el mismo recuadro de la ficha, con Editar.
  if (!open) {
    return <RepartoBox titulo={`${titulo} por llanta`} filas={repartoEx(n, comun, exceptions)} mono={isDot} onEditar={() => setOpen(true)} />;
  }

  const miniBtn = (dis) => ({ border: 'none', background: 'transparent', width: 30, height: 32, fontSize: 18, color: dis ? '#9aa6b6' : TOKENS.primary, cursor: dis ? 'not-allowed' : 'pointer', fontFamily: 'inherit' });
  return (
    <div style={{ background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 12, padding: 10 }}>
      <div style={{ fontSize: 10.5, fontWeight: 800, color: TOKENS.textMuted, letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 4 }}>{titulo} diferente</div>
      {exceptions.map((ex, i) =>
      <div key={i} style={{ borderTop: i ? `1px dashed ${TOKENS.border}` : 'none', marginTop: i ? 8 : 0, paddingTop: i ? 2 : 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 6 }}>
            <div style={{ display: 'flex', alignItems: 'center', border: `1px solid ${TOKENS.borderInput}`, borderRadius: 9, background: TOKENS.surfaceLow, flex: 'none' }}>
              <button type="button" disabled={ex.count <= 1} onClick={() => update(i, { count: ex.count - 1 })} style={miniBtn(ex.count <= 1)}>−</button>
              <b style={{ minWidth: 18, textAlign: 'center', fontSize: 14, color: TOKENS.text }}>{ex.count}</b>
              <button type="button" disabled={libre <= 0} onClick={() => update(i, { count: ex.count + 1 })} style={miniBtn(libre <= 0)}>+</button>
            </div>
            <span style={{ flex: 1, fontSize: 12.5, color: TOKENS.textMuted, fontWeight: 600 }}>{ex.count === 1 ? 'llanta con' : 'llantas con'}</span>
            <button type="button" aria-label="Quitar fila" onClick={() => remove(i)} style={{ flex: 'none', width: 32, height: 32, borderRadius: 8, border: 'none', background: TOKENS.surfaceLow, cursor: 'pointer', display: 'grid', placeItems: 'center' }}>{I.trash(15, TOKENS.danger)}</button>
          </div>
          <div style={{ marginTop: 12 }}>
            {isDot ?
          <div style={{ position: 'relative' }}>
                <TextInput value={ex.value} onChange={(v) => update(i, { value: v, touched: true })} transform={maskDot} placeholder="Escribe el otro DOT" style={{ paddingRight: 34, fontFamily: 'monospace', fontSize: 13.5 }} />
                {ex.value &&
            <button type="button" onClick={() => update(i, { value: '', touched: true })} aria-label="Borrar DOT" title="Borrar para escribir uno totalmente distinto" style={{
              position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)', width: 20, height: 20, padding: 0,
              border: 'none', background: 'transparent', color: TOKENS.text, fontSize: 13, fontWeight: 700, cursor: 'pointer'
            }}>✕</button>}
              </div> :
          <ChipGroup small options={LLANTA_CALIDAD} disabledOptions={[comun]} value={ex.value} onChange={(v) => update(i, { value: v, touched: true })} />
          }
          </div>
          {igual(ex) &&
        <div style={{ marginTop: 6, fontSize: 11.5, fontWeight: 600, borderRadius: 8, padding: '5px 8px', background: AMARILLO.bg, color: AMARILLO.fg }}>
              {isDot && !ex.touched ?
          'Cambia los dígitos que son distintos (o toca ✕ si es un DOT totalmente diferente).' :
          `Es igual al ${isDot ? 'DOT' : 'valor'} común: no es diferente. Cámbialo o quita la fila.`}
            </div>
        }
        </div>
      )}
      <div style={{ marginTop: 10, paddingTop: 8, borderTop: `1px dashed ${TOKENS.border}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, fontSize: 12, color: TOKENS.textMuted }}>
        <span>{rem === 1 ? 'La otra llanta lleva ' : `Las otras ${rem} llantas llevan `}<b style={{ color: TOKENS.text }}>{comun || '—'}</b></span>
        <button type="button" onClick={add} disabled={libre <= 0} style={{
          flex: 'none', whiteSpace: 'nowrap', background: 'transparent', border: 'none', padding: 0, fontFamily: 'inherit',
          color: libre <= 0 ? TOKENS.textSubtle : TOKENS.primary, fontSize: 12.5, fontWeight: 700, cursor: libre <= 0 ? 'not-allowed' : 'pointer'
        }}>＋ Otra</button>
      </div>
      <div style={{ marginTop: 8, paddingTop: 8, borderTop: `1px dashed ${TOKENS.border}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10 }}>
        <span style={{ fontSize: 11.5, color: TOKENS.textMuted }}>{ok ? 'Confirma para contraer.' : 'Completa o corrige cada fila.'}</span>
        <button type="button" disabled={!ok} onClick={confirmar} style={{
          flex: 'none', display: 'inline-flex', alignItems: 'center', gap: 6, border: 'none', borderRadius: 9, padding: '8px 14px',
          background: ok ? TOKENS.primary : TOKENS.surfaceLow, color: ok ? '#fff' : TOKENS.textSubtle,
          fontSize: 13, fontWeight: 700, cursor: ok ? 'pointer' : 'not-allowed', fontFamily: 'inherit'
        }}>{I.check(15, ok ? '#fff' : TOKENS.textSubtle)} Listo</button>
      </div>
    </div>);
}
const SI_NO = ['Sí', 'No'];
const LLANTA_CALIDAD = ['Nueva', 'Usada', 'Mala'];

// Empty product form
const EMPTY_FORM = {
  tipo: '', // '' | 'rin' | 'llanta' | 'valvula'
  cantidad: 1,
  // rin
  tamano: '', material: '', huecos: '', tapa: '', tapaValvula: '',
  // llanta
  marca: '', referencia: '', dot: '', calidad: '',
  // Excepciones por cantidad (mismo valor común salvo estas):
  dotExceptions: [], // [{ count, dot }]
  calidadExceptions: [], // [{ count, calidad }]
  // valvula
  valvulaSensor: ''
};

// ─── Consecutive code generator (persisted to localStorage) ──────────────
function getNextCode() {
  try {
    const cur = parseInt(localStorage.getItem('rodando.code') || '6000', 10);
    const next = cur + 1;
    localStorage.setItem('rodando.code', String(next));
    return String(next);
  } catch (e) {
    return String(Math.floor(6000 + Math.random() * 999));
  }
}

// ─── Recoger Screen ─────────────────────────────────────────────────────
function RecogerScreen({ state, setState, onCancel, onGrabar, onNav, editingItem, onExitEdit, editingMeta, onEditItem, modificando, onVolverResumen }) {
  const [showCancel, setShowCancel] = React.useState(false);
  const [modoGar, setModoGar] = React.useState(false); // Recoger › Garantía (16/11/2026)
  const [showSaveConfirm, setShowSaveConfirm] = React.useState(false);
  const [resumenIdx, setResumenIdx] = React.useState(0);
  const [photos, setPhotos] = React.useState([]); // dataURLs (sin huecos)
  const [verFoto, setVerFoto] = React.useState(null); // índice de la foto abierta en grande
  const [showObs, setShowObs] = React.useState(false);
  const [exOpen, setExOpen] = React.useState({ dot: false, cal: false });
  const [warn, setWarn] = React.useState('');
  const [placaTouched, setPlacaTouched] = React.useState(false);
  const [editMode, setEditMode] = React.useState(false);
  const [confirmDelete, setConfirmDelete] = React.useState(null); // item id pending delete
  const [pendingEditId, setPendingEditId] = React.useState(null); // switch-edit guard
  const productoRef = React.useRef(null);

  // Placa/VIN validation (Colombia)
  const isVin = state.idType === 'vin';
  const placaInvalid = isVin ?
  state.placa.length > 0 && !isVinValido(state.placa) :
  state.placa.length > 0 && !isPlacaValida(state.placa);
  const placaErrorMsg = placaTouched && placaInvalid ?
  isVin ? 'El VIN debe ser alfanumérico (A-Z, 0-9).' : PLACA_ERROR_MSG :
  null;

  const [form, setForm] = React.useState(editingItem ? { ...EMPTY_FORM, ...editingItem } : { ...EMPTY_FORM });

  // Seed form / photos / showObs from editingItem when it changes
  React.useEffect(() => {
    if (editingItem) {
      setForm({ ...EMPTY_FORM, ...editingItem });
      setExOpen({ dot: false, cal: false });
      setPhotos((editingItem.photos || []).filter(Boolean));
      setShowObs(!!editingItem.observaciones);
    } else {
      // entering fresh mode
      setForm({ ...EMPTY_FORM });
      setPhotos([]);
      setShowObs(false);
    }
  }, [editingItem?.id]);

  const setField = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  // When an item is loaded for editing (here or from Grabar), reveal edit controls.
  React.useEffect(() => {if (editingItem) setEditMode(true);}, [editingItem?.id]);

  const scrollToProducto = () => {
    setTimeout(() => {
      const el = productoRef.current;
      if (el) {
        const y = el.getBoundingClientRect().top + window.scrollY - 12;
        try {window.scrollTo({ top: Math.max(0, y), behavior: 'smooth' });} catch (e) {window.scrollTo(0, Math.max(0, y));}
      }
    }, 60);
  };
  // Guarded edit: if another item is mid-edit (unsaved), warn before switching.
  const requestEdit = (id) => {
    if (editingItem && editingItem.id !== id) {setPendingEditId(id);return;}
    onEditItem && onEditItem(id);
    scrollToProducto();
  };
  const doDelete = (id) => {
    setState((s) => ({ ...s, items: (s.items || []).filter((x) => x.id !== id) }));
    setResumenIdx((i) => Math.max(0, Math.min(i, items.length - 2)));
    if (editingItem && editingItem.id === id) onExitEdit && onExitEdit();
    setConfirmDelete(null);
  };

  // Fotos de la PLACA (12/11/2026): se guardan en el ticket, no en cada registro.
  const fotosList = (state.fotosPlaca || []).filter(Boolean);
  const photosOk = fotosList.length >= 1;
  const setFotosPlaca = (fn) => setState((s) => ({ ...s, fotosPlaca: fn((s.fotosPlaca || []).filter(Boolean)) }));
  const [cambioTipo, setCambioTipo] = React.useState(null);
  const [confirmarGuardar, setConfirmarGuardar] = React.useState(false);
  const [sinAgregar, setSinAgregar] = React.useState(false); // producto en el formulario sin "Agregar registro"
  const [confirmarSalir, setConfirmarSalir] = React.useState(false);
  const [confirmarNav, setConfirmarNav] = React.useState(null); // pantalla a la que se quiso ir en modo modificar
  const [confirmarFoto, setConfirmarFoto] = React.useState(null); // índice de la foto a quitar
  // Modo modificar (desde Revisar recogida): misma pantalla, otro título, ← / ✕ vuelven al resumen.
  const cambiosMod = modificando ? diffRecogida(modificando, state) : [];
  const salir = () => {
    if (modificando) {if (cambiosMod.length) setConfirmarSalir(true);else onVolverResumen && onVolverResumen(false);return;}
    setShowCancel(true);
  }; // producto al que se quiere pasar con datos sin agregar
  const [verFotoSrc, setVerFotoSrc] = React.useState(null);
  const enCurso = window.getRutaEnCurso ? window.getRutaEnCurso() : null;
  // Opción B: al editar un ENTREGADO, items y comprobante quedan bloqueados.
  const lockItems = !!(editingMeta && editingMeta.wasDelivered);

  const items = state.items || [];
  React.useEffect(() => {
    // Keep resumen index in valid range
    if (resumenIdx >= items.length) setResumenIdx(Math.max(0, items.length - 1));
  }, [items.length]);

  const formValid = (() => {
    if (!form.tipo) return false;
    if (form.tipo === 'rin') return form.tamano && form.material && form.huecos && form.tapa && form.tapaValvula;
    if (form.tipo === 'llanta') {
      if (!(form.marca && form.referencia)) return false;
      const n = Math.max(1, Number(form.cantidad) || 1);
      // Validate one dimension's "common value + exceptions":
      // exceptions can't exceed the total; each must have count≥1 and a value;
      // the common value is required whenever any unit falls in the remainder.
      const dimOk = (common, exceptions) => {
        const used = exceptions.reduce((s, e) => s + (Number(e.count) || 0), 0);
        if (used > n) return false;
        if (exceptions.some((e) => !(Number(e.count) >= 1) || !(e.value || '').trim())) return false;
        if (n - used > 0 && !(common || '').trim()) return false; // remainder needs a common value
        return true;
      };
      return dimOk(form.dot, form.dotExceptions) && dimOk(form.calidad, form.calidadExceptions);
    }
    if (form.tipo === 'valvula') return form.valvulaSensor;
    return false;
  })();

  // ¿Hay datos del producto actual sin agregar? (cualquier campo distinto del formulario vacío)
  const formSucio = !editingItem && Object.keys(EMPTY_FORM).some((k) => {
    if (k === 'tipo') return false;
    const v = form[k],e = EMPTY_FORM[k];
    if (Array.isArray(e)) return Array.isArray(v) && v.length > 0;
    if (k === 'cantidad') return Number(v) > 1;
    return v !== e && v !== undefined && v !== '';
  }) || !!(form.observaciones && form.observaciones.trim());
  const pasarA = (v, agregar) => {
    if (agregar) commitItem();
    setForm({ ...EMPTY_FORM, tipo: v });setExOpen({ dot: false, cal: false });setShowObs(false);setCambioTipo(null);
  };
  const puedeGuardar = items.length > 0 && (photosOk || !!editingMeta);
  const faltantes = (() => {
    const f = [];
    if (form.tipo === 'rin') {if (!form.tamano) f.push('tamaño');if (!form.material) f.push('material');if (!form.huecos) f.push('huecos');if (!form.tapa) f.push('tapa');if (!form.tapaValvula) f.push('tapa válvula');}
    if (form.tipo === 'llanta') {if (!form.marca) f.push('marca');if (!form.referencia) f.push('referencia');if (!formValid && form.marca && form.referencia) f.push('DOT o calidad');}
    if (form.tipo === 'valvula' && !form.valvulaSensor) f.push('sensor');
    return f;
  })();

  // Header (top) fields validation — required before product can be added
  const placaOk = isVin ? isVinValido(state.placa) : isPlacaValida(state.placa);
  const partic = !!(window.esParticular && window.esParticular(state.taller));
  const cli = state.cliente || {};
  const clienteOk = !partic || ((cli.nombre || '').trim() && (cli.telefono || '').trim().length >= 7 && (cli.direccion || '').trim());
  const topFieldsComplete = state.placa && placaOk && (state.aseguradora || partic) && (state.taller || '').trim() && (state.sede || state.tallerNuevo || partic) && clienteOk;
  const missingTop = !topFieldsComplete;

  // When editing, skip photo requirement (photos persist on item, not in form state)
  const canAgregar = formValid; // ya no pide foto por registro

  const onAgregar = () => {
    // If editing, ask confirmation first
    if (editingItem) {
      setShowSaveConfirm(true);
      return;
    }
    commitItem();
  };

  const commitItem = () => {
    const item = { ...form, photos: editingItem ? (editingItem.photos || []).filter(Boolean) : [], id: editingItem ? editingItem.id : 'i' + Date.now() };
    // Normalize per-quantity exceptions: drop empties, and if exceptions cover
    // every unit, fold the most common one back into the default so a single
    // value never shows as a redundant "exception".
    if (item.tipo === 'llanta') {
      const clean = (exceptions, comun) => {
        const out = [];
        (Array.isArray(exceptions) ? exceptions : []).
        map((e) => ({ count: Number(e.count) || 0, value: (e.value || '').trim() })).
        filter((e) => e.count > 0 && e.value !== '' && normEx(e.value) !== normEx(comun)).
        forEach((e) => {const f = out.find((x) => normEx(x.value) === normEx(e.value));if (f) f.count += e.count;else out.push(e);});
        return out;
      };
      item.dotExceptions = clean(item.dotExceptions, item.dot);
      item.calidadExceptions = clean(item.calidadExceptions, item.calidad);
    }
    setState((s) => {
      const existing = s.items || [];
      if (editingItem) {
        return { ...s, items: existing.map((x) => x.id === item.id ? item : x) };
      }
      return { ...s, items: [...existing, item] };
    });
    if (editingItem) {
      // Show the edited item in resumen
      const idx = items.findIndex((x) => x.id === editingItem.id);
      if (idx >= 0) setResumenIdx(idx);
      // Clear edit mode and stay on Recoger — sale del modo edición
      // automáticamente, sin requerir un clic extra en "Listo".
      setShowSaveConfirm(false);
      setEditMode(false);
      onExitEdit && onExitEdit();
    } else {
      // Reset for next item
      // Formulario en blanco y sin producto escogido (12/11/2026).
      setForm({ ...EMPTY_FORM });
      setExOpen({ dot: false, cal: false });
      setPhotos([]);
      setShowObs(false);
      setTimeout(() => setResumenIdx(items.length), 0);
    }
  };

  // ─── Photo capture (camera or file) ────────────────────────────────
  const fileRefs = React.useRef([]);
  const openPhotoPicker = (i) => fileRefs.current[i]?.click();
  const onPhotoChange = (i, file) => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = async () => {const s = await window.downscaleDataURL(reader.result, 1100, 0.6);setPhotos((arr) => arr.map((v, j) => j === i ? s : v));};
    reader.readAsDataURL(file);
  };
  const addPhotoFromFile = (file) => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = async () => {const s = await window.downscaleDataURL(reader.result, 1100, 0.6);setFotosPlaca((arr) => arr.length >= 10 ? arr : [...arr, s]);};
    reader.readAsDataURL(file);
  };

  // Nueva recogida / Garantía: el taller devuelve un rin ya entregado (16/11/2026).
  const puedeGar = !editingItem && !editingMeta && !modificando && !!window.GarantiaRecogerMovil;
  const segGar = puedeGar &&
  <div style={{ display: 'flex', background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 12, padding: 3, gap: 3, marginBottom: 12 }}>
      {[[false, 'Nueva recogida'], [true, '↺ Garantía']].map(([v, l]) =>
    <button key={l} type="button" onClick={() => setModoGar(v)} style={{ flex: 1, border: 0, borderRadius: 9, padding: '9px 8px', fontFamily: 'inherit', fontSize: 13.5, fontWeight: 800, cursor: 'pointer', background: modoGar === v ? TOKENS.surface : 'transparent', color: modoGar === v ? (v ? '#0e7490' : TOKENS.primary) : TOKENS.textMuted, boxShadow: modoGar === v ? '0 1px 3px rgba(11,28,48,.12)' : 'none' }}>{l}</button>)}
    </div>;
  if (puedeGar && modoGar) return (
    <div style={{ background: TOKENS.bg, display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
      <AppHeader title="Recoger" onBack={() => setModoGar(false)} />
      <div style={{ padding: '14px 16px 24px', flex: 1 }}>{segGar}<window.GarantiaRecogerMovil onListo={() => setModoGar(false)} /></div>
      <div style={{ position: 'sticky', bottom: 0, zIndex: 20 }}><BottomNav current="recoger" onNav={onNav} /></div>
    </div>);

  return (
    <div style={{ background: TOKENS.bg, display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
      <AppHeader title={editingItem ? 'Editar item' : modificando ? 'Modificar recogida' : editingMeta ? 'Editar registro' : 'Recoger'} onBack={salir} hideRuta={!editingMeta && !modificando && !!enCurso} />
      <div style={{ padding: '14px 16px 16px' }}>
        {segGar}

        {/* Contexto de ruta: parada en curso (12/11/2026) */}
        {!editingMeta && enCurso &&
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10,
          background: TOKENS.cautionBg, border: `1px solid ${TOKENS.caution}`, color: TOKENS.cautionText,
          borderRadius: 10, padding: '7px 10px', fontSize: 12, fontWeight: 700
        }}>
            <span style={{ width: 7, height: 7, borderRadius: 999, background: TOKENS.cautionText, animation: 'rdBlink 1.4s infinite', flexShrink: 0 }} />
            En curso: {enCurso.taller}{enCurso.sede ? ' · ' + enCurso.sede : ''}
          </div>
        }

        {/* Banner de edición admin */}
        {editingMeta &&
        <div style={{
          background: editingMeta.wasDelivered ? TOKENS.dangerBg : TOKENS.warningBg,
          border: `1px solid ${editingMeta.wasDelivered ? TOKENS.dangerBorder : TOKENS.warningBorder}`,
          borderRadius: 12, padding: '12px 14px', marginBottom: 14,
          display: 'flex', gap: 12, alignItems: 'flex-start'
        }}>
            <div style={{
            width: 32, height: 32, borderRadius: 999,
            background: editingMeta.wasDelivered ? TOKENS.danger : TOKENS.warning,
            color: editingMeta.wasDelivered ? '#fff' : TOKENS.warningText, display: 'flex', alignItems: 'center', justifyContent: 'center',
            flexShrink: 0, fontWeight: 700
          }}>!</div>
            <div style={{ fontSize: 12, color: editingMeta.wasDelivered ? TOKENS.danger : TOKENS.warningText, lineHeight: 1.5 }}>
              <b style={{ display: 'block', marginBottom: 2, fontSize: 13 }}>
                {editingMeta.wasDelivered ?
              'Editando un registro ENTREGADO' :
              'Editando un registro existente'}
              </b>
              {editingMeta.wasDelivered ?
            <>Este registro ya fue entregado. Por seguridad solo puedes corregir los <b>datos de identificación</b> (placa, aseguradora, taller, sede). Los <b>items y el comprobante firmado no se modifican</b>. La acción quedará auditada.</> :
            <>Los cambios sobrescribirán la información actual del registro ({state.codigo}).</>
            }
            </div>
          </div>
        }

        {/* Fecha + consecutivo en una línea */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', fontSize: 12.5, color: TOKENS.textMuted, margin: '0 2px 10px' }}>
          <span style={{ fontFeatureSettings: '"tnum"' }}>{state.fecha}</span>
          <span>Orden <b style={{ fontFamily: "'JetBrains Mono', monospace", color: TOKENS.text, fontSize: 13.5 }}>{state.codigo}</b></span>
        </div>

        {/* Placa/VIN + Aseguradora (13/11/2026: aseguradoras del catálogo, ordenadas por uso) */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 12 }}>
          <div>
            {/* Label dropdown: switch Placa <-> VIN — small trigger, styled popover */}
            <IdTypeDropdown
              value={state.idType}
              onChange={(v) => {setPlacaTouched(false);setState((s) => ({ ...s, idType: v, placa: '' }));}} />
            
            <TextInput
              value={state.placa}
              onChange={(v) => setState((s) => ({ ...s, placa: v }))}
              onBlur={() => setPlacaTouched(true)}
              placeholder={isVin ? '1HGBH41JXMN109186' : 'ABC123'}
              transform={sanitizeAlnum}
              maxLength={isVin ? undefined : 6}
              upper
              error={placaErrorMsg} />
            
          </div>
          <div>
            <FieldLabel>Aseguradora</FieldLabel>
            {partic ? <div style={{ border: `1px solid ${TOKENS.border}`, background: TOKENS.surfaceLow, borderRadius: 10, padding: '11px 12px', fontSize: 14, color: TOKENS.textSubtle }}>No aplica</div> :
            <Select value={state.aseguradora} options={window.catAseguradoras ? window.catAseguradoras().map((a) => a.nombre) : []}
            placeholder="Seleccionar" searchable
            onChange={(v) => setState((s) => ({ ...s, aseguradora: v }))} />}
          </div>
        </div>

        {/* Taller + Sede. Taller busca también por cómo llega en la orden; una sola sede se llena sola.
            "¿No está?" → campos de texto, queda por revisar y le llega al admin al guardar. */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: state.tallerNuevo ? 8 : 14 }}>
          <div>
            <FieldLabel>Taller</FieldLabel>
            {state.tallerNuevo ?
            <TextInput value={state.taller} onChange={(v) => setState((s) => ({ ...s, taller: v }))} placeholder="Como aparece en la orden" /> :
            <Select value={state.taller} options={window.catTallerOpciones ? window.catTallerOpciones() : []}
            placeholder="Seleccionar" searchable popWidth="calc(200% + 12px)"
            onChange={(v) => setState((s) => { const ss = window.catSedesDe ? window.catSedesDe(v) : []; const pa = window.esParticular && window.esParticular(v); return { ...s, taller: v, sede: pa ? '' : v === s.taller ? s.sede : ss.length === 1 ? ss[0] : '', ...(pa ? { aseguradora: '', cliente: s.cliente || { nombre: '', telefono: '', direccion: '' } } : { cliente: undefined }) }; })}
            footer={(q, cerrar) =>
            <button type="button" onClick={() => { cerrar(); setState((s) => ({ ...s, tallerNuevo: true, taller: q.trim().toUpperCase(), sede: '' })); }} style={{ border: 0, borderTop: `1px solid ${TOKENS.border}`, background: 'none', marginTop: 4, padding: '10px 8px 6px', fontFamily: 'inherit', fontSize: 13, fontWeight: 800, color: TOKENS.primary, cursor: 'pointer', textAlign: 'left' }}>¿No está? Escribir otro taller</button>
            } />
            }
          </div>
          <div>
            <FieldLabel>Sede</FieldLabel>
            {partic ? <div style={{ border: `1px solid ${TOKENS.border}`, background: TOKENS.surfaceLow, borderRadius: 10, padding: '11px 12px', fontSize: 14, color: TOKENS.textSubtle }}>No aplica</div> :
            state.tallerNuevo ?
            <TextInput value={state.sede} onChange={(v) => setState((s) => ({ ...s, sede: v }))} placeholder="Opcional" /> :
            <DisabledSelect
              value={state.sede}
              options={state.taller && window.catSedesDe ? window.catSedesDe(state.taller) : []}
              placeholder="Seleccionar"
              disabled={!state.taller}
              onChange={(v) => setState((s) => ({ ...s, sede: v }))} />
            }
          </div>
        </div>
        {partic &&
        <div style={{ background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 12, padding: '10px 12px', marginBottom: 14 }}>
            <div style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: '.06em', color: TOKENS.textMuted, marginBottom: 6 }}>CLIENTE</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
              <TextInput value={cli.nombre || ''} onChange={(v) => setState((s) => ({ ...s, cliente: { ...(s.cliente || {}), nombre: v } }))} placeholder="Nombre" />
              <TextInput value={cli.telefono || ''} onChange={(v) => setState((s) => ({ ...s, cliente: { ...(s.cliente || {}), telefono: v.replace(/[^\d ]/g, '') } }))} placeholder="Teléfono" />
            </div>
            <div style={{ marginTop: 8 }}><TextInput value={cli.direccion || ''} onChange={(v) => setState((s) => ({ ...s, cliente: { ...(s.cliente || {}), direccion: v } }))} placeholder="Dirección · ej. Cra 100 # 11-60, apto 302" /></div>
          </div>
        }
        {state.tallerNuevo &&
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14, fontSize: 11.5, color: TOKENS.textMuted }}>
            <span style={{ fontSize: 10.5, fontWeight: 600, borderRadius: 999, padding: '2px 8px', background: '#fff2cc', color: '#7f6000', border: '1px solid #ecd98f', whiteSpace: 'nowrap' }}>Nuevo · por revisar</span>
            <span style={{ flex: 1 }}>El admin lo revisa.</span>
            <button type="button" onClick={() => setState((s) => ({ ...s, tallerNuevo: false, taller: '', sede: '' }))} style={{ border: 0, background: 'none', padding: 0, fontFamily: 'inherit', fontSize: 12, fontWeight: 700, color: TOKENS.primary, cursor: 'pointer', whiteSpace: 'nowrap' }}>Volver a la lista</button>
          </div>
        }

        {/* Express (16/11/2026): el taller pidió entregarla primero; plazo más corto. */}
        <button type="button" onClick={() => setState((s) => ({ ...s, express: !s.express }))} style={{ display: 'flex', alignItems: 'center', gap: 12, width: '100%', textAlign: 'left', border: `1.5px solid ${state.express ? '#e879b0' : TOKENS.border}`, background: state.express ? '#fce7f3' : TOKENS.surface, borderRadius: 12, padding: '11px 14px', marginBottom: 14, cursor: 'pointer', fontFamily: 'inherit' }}>
          <span style={{ fontSize: 19 }}>⚡</span>
          <span style={{ flex: 1 }}><b style={{ display: 'block', fontSize: 14, color: TOKENS.text }}>Express</b><span style={{ fontSize: 12, color: TOKENS.textMuted }}>El taller pidió entregarla primero</span></span>
          <span style={{ width: 40, height: 22, borderRadius: 99, background: state.express ? '#be185d' : TOKENS.borderInput, position: 'relative', flexShrink: 0, transition: 'background .15s' }}><span style={{ position: 'absolute', top: 2, left: state.express ? 20 : 2, width: 18, height: 18, borderRadius: 99, background: '#fff', transition: 'left .15s' }} /></span>
        </button>

        {/* Producto a recoger card */}
        <Card forwardedRef={productoRef} style={{ marginBottom: 14, position: 'relative', opacity: missingTop || lockItems ? 0.55 : 1 }}>
          {lockItems &&
          <div style={{
            position: 'absolute', inset: 0, zIndex: 6, cursor: 'not-allowed', borderRadius: 14,
            background: 'rgba(255,255,255,0.35)',
            display: 'flex', alignItems: 'flex-start', justifyContent: 'center', paddingTop: 16
          }}>
              <div style={{
              background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 10,
              padding: '8px 12px', fontSize: 12, fontWeight: 600, color: TOKENS.textMuted,
              display: 'flex', gap: 6, alignItems: 'center', boxShadow: '0 4px 12px rgba(11,28,48,0.12)'
            }}>
                {I.lock ? I.lock(14, TOKENS.textMuted) : '🔒'}
                <span>Items bloqueados · registro entregado</span>
              </div>
            </div>
          }
          {missingTop &&
          <div
            onClick={(e) => {
              e.stopPropagation();
              const missing = [];
              if (!state.placa) missing.push(state.idType === 'vin' ? 'VIN' : 'Placa');else
              if (!placaOk) {setPlacaTouched(true);missing.push((isVin ? 'VIN' : 'Placa') + ' (formato inválido)');}
              if (!state.aseguradora && !partic) missing.push('Aseguradora');
              if (!state.taller) missing.push('Taller');
              if (!state.sede && !state.tallerNuevo && !partic) missing.push('Sede');
              if (partic && !clienteOk) missing.push('Datos del cliente');
              setWarn(`Completa primero: ${missing.join(', ')}`);
              setTimeout(() => setWarn(''), 3500);
            }}
            style={{
              position: 'absolute', inset: 0, zIndex: 5,
              cursor: 'not-allowed', borderRadius: 14
            }} />

          }
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
            <div style={{ fontSize: 15, fontWeight: 700, color: TOKENS.text }}>Producto a recoger</div>
            <div style={{ fontSize: 11, color: TOKENS.textMuted, fontWeight: 600 }}>
              {editingItem ? `Editando #${(items.findIndex((x) => x.id === editingItem.id) + 1).toString().padStart(2, '0')}` : `${items.length + 1}.º item`}
            </div>
          </div>
          <div style={{ borderTop: `1px solid ${TOKENS.border}`, marginBottom: 12 }} />

          {/* Producto: tres botones (12/11/2026) */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6 }}>
            {[['rin', 'Rin'], ['llanta', 'Llanta'], ['valvula', 'Válvula']].map(([v, l]) =>
            <ChipBtn key={v} big on={form.tipo === v} onClick={() => {
              if (form.tipo === v) return;
              if (form.tipo && formSucio) {setCambioTipo(v);return;}
              setForm({ ...EMPTY_FORM, tipo: v });setExOpen({ dot: false, cal: false });
            }}>{l}</ChipBtn>
            )}
          </div>
          <Seccion titulo="Cantidad">
            <div style={{ width: 150 }}>
              <DisabledableStepper value={form.cantidad} onChange={(v) => setField('cantidad', v)} disabled={!form.tipo} />
            </div>
          </Seccion>

          {/* RIN fields */}
          {form.tipo === 'rin' &&
          <React.Fragment>
              <Seccion titulo="Tamaño"><ChipGroup scroll options={RIN_TAMANOS} value={form.tamano} onChange={(v) => setField('tamano', v)} suffix={'"'} /></Seccion>
              <Seccion titulo="Material"><ChipGroup options={RIN_MATERIALES} value={form.material} onChange={(v) => setField('material', v)} /></Seccion>
              <Seccion titulo="Huecos"><ChipGroup options={RIN_HUECOS} value={form.huecos} onChange={(v) => setField('huecos', v)} /></Seccion>
              <div style={{ borderTop: `1px solid ${TOKENS.border}`, paddingTop: 12, marginTop: 14, display: 'flex', justifyContent: 'space-between' }}>
                <div>
                  <SeccionTitulo>Tapa</SeccionTitulo>
                  <ChipGroup options={SI_NO} value={form.tapa} onChange={(v) => setField('tapa', v)} />
                </div>
                <div style={{ textAlign: 'right' }}>
                  <SeccionTitulo>T. válvula</SeccionTitulo>
                  <ChipGroup options={SI_NO} value={form.tapaValvula} onChange={(v) => setField('tapaValvula', v)} />
                </div>
              </div>
            </React.Fragment>
          }

          {/* LLANTA fields */}
          {form.tipo === 'llanta' &&
          <React.Fragment>
              <div style={{ borderTop: `1px solid ${TOKENS.border}`, paddingTop: 12, marginTop: 14, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                <div>
                  <FieldLabel upper>Marca</FieldLabel>
                  <TextInput value={form.marca} onChange={(v) => setField('marca', v)} transform={capWords} placeholder="Ej: Michelin" />
                </div>
                <div>
                  <FieldLabel upper>Referencia</FieldLabel>
                  <TextInput value={form.referencia} onChange={(v) => setField('referencia', String(v).toUpperCase())} placeholder="205/55 R16" />
                </div>
              </div>
              {(() => {
              const multi = Number(form.cantidad) > 1;
              const secc = (kind, tit, comunNode, ex, field, comun) => {
                const plegado = multi && ex.length > 0 && !exOpen[kind];
                const titulo = !multi ? tit : plegado ? tit : ex.length ? `${tit} de las demás` : `${tit} (común a las ${form.cantidad})`;
                return (
                  <Seccion titulo={titulo}>
                    {!plegado && comunNode}
                    {multi &&
                    <div style={{ marginTop: plegado ? 0 : 8 }}>
                        <ExceptionsEditor kind={kind} total={form.cantidad} comun={comun} titulo={tit}
                      exceptions={ex} onChange={(v) => setField(field, v)}
                      open={exOpen[kind]} setOpen={(o) => setExOpen((s) => ({ ...s, [kind]: o }))} />
                      </div>}
                  </Seccion>);
              };
              return (
                <React.Fragment>
                    {secc('dot', 'DOT',
                  <TextInput value={form.dot} onChange={(v) => setField('dot', v)} transform={maskDot} placeholder="Ej: 1P50326B3 0620" style={{ fontFamily: 'monospace' }} />,
                  form.dotExceptions, 'dotExceptions', form.dot)}
                    {secc('cal', 'Calidad',
                  <ChipGroup options={LLANTA_CALIDAD} value={form.calidad} onChange={(v) => {
                    setField('calidad', v);
                    // si una diferencia quedó igual a la nueva calidad común, se vacía
                    setField('calidadExceptions', (form.calidadExceptions || []).map((e) => e.value === v ? { ...e, value: '' } : e));
                  }} />,
                  form.calidadExceptions, 'calidadExceptions', form.calidad)}
                  </React.Fragment>);
            })()}
            </React.Fragment>
          }

          {/* VÁLVULA fields */}
          {form.tipo === 'valvula' &&
          <Seccion titulo="Válvula con sensor">
              <ChipGroup options={SI_NO} value={form.valvulaSensor} onChange={(v) => setField('valvulaSensor', v)} />
            </Seccion>
          }

          {/* Observaciones (diseño original, encima de Fotos) */}
          <div style={{ borderTop: `1px solid ${TOKENS.border}`, marginTop: 14 }} />
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            marginTop: 12, padding: '10px 12px', background: TOKENS.surfaceLow,
            borderRadius: 10, border: `1px solid ${TOKENS.border}`
          }}>
            <div>
              <div style={{ fontSize: 13, fontWeight: 600, color: TOKENS.text }}>Agregar observaciones</div>
              <div style={{ fontSize: 11, color: TOKENS.textMuted, marginTop: 2 }}>
                Notas adicionales para este item (opcional)
              </div>
            </div>
            <Toggle value={showObs} onChange={setShowObs} />
          </div>

          {showObs &&
          <textarea
            value={form.observaciones || ''}
            onChange={(e) => setField('observaciones', e.target.value)}
            placeholder="Ej: el rin presenta una abolladura en el borde…"
            rows={3}
            style={{
              marginTop: 10, width: '100%', boxSizing: 'border-box', fontFamily: 'inherit',
              border: `1px solid ${TOKENS.borderInput}`, background: TOKENS.surfaceLow,
              borderRadius: 10, padding: '10px 12px', fontSize: 14, color: TOKENS.text,
              resize: 'vertical', outline: 'none', minHeight: 70
            }} />

          }

          {/* Agregar registro en su propio espacio */}
          <div style={{ borderTop: `1px solid ${TOKENS.border}`, marginTop: 14 }} />
          <Button variant="primary" full icon={I.plus(18, '#fff')} onClick={onAgregar}
          style={{
            marginTop: 14, padding: '14px', fontSize: 15,
            opacity: canAgregar ? 1 : 0.5, cursor: canAgregar ? 'pointer' : 'not-allowed',
            pointerEvents: canAgregar ? 'auto' : 'none'
          }}>
            {editingItem ? 'Guardar cambios' : 'Agregar registro'}
          </Button>
          {editingItem &&
          <button type="button" onClick={() => {setEditMode(false);onExitEdit && onExitEdit();}} style={{
            display: 'block', margin: '8px auto 0', background: 'transparent', border: 'none', fontFamily: 'inherit',
            fontSize: 12.5, fontWeight: 700, color: TOKENS.textMuted, cursor: 'pointer'
          }}>Cancelar edición</button>}
          {!canAgregar && form.tipo && <div style={{ fontSize: 11.5, color: TOKENS.textMuted, textAlign: 'center', marginTop: 6 }}>Falta: {faltantes.join(', ')}</div>}
        </Card>

        {/* Resumen de la placa (12/11/2026): totales (CANT = solo rines) + ficha por registro */}
        <Card style={{ marginBottom: 14, padding: '14px 14px', background: TOKENS.surface, opacity: lockItems ? 0.65 : 1 }}>
          {lockItems &&
          <div style={{ fontSize: 11, fontWeight: 600, color: TOKENS.textMuted, display: 'flex', alignItems: 'center', gap: 6, marginBottom: 10 }}>
              {I.lock ? I.lock(13, TOKENS.textMuted) : '🔒'}
              <span>Solo lectura — el registro ya fue entregado</span>
            </div>
          }
          <div style={{ fontSize: 15, fontWeight: 700, color: TOKENS.text }}>Resumen de la placa</div>
          {items.length === 0 ?
          <div style={{ fontSize: 12.5, color: TOKENS.textSubtle, padding: '6px 0 0' }}>Todavía no hay registros para esta placa.</div> :
          <React.Fragment>
              <TotalesPlaca items={items} />
              {items.map((it, i) =>
            <FichaItem key={it.id} item={it} index={i}
            onFoto={(src) => setVerFotoSrc(src)}
            onEdit={!lockItems ? () => {setEditMode(true);requestEdit(it.id);} : undefined}
            onDelete={!lockItems ? () => setConfirmDelete(it.id) : undefined} />
            )}
            </React.Fragment>
          }
        </Card>

        {/* Fotos de la recogida (12/11/2026): obligatorio, mínimo 1. Documento o permiso del
            taller (si lo hay) y el conjunto desde varios ángulos. */}
        <Card style={{ marginBottom: 14, padding: '14px 14px', background: TOKENS.surface, opacity: lockItems ? 0.65 : 1 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 }}>
            <div style={{ fontSize: 15, fontWeight: 700, color: TOKENS.text }}>Fotos de la recogida</div>
            <span style={{ fontSize: 11.5, color: photosOk ? TOKENS.successText : TOKENS.textMuted, fontWeight: 700 }}>
              {fotosList.length} {fotosList.length === 1 ? 'foto' : 'fotos'} · máx 10
            </span>
          </div>
          <div style={{ fontSize: 11.5, color: TOKENS.textMuted, lineHeight: 1.4, margin: '4px 0 10px' }}>
            Obligatorio, mínimo 1. Documento o permiso de salida del taller (si lo hay) y el conjunto desde varios ángulos.
          </div>
          {fotosList.length === 0 ?
          <label style={{
            height: 140, cursor: lockItems ? 'not-allowed' : 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 6,
            border: `1.5px dashed ${TOKENS.primary}`, background: TOKENS.primaryBg, color: TOKENS.primary, borderRadius: 14
          }}>
              <input type="file" accept="image/*" multiple style={{ display: 'none' }} disabled={lockItems}
            onChange={(e) => {Array.from(e.target.files || []).slice(0, 10).forEach((f) => addPhotoFromFile(f));e.target.value = '';}} />
              {I.cam(30, TOKENS.primary)}
              <span style={{ fontSize: 15, fontWeight: 800 }}>Tomar o elegir fotos</span>
            </label> :
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
              {fotosList.map((src, i) =>
            <div key={i} style={{ position: 'relative', aspectRatio: '1' }}>
                  <img src={src} alt={`Foto ${i + 1}`} onClick={() => setVerFoto(i)}
              style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: 10, display: 'block', cursor: 'zoom-in' }} />
                  {!lockItems &&
              <button type="button" aria-label="Quitar foto" onClick={() => setConfirmarFoto(i)} style={{
                position: 'absolute', top: -6, right: -6, width: 22, height: 22, borderRadius: 999, border: 'none',
                background: '#1b2333', color: '#fff', fontSize: 12, cursor: 'pointer', display: 'grid', placeItems: 'center', padding: 0
              }}>×</button>}
                </div>
            )}
              {fotosList.length < 10 && !lockItems &&
            <label style={{
              aspectRatio: '1', cursor: 'pointer', display: 'grid', placeItems: 'center',
              border: `1.5px dashed ${TOKENS.primary}`, background: TOKENS.primaryBg, borderRadius: 10
            }}>
                  <input type="file" accept="image/*" multiple style={{ display: 'none' }}
              onChange={(e) => {Array.from(e.target.files || []).slice(0, Math.max(0, 10 - fotosList.length)).forEach((f) => addPhotoFromFile(f));e.target.value = '';}} />
                  {I.plus(24, TOKENS.primary)}
                </label>
            }
            </div>
          }
        </Card>

        {/* Acciones al final (sin barra fija, 12/11/2026) */}
        <div style={{ display: 'flex', gap: 8, marginTop: 4 }}>
          <IconAction title={modificando ? 'Volver al resumen' : 'Cancelar'} onClick={salir}>{I.x(20, TOKENS.danger)}</IconAction>
          <button type="button" disabled={!puedeGuardar} onClick={() => {
            if (!puedeGuardar) return;
            if (!placaOk) {setPlacaTouched(true);setWarn(PLACA_ERROR_MSG);setTimeout(() => setWarn(''), 3500);return;}
            if (form.tipo && formSucio) {setSinAgregar(true);return;}
            setConfirmarGuardar(true);
          }} style={{
            flex: 1, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            border: 'none', borderRadius: 12, padding: '13px', fontFamily: 'inherit', fontSize: 15, fontWeight: 800,
            background: TOKENS.primary, color: '#fff', cursor: puedeGuardar ? 'pointer' : 'not-allowed', opacity: puedeGuardar ? 1 : 0.45
          }}>{I.save(18, '#fff')} {modificando ? 'Guardar cambios' : 'Guardar'}</button>
        </div>
        {!puedeGuardar &&
        <div style={{ fontSize: 11.5, color: TOKENS.textMuted, textAlign: 'center', marginTop: 6 }}>
            Para guardar falta: {[!items.length && 'al menos 1 registro', !photosOk && !editingMeta && '1 foto de la recogida'].filter(Boolean).join(' y ')}
          </div>
        }

      </div>

      <div style={{ position: 'sticky', bottom: 0, zIndex: 20 }}>
        <BottomNav current="recoger" onNav={(id) => {if (modificando) {setConfirmarNav(id);return;}onNav(id);}} />
      </div>

      {(verFoto !== null && fotosList[verFoto] || verFotoSrc) && window.FotoGrande &&
      <window.FotoGrande src={verFotoSrc ? verFotoSrc : { src: fotosList[verFoto], list: fotosList }} onClose={() => {setVerFoto(null);setVerFotoSrc(null);}} />
      }

      {confirmarGuardar && modificando &&
      <ConfirmActionModal
        icon={I.save(24, TOKENS.primary)}
        tone="primary"
        title={cambiosMod.length ? `¿Guardar ${cambiosMod.length} ${cambiosMod.length === 1 ? 'cambio' : 'cambios'}?` : '¿Guardar sin cambios?'}
        message={cambiosMod.length ? <ListaCambios cambios={cambiosMod} /> : 'No hiciste ningún cambio. Vuelves al resumen igual que estaba.'}
        cancelLabel="Seguir modificando"
        confirmLabel="Guardar cambios"
        onConfirm={() => {setConfirmarGuardar(false);avisarTallerNuevo(state);onVolverResumen && onVolverResumen(true);}}
        onDismiss={() => setConfirmarGuardar(false)} />
      }

      {confirmarSalir &&
      <ConfirmActionModal
        icon={I.alert ? I.alert(24, TOKENS.danger) : I.x(24, TOKENS.danger)}
        tone="danger"
        title={`Tienes ${cambiosMod.length} ${cambiosMod.length === 1 ? 'cambio' : 'cambios'} sin guardar`}
        message="Si sales, se descartan y vuelves al resumen como estaba."
        cancelLabel="Seguir modificando"
        confirmLabel="Descartar cambios"
        onConfirm={() => {setConfirmarSalir(false);setState(modificando);onVolverResumen && onVolverResumen(false);}}
        onDismiss={() => setConfirmarSalir(false)} />
      }

      {confirmarNav &&
      <ConfirmActionModal
        icon={I.alert ? I.alert(24, TOKENS.danger) : I.x(24, TOKENS.danger)}
        tone="danger"
        title={`Estás modificando la recogida ${state.codigo}`}
        message="Guarda o descarta los cambios antes de salir. La recogida todavía no tiene ticket."
        cancelLabel="Seguir modificando"
        confirmLabel="Descartar y volver al resumen"
        onConfirm={() => {setConfirmarNav(null);setState(modificando);onVolverResumen && onVolverResumen(false);}}
        onDismiss={() => setConfirmarNav(null)} />
      }

      {confirmarFoto !== null &&
      <ConfirmActionModal
        icon={I.trash(24, TOKENS.danger)}
        tone="danger"
        title="¿Quitar esta foto?"
        message="La foto se elimina de la recogida."
        confirmLabel="Quitar foto"
        onConfirm={() => {const i = confirmarFoto;setConfirmarFoto(null);setFotosPlaca((arr) => arr.filter((_, j) => j !== i));}}
        onDismiss={() => setConfirmarFoto(null)} />
      }

      {/* Producto a medias al guardar (18/11/2026): no se descarta en silencio. */}
      {sinAgregar && ReactDOM.createPortal(
      <div onClick={() => setSinAgregar(false)} style={{ position: 'fixed', inset: 0, background: 'rgba(11,28,48,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1300, padding: 16 }}>
          <div onClick={(e) => e.stopPropagation()} style={{ background: TOKENS.surface, borderRadius: 16, padding: '20px 18px', width: '100%', maxWidth: 360, textAlign: 'center' }}>
            <div style={{ width: 50, height: 50, borderRadius: 999, background: '#fdf0d5', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 12px', fontSize: 22, color: '#8a5a00' }}>!</div>
            <div style={{ fontSize: 17, fontWeight: 700 }}>Tienes {{ rin: 'un rin', llanta: 'una llanta', valvula: 'una válvula' }[form.tipo] || 'un producto'} sin agregar</div>
            <div style={{ fontSize: 13, color: TOKENS.textMuted, lineHeight: 1.45, marginTop: 6 }}>{formValid ? 'Llenaste los datos pero no tocaste "Agregar registro". ¿La agregamos antes de guardar?' : `Le falta: ${faltantes.join(', ')}. Complétala o descártala.`}</div>
            <div style={{ display: 'grid', gap: 8, marginTop: 16 }}>
              {formValid && <Button variant="primary" full onClick={() => {commitItem();setForm({ ...EMPTY_FORM });setSinAgregar(false);setConfirmarGuardar(true);}}>Agregar y guardar</Button>}
              <Button variant="outline" full onClick={() => setSinAgregar(false)}>{formValid ? 'Volver a revisar' : 'Completar'}</Button>
              <Button variant="outline" full onClick={() => {setForm({ ...EMPTY_FORM });setSinAgregar(false);setConfirmarGuardar(true);}} style={{ color: TOKENS.danger, borderColor: TOKENS.borderInput, borderWidth: 1.5 }}>Descartar y guardar</Button>
            </div>
          </div>
        </div>, document.body)}
      {confirmarGuardar && !modificando &&
      <ConfirmActionModal
        icon={I.doc(24, TOKENS.primary)}
        tone="primary"
        title="¿Terminaste de registrar esta placa?"
        message="Vas a revisar el resumen antes de generar el ticket."
        cancelLabel="Seguir registrando"
        confirmLabel="Revisar resumen"
        onConfirm={() => {setConfirmarGuardar(false);avisarTallerNuevo(state);onGrabar();}}
        onDismiss={() => setConfirmarGuardar(false)} />
      }

      {cambioTipo && ReactDOM.createPortal(
        <div onClick={() => setCambioTipo(null)} style={{ position: 'fixed', inset: 0, zIndex: 1000, background: 'rgba(11,28,48,0.5)', display: 'flex', alignItems: 'flex-end', justifyContent: 'center' }}>
          <div onClick={(e) => e.stopPropagation()} style={{ background: TOKENS.surface, width: '100%', maxWidth: 440, borderRadius: '18px 18px 0 0', padding: '16px 16px 20px' }}>
            {(() => {
              const nom = (t) => t === 'rin' ? 'rin' : t === 'llanta' ? 'llanta' : 'válvula';
              const art = (t) => t === 'llanta' || t === 'valvula' ? 'una' : 'un';
              const btn = (bg, fg) => ({ display: 'block', width: '100%', border: 'none', borderRadius: 12, padding: 12, marginTop: 8, fontFamily: 'inherit', fontSize: 14.5, fontWeight: 800, cursor: 'pointer', background: bg, color: fg });
              return (
                <React.Fragment>
                  <div style={{ fontSize: 17, fontWeight: 800, color: TOKENS.text }}>Tienes {art(form.tipo)} {nom(form.tipo)} sin agregar</div>
                  <div style={{ fontSize: 13, color: TOKENS.textMuted, margin: '4px 0 6px', lineHeight: 1.45 }}>
                    {formValid ? `Está completo. ¿Lo agregas antes de pasar a ${nom(cambioTipo)}?` : `Le falta: ${faltantes.join(', ')}.`}
                  </div>
                  {formValid && <button type="button" onClick={() => pasarA(cambioTipo, true)} style={btn(TOKENS.primary, '#fff')}>Agregarlo y pasar a {nom(cambioTipo)}</button>}
                  <button type="button" onClick={() => pasarA(cambioTipo, false)} style={btn('#fdf3f1', TOKENS.dangerText)}>Descartar y pasar a {nom(cambioTipo)}</button>
                  <button type="button" onClick={() => setCambioTipo(null)} style={btn(TOKENS.surfaceLow, TOKENS.text)}>Seguir con {form.tipo === 'rin' ? 'el' : 'la'} {nom(form.tipo)}</button>
                </React.Fragment>);
            })()}
          </div>
        </div>, document.body)
      }

      {warn &&
      <div style={{
        position: 'fixed', bottom: 96, left: '50%', transform: 'translateX(-50%)',
        background: '#fff2cc', color: '#7f6000',
        padding: '12px 16px', borderRadius: 12, fontSize: 13, fontWeight: 600, zIndex: 500,
        border: '1px solid #ecd98f',
        boxShadow: '0 8px 24px rgba(127,96,0,0.18)',
        display: 'flex', alignItems: 'center', gap: 11, maxWidth: 360
      }}>
          <div style={{
            width: 24, height: 24, borderRadius: 999, flexShrink: 0,
            background: TOKENS.warning, color: '#fff', fontWeight: 800, fontSize: 15,
            display: 'flex', alignItems: 'center', justifyContent: 'center', lineHeight: 1
          }}>!</div>
          <span style={{ lineHeight: 1.4 }}>{warn}</span>
        </div>
      }

      {showSaveConfirm &&
      <ConfirmEditModal
        before={editingItem}
        after={{ ...form, photos }}
        onDismiss={() => setShowSaveConfirm(false)}
        onConfirm={commitItem} />

      }

      {showCancel && <CancelModal onDismiss={() => setShowCancel(false)} onConfirm={() => {setShowCancel(false);onCancel();}} />}

      {/* Confirmar eliminación de un item */}
      {confirmDelete != null &&
      <ConfirmActionModal
        icon={I.trash(26, TOKENS.danger)}
        tone="danger"
        title="¿Eliminar este item?"
        message="Se quitará de la recogida. Esta acción no se puede deshacer."
        confirmLabel="Eliminar"
        onConfirm={() => doDelete(confirmDelete)}
        onDismiss={() => setConfirmDelete(null)} />

      }

      {/* Cambiar de item en edición con cambios sin guardar */}
      {pendingEditId != null &&
      <ConfirmActionModal
        icon={I.pencil(24, TOKENS.primary)}
        tone="primary"
        title="Tienes cambios sin guardar"
        message="Estás editando un item y no has guardado los cambios. Si editas otro, se descartarán."
        confirmLabel="Descartar y editar"
        onConfirm={() => {
          const id = pendingEditId;
          setPendingEditId(null);
          onEditItem && onEditItem(id);
          scrollToProducto();
        }}
        onDismiss={() => setPendingEditId(null)} />

      }
    </div>);

}

const panelStyle = {
  padding: 12, background: TOKENS.surfaceLow, borderRadius: 10,
  border: `1px solid ${TOKENS.border}`
};

// ─── Placa/VIN type dropdown (small trigger, styled popover) ────────────
function IdTypeDropdown({ value, onChange }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  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]);

  const options = [
  { value: 'placa', label: 'Placa' },
  { value: 'vin', label: 'VIN' }];

  const current = options.find((o) => o.value === value) || options[0];

  return (
    <div ref={ref} style={{ position: 'relative', marginBottom: 6, display: 'inline-block' }}>
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        style={{
          display: 'inline-flex', alignItems: 'center', gap: 4,
          background: 'transparent', border: 'none', padding: 0,
          fontSize: 13, fontWeight: 600, color: TOKENS.text,
          cursor: 'pointer', fontFamily: 'inherit', outline: 'none'
        }}>
        
        {current.label}
        <svg width="10" height="6" viewBox="0 0 10 6" style={{ marginLeft: 2 }}>
          <path fill={TOKENS.textMuted} d="M0 0h10L5 6z" />
        </svg>
      </button>
      {open &&
      <div style={{
        position: 'absolute', top: 'calc(100% + 6px)', left: 0, zIndex: 50,
        minWidth: 160, background: TOKENS.surface,
        border: `1px solid ${TOKENS.border}`, borderRadius: 12,
        padding: 6, boxShadow: '0 12px 28px rgba(11,28,48,0.16)',
        display: 'flex', flexDirection: 'column', gap: 2
      }}>
          {options.map((o) => {
          const selected = o.value === value;
          return (
            <button
              key={o.value}
              type="button"
              onClick={() => {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: '10px 12px',
                background: selected ? TOKENS.surfaceLow : 'transparent',
                color: selected ? TOKENS.primary : TOKENS.text,
                border: 'none', borderRadius: 8,
                fontSize: 14, fontWeight: selected ? 700 : 500,
                cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left'
              }}>
              
                {o.label}
                {selected && I.check(14, TOKENS.primary)}
              </button>);

        })}
        </div>
      }
    </div>);

}

function DisabledSelect({ value, options, placeholder, disabled, onChange }) {
  return (
    <div style={{ opacity: disabled ? 0.55 : 1 }}>
      <Select value={value} options={options} placeholder={placeholder} disabled={disabled} onChange={onChange} />
    </div>);

}

function navBtn(disabled) {
  return {
    width: 34, height: 34, borderRadius: 999,
    background: TOKENS.surface, border: `1px solid ${TOKENS.borderInput}`,
    cursor: disabled ? 'not-allowed' : 'pointer',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    padding: 0, flexShrink: 0
  };
}

function LabelWithHelp({ text, help }) {
  return (
    <div title={help} style={{
      display: 'flex', alignItems: 'center', gap: 4, marginBottom: 6
    }}>
      <span style={{
        fontSize: 11, fontWeight: 600, color: TOKENS.textMuted,
        letterSpacing: '0.06em', textTransform: 'uppercase'
      }}>{text}</span>
      <span title={help} style={{
        width: 14, height: 14, borderRadius: 999, fontSize: 9, fontWeight: 700,
        background: TOKENS.surfaceContainer, color: TOKENS.textMuted,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        cursor: 'help'
      }}>?</span>
    </div>);

}

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

}

function PhotoSlotImg({ n, src, onClick, onRemove }) {
  if (src) {
    return (
      <div style={{
        aspectRatio: '1', borderRadius: 12, overflow: 'hidden', position: 'relative',
        border: `1px solid ${TOKENS.primary}`, background: '#000', cursor: 'pointer'
      }} onClick={onClick}>
        <img src={src} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
        <button onClick={(e) => {e.stopPropagation();onRemove();}} style={{
          position: 'absolute', top: 4, right: 4, width: 22, height: 22, borderRadius: 999,
          background: 'rgba(0,0,0,0.6)', border: 'none', color: '#fff', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0,
          fontSize: 14, fontWeight: 700, lineHeight: 1
        }}>×</button>
        <div style={{
          position: 'absolute', bottom: 0, left: 0, right: 0, padding: '2px 6px',
          background: 'linear-gradient(transparent, rgba(0,0,0,0.7))',
          color: '#fff', fontSize: 10, fontWeight: 700, textAlign: 'right'
        }}>{n}</div>
      </div>);

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

}

// ─── Cambios entre dos versiones de una recogida (12/11/2026) ───────────
// Devuelve una lista de textos ("Taller: Almotor → Llantamax", "Item 02 (Llanta): eliminado", "Fotos: +1 foto").
function diffRecogida(a, b) {
  if (!a || !b) return [];
  const out = [];
  [['placa', 'Placa'], ['aseguradora', 'Aseguradora'], ['taller', 'Taller'], ['sede', 'Sede']].forEach(([k, l]) => {
    if ((a[k] || '') !== (b[k] || '')) out.push(`${l}: ${a[k] || '—'} → ${b[k] || '—'}`);
  });
  const nom = (t) => t === 'rin' ? 'Rin' : t === 'llanta' ? 'Llanta' : 'Válvula';
  const ia = a.items || [],ib = b.items || [];
  const etiqueta = (it, lista) => `Item ${String(lista.indexOf(it) + 1).padStart(2, '0')} (${nom(it.tipo)})`;
  const CAMPOS = {
    rin: [['cantidad', 'Cantidad'], ['tamano', 'Tamaño'], ['material', 'Material'], ['huecos', 'Huecos'], ['tapa', 'Tapa'], ['tapaValvula', 'T. válvula']],
    llanta: [['cantidad', 'Cantidad'], ['marca', 'Marca'], ['referencia', 'Referencia'], ['dot', 'DOT'], ['calidad', 'Calidad']],
    valvula: [['cantidad', 'Cantidad'], ['valvulaSensor', 'Sensor']]
  };
  const exTxt = (ex) => (ex || []).map((e) => `${e.value}×${e.count}`).join(', ');
  ia.forEach((x) => {
    const y = ib.find((z) => z.id === x.id);
    if (!y) {out.push(`${etiqueta(x, ia)}: eliminado`);return;}
    (CAMPOS[x.tipo] || []).forEach(([k, l]) => {if (String(x[k] || '') !== String(y[k] || '')) out.push(`${etiqueta(y, ib)}: ${l} ${x[k] || '—'} → ${y[k] || '—'}`);});
    if (x.tipo === 'llanta') {
      if (exTxt(x.dotExceptions) !== exTxt(y.dotExceptions)) out.push(`${etiqueta(y, ib)}: DOT diferentes cambiados`);
      if (exTxt(x.calidadExceptions) !== exTxt(y.calidadExceptions)) out.push(`${etiqueta(y, ib)}: calidades diferentes cambiadas`);
    }
    if ((x.observaciones || '') !== (y.observaciones || '')) out.push(`${etiqueta(y, ib)}: observaciones cambiadas`);
  });
  ib.forEach((y) => {if (!ia.find((x) => x.id === y.id)) out.push(`${etiqueta(y, ib)}: agregado`);});
  const fa = (a.fotosPlaca || []).filter(Boolean),fb = (b.fotosPlaca || []).filter(Boolean);
  // Conteo por multiconjunto (la misma foto puede estar dos veces)
  const cuenta = (l) => l.reduce((m, f) => (m.set(f, (m.get(f) || 0) + 1), m), new Map());
  const ca = cuenta(fa),cb = cuenta(fb);
  let nuevas = 0,quitadas = 0;
  cb.forEach((n, f) => {nuevas += Math.max(0, n - (ca.get(f) || 0));});
  ca.forEach((n, f) => {quitadas += Math.max(0, n - (cb.get(f) || 0));});
  if (nuevas) out.push(`Fotos: +${nuevas} ${nuevas === 1 ? 'foto' : 'fotos'}`);
  if (quitadas) out.push(`Fotos: −${quitadas} ${quitadas === 1 ? 'foto' : 'fotos'}`);
  return out;
}
function ListaCambios({ cambios }) {
  return (
    <ul style={{ margin: '0 0 2px', paddingLeft: 18, textAlign: 'left', fontSize: 12.5, lineHeight: 1.6, color: TOKENS.text }}>
      {cambios.map((c, i) => <li key={i}>{c}</li>)}
    </ul>);
}

// ─── Componentes del rediseño de Recoger (12/11/2026) ───────────────────
function SeccionTitulo({ children }) {
  return <div style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: '0.06em', color: TOKENS.textMuted, textTransform: 'uppercase', marginBottom: 8 }}>{children}</div>;
}
function Seccion({ titulo, children }) {
  return (
    <div style={{ borderTop: `1px solid ${TOKENS.border}`, paddingTop: 12, marginTop: 14 }}>
      {titulo && <SeccionTitulo>{titulo}</SeccionTitulo>}
      {children}
    </div>);
}
function ChipBtn({ on, onClick, children, big, small, disabled }) {
  return (
    <button type="button" onClick={disabled ? undefined : onClick} disabled={disabled} style={{
      flex: 'none', fontFamily: 'inherit', cursor: disabled ? 'not-allowed' : 'pointer', opacity: disabled ? 0.35 : 1,
      padding: big ? '11px 4px' : small ? '6px 9px' : '8px 12px', fontSize: small ? 12.5 : 13.5, fontWeight: 700,
      borderRadius: 9, border: `1px solid ${on ? TOKENS.primary : TOKENS.borderInput}`,
      background: on ? TOKENS.primary : TOKENS.surface, color: on ? '#fff' : TOKENS.text
    }}>{children}</button>);
}
function ChipGroup({ options, value, onChange, scroll, suffix = '', small, disabledOptions = [] }) {
  return (
    <div className={scroll ? 'rd-noscroll' : undefined} style={{
      display: 'flex', gap: small ? 5 : 8, flexWrap: scroll ? 'nowrap' : 'wrap', overflowX: scroll ? 'auto' : 'visible',
      scrollbarWidth: 'none', msOverflowStyle: 'none', paddingBottom: scroll ? 2 : 0
    }}>
      {options.map((o) => <ChipBtn key={o} small={small} on={value === o} disabled={disabledOptions.includes(o)} onClick={() => onChange(o)}>{o}{suffix}</ChipBtn>)}
    </div>);
}
(function ensureNoScrollbar() {
  if (typeof document === 'undefined' || document.getElementById('rd-noscroll-style')) return;
  const st = document.createElement('style');st.id = 'rd-noscroll-style';
  st.textContent = '.rd-noscroll::-webkit-scrollbar{display:none}';
  document.head.appendChild(st);
})();
function TotalesPlaca({ items }) {
  const sum = (t) => items.filter((x) => x.tipo === t).reduce((n, x) => n + (Number(x.cantidad) || 1), 0);
  const r = sum('rin'),l = sum('llanta'),v = sum('valvula');
  const pill = (txt, main) => <span style={{ fontSize: 12, fontWeight: 700, borderRadius: 999, padding: '3px 9px', background: main ? TOKENS.primaryBg : TOKENS.surfaceLow, color: main ? TOKENS.primary : TOKENS.textMuted }}>{txt}</span>;
  return (
    <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', margin: '6px 0 4px' }}>
      {pill(`${r} ${r === 1 ? 'rin' : 'rines'}`, true)}
      {l > 0 && pill(`${l} ${l === 1 ? 'llanta' : 'llantas'}`)}
      {v > 0 && pill(`${v} ${v === 1 ? 'válvula' : 'válvulas'}`)}
    </div>);
}
function RepartoBox({ titulo, filas, mono, onEditar }) {
  return (
    <div style={{ marginTop: 6, border: `1px solid ${TOKENS.border}`, borderRadius: 10, background: TOKENS.surface, overflow: 'hidden', fontSize: 12.5 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 10, fontWeight: 800, letterSpacing: '0.06em', color: TOKENS.text, textTransform: 'uppercase', padding: onEditar ? '5px 6px 5px 10px' : '6px 10px', background: TOKENS.surfaceHigh, borderBottom: `1px solid ${TOKENS.border}` }}>
        <span>{titulo}</span>
        {onEditar &&
        <button type="button" onClick={onEditar} style={{ display: 'inline-flex', alignItems: 'center', gap: 4, border: `1px solid ${TOKENS.border}`, background: TOKENS.surface, borderRadius: 7, padding: '3px 9px', fontFamily: 'inherit', fontSize: 11, fontWeight: 700, color: TOKENS.primary, letterSpacing: 0, textTransform: 'none', cursor: 'pointer' }}>{I.pencil(12, TOKENS.primary)} Editar</button>}
      </div>
      {filas.map(([v, c], i) =>
      <div key={v} style={{ display: 'flex', justifyContent: 'space-between', gap: 10, padding: '5px 10px', borderTop: i ? `1px dashed ${TOKENS.border}` : 'none' }}>
          <b style={{ fontWeight: 700, color: TOKENS.text, overflowWrap: 'anywhere', fontFamily: mono ? "'JetBrains Mono', monospace" : undefined }}>{v}</b>
          <span style={{ color: TOKENS.textMuted, fontWeight: 700, flex: 'none' }}>{c} {c === 1 ? 'llanta' : 'llantas'}</span>
        </div>
      )}
    </div>);
}
// Ficha de un registro: todo lo registrado en dos columnas, con el valor pegado al nombre.
function FichaItem({ item, index, onEdit, onDelete, onFoto }) {
  const n = Number(item.cantidad) || 1;
  // Reparto de un valor con excepciones → [[valor, cantidad], ...] (valores iguales se suman).
  const reparto = (comun, ex) => {
    const list = (ex || []).filter((e) => e && (e.value || '').trim());
    const r = n - list.reduce((s, e) => s + (Number(e.count) || 0), 0);
    const out = [];
    const add = (v, c) => {const f = out.find((x) => x[0] === v);if (f) f[1] += c;else out.push([v, c]);};
    if (r > 0) add(comun || '—', r);
    list.forEach((e) => add(e.value.trim(), Number(e.count) || 0));
    return out;
  };
  const dots = item.tipo === 'llanta' ? reparto(item.dot, item.dotExceptions) : [];
  const cals = item.tipo === 'llanta' ? reparto(item.calidad, item.calidadExceptions) : [];
  const kv = item.tipo === 'rin' ?
  [['Cantidad', n], ['Tamaño', item.tamano ? item.tamano + '"' : '—'], ['Material', item.material], ['Huecos', item.huecos], ['Tapa', item.tapa], ['T. válvula', item.tapaValvula]] :
  item.tipo === 'llanta' ?
  [['Cantidad', n], ['Marca', item.marca], ['Referencia', item.referencia, true],
  ...(cals.length === 1 ? [['Calidad', cals[0][0], true]] : []),
  ...(dots.length === 1 ? [['DOT', dots[0][0], true, true]] : [])] :
  [['Cantidad', n], ['Sensor', item.valvulaSensor]];
  const nombre = item.tipo === 'rin' ? 'Rin' : item.tipo === 'llanta' ? 'Llanta' : 'Válvula';
  const fotos = (item.photos || []).filter(Boolean);
  const ic = { border: 'none', background: TOKENS.surface, borderRadius: 8, width: 32, height: 32, cursor: 'pointer', display: 'grid', placeItems: 'center' };
  return (
    <div style={{ border: `1px solid ${TOKENS.border}`, borderRadius: 12, background: TOKENS.surfaceLow, padding: '10px 12px', marginTop: 8 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
        <span style={{ background: TOKENS.primary, color: '#fff', fontSize: 10, fontWeight: 800, borderRadius: 999, padding: '2px 8px' }}>ITEM {String(index + 1).padStart(2, '0')}</span>
        <b style={{ flex: 1, fontSize: 13.5, color: TOKENS.text }}>{nombre}</b>
        {onEdit && <button type="button" aria-label="Editar" onClick={onEdit} style={ic}>{I.pencil(14, TOKENS.primary)}</button>}
        {onDelete && <button type="button" aria-label="Borrar" onClick={onDelete} style={ic}>{I.trash(14, TOKENS.danger)}</button>}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '2px 12px', fontSize: 12.5 }}>
        {kv.map(([k, v, w, mono]) =>
        <div key={k} style={{ gridColumn: w ? '1 / -1' : undefined, display: 'flex', gap: 5, padding: '3px 0', borderBottom: `1px dashed ${TOKENS.border}`, minWidth: 0 }}>
            <span style={{ color: TOKENS.textMuted, flex: 'none' }}>{k}:</span>
            <b style={{ color: TOKENS.text, fontWeight: 700, overflowWrap: 'anywhere', fontFamily: mono ? "'JetBrains Mono', monospace" : undefined }}>{v || '—'}</b>
          </div>
        )}
      </div>
      {/* Recuadro de reparto (opción C, 12/11/2026): solo cuando hay más de un DOT o calidad */}
      {dots.length > 1 && <RepartoBox titulo="DOT" filas={dots} mono />}
      {cals.length > 1 && <RepartoBox titulo="Calidad" filas={cals} />}
      {item.observaciones && <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 6 }}>Obs.: {item.observaciones}</div>}
      {fotos.length > 0 &&
      <div style={{ display: 'flex', gap: 6, marginTop: 8, flexWrap: 'wrap' }}>
          {fotos.map((src, i) => <img key={i} src={src} alt="" onClick={() => onFoto && onFoto(src)} style={{ width: 44, height: 44, objectFit: 'cover', borderRadius: 8, cursor: 'zoom-in' }} />)}
        </div>
      }
    </div>);
}

function IconAction({ title, onClick, disabled, active, children }) {
  return (
    <button type="button" title={title} aria-label={title} onClick={!disabled ? onClick : undefined} disabled={disabled} style={{
      width: 48, flex: 'none', display: 'grid', placeItems: 'center', borderRadius: 12,
      border: `1.5px solid ${active ? TOKENS.primaryBorder : TOKENS.borderInput}`,
      background: active ? TOKENS.primaryBg : TOKENS.surface,
      cursor: disabled ? 'not-allowed' : 'pointer', opacity: disabled ? 0.45 : 1
    }}>{children}</button>);
}

function ActionButton({ icon, label, color, bg, borderColor, onClick, disabled }) {
  return (
    <button onClick={!disabled ? onClick : undefined} disabled={disabled} style={{
        background: bg || TOKENS.surface, color, border: `1.5px solid ${borderColor}`,
        borderRadius: 12, padding: '12px 8px', cursor: disabled ? 'not-allowed' : 'pointer',
        fontFamily: 'inherit', display: 'flex', flexDirection: 'column',
        alignItems: 'center', gap: 6, opacity: disabled ? 0.45 : 1
       }}>
      {icon}
      <div style={{ fontSize: 13, fontWeight: 700, color: color }}>{label}</div>
    </button>);

}

// ─── Resumen Card (redesigned: stacked rows with thin dividers) ────────
function ResumenCard({ item, index, total, onEdit, onDelete }) {
  if (!item) return null;
  const isRin = item.tipo === 'rin';
  const isLlanta = item.tipo === 'llanta';
  const isValvula = item.tipo === 'valvula';
  const photos = (Array.isArray(item.photos) ? item.photos : []).filter(Boolean);
  const photoTitle = `Item ${String(index + 1).padStart(2, '0')} · ${isRin ? `Rin ${item.tamano}″` : isLlanta ? item.referencia || 'Llanta' : 'Válvula'}`;

  const typeLabel = isRin ? 'RIN' : isLlanta ? 'LLANTA' : 'VÁLVULA';

  return (
    <div style={{
      background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`,
      borderRadius: 12, padding: '4px 14px', position: 'relative'
    }}>
      {/* Item number tag floating */}
      <div style={{
        position: 'absolute', top: -10, left: 12,
        padding: '2px 10px', borderRadius: 6, background: TOKENS.navy,
        color: '#fff', fontSize: 10, fontWeight: 700, letterSpacing: '0.08em'
      }}>ITEM {String(index + 1).padStart(2, '0')}</div>

      <Row k="Producto" v={<b style={{ color: TOKENS.text }}>{typeLabel}</b>} />

      {isRin && <>
        <Row k="Tamaño" v={<b>{item.tamano}″</b>} />
        <Row k="Material" v={<b>{item.material}</b>} />
        <Row k="Huecos" v={<b>{item.huecos}</b>} />
        <Row k="Tapa" v={<Chip tone={item.tapa === 'Sí' ? 'success' : 'danger'}>{item.tapa === 'Sí' ? 'SÍ' : 'NO'}</Chip>} />
        <Row k="T. Válvula" v={<Chip tone={item.tapaValvula === 'Sí' ? 'success' : 'danger'}>{item.tapaValvula === 'Sí' ? 'SÍ' : 'NO'}</Chip>} />
      </>}

      {isLlanta && <>
        <Row k="Marca" v={<b>{item.marca || '—'}</b>} />
        <Row k="Referencia" v={<b style={{ fontFamily: 'monospace' }}>{item.referencia || '—'}</b>} />
        <Row k="DOT" v={<LlantaDotValue item={item} />} />
        <Row k="Calidad" v={<LlantaCalidadValue item={item} />} />
      </>}

      {isValvula && <>
        <Row k="Con sensor" v={<Chip tone={item.valvulaSensor === 'Sí' ? 'success' : 'neutral'}>{item.valvulaSensor === 'Sí' ? 'TPMS' : 'Estándar'}</Chip>} />
      </>}

      <Row k="Cantidad" v={
      <span style={{ color: TOKENS.primary, fontWeight: 700, fontSize: 16, fontFamily: 'monospace' }}>
          {String(item.cantidad).padStart(2, '0')}
        </span>
      } last />

      {item.observaciones &&
      <div style={{
        marginTop: 4, marginBottom: 10, padding: '8px 10px',
        background: '#fff', borderRadius: 8, border: `1px dashed ${TOKENS.border}`,
        fontSize: 12, color: TOKENS.textMuted, lineHeight: 1.45
      }}>
          <b style={{ color: TOKENS.text }}>Obs:</b> {item.observaciones}
        </div>
      }

      {/* Fotos del item — slide a pantalla completa */}
      {photos.length > 0 &&
      <div style={{ padding: '12px 0 4px' }}>
          <PhotoSlider photos={photos} title={`Fotos · ${photos.length === 1 ? '1 foto' : photos.length + ' fotos'}`} />
        </div>
      }

      {/* Acciones por-tarjeta (editar / eliminar) */}
      {(onEdit || onDelete) &&
      <div style={{
        display: 'flex', gap: 8, paddingTop: 10, marginTop: 4,
        borderTop: `1px solid ${TOKENS.border}`
      }}>
          {onEdit &&
        <button
          type="button"
          onClick={onEdit}
          style={{
            flex: 1, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
            padding: '9px 12px', borderRadius: 9, fontSize: 13, fontWeight: 700,
            background: TOKENS.surface, color: TOKENS.text,
            border: `1px solid ${TOKENS.border}`, cursor: 'pointer', fontFamily: 'inherit'
          }}>
              {I.pencil(15, TOKENS.text)}
              <span>Editar</span>
            </button>
        }
          {onDelete &&
        <button
          type="button"
          onClick={onDelete}
          style={{
            flex: 1, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
            padding: '9px 12px', borderRadius: 9, fontSize: 13, fontWeight: 700,
            background: '#fff', color: TOKENS.danger,
            border: `1.5px solid ${TOKENS.borderInput}`, cursor: 'pointer', fontFamily: 'inherit'
          }}>
              {I.trash(15, TOKENS.danger)}
              <span>Eliminar</span>
            </button>
        }
        </div>
      }
    </div>);

}

function Row({ k, v, last }) {
  return (
    <div style={{
      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      padding: '10px 0', borderBottom: last ? 'none' : `1px solid ${TOKENS.border}`,
      fontSize: 14
    }}>
      <span style={{ color: TOKENS.textMuted }}>{k}</span>
      <span style={{ color: TOKENS.text }}>{v}</span>
    </div>);

}

// ─── Revisar recogida (antes "Grabar", 12/11/2026) ──────────────────────
// Solo para mirar antes de generar el ticket. Sin flecha de volver ni edición por
// producto: "Modificar" regresa a Recoger con todo cargado. "Generar ticket" guarda.
function GrabarScreen({ state, onModificar, onCerrar, isEditing, wasDelivered, cambios, rondas }) {
  const items = state.items || [];
  const totalUnits = items.reduce((s, it) => s + (Number(it.cantidad) || 0), 0);
  const fotos = (state.fotosPlaca || []).filter(Boolean);
  const [confirmSave, setConfirmSave] = React.useState(false);
  const [confirmGenerar, setConfirmGenerar] = React.useState(false);
  const [confirmModificar, setConfirmModificar] = React.useState(false);
  const [verFoto, setVerFoto] = React.useState(null);
  const lista = cambios || [];
  const dato = (label, value) =>
  <div style={{ padding: '10px 12px', minWidth: 0 }}>
      <div style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: '0.06em', color: TOKENS.textMuted, textTransform: 'uppercase' }}>{label}</div>
      <div style={{ fontSize: 13.5, fontWeight: 700, color: TOKENS.text, marginTop: 3, wordBreak: 'break-word', lineHeight: 1.25 }}>{value || '—'}</div>
    </div>;

  return (
    <div style={{ background: TOKENS.bg, display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
      <AppHeader title={isEditing ? 'Revisar cambios' : 'Revisar recogida'} />
      <div style={{ padding: '14px 16px 24px' }}>

        {/* Cambios acumulados desde el primer resumen (aparece después de modificar) */}
        {rondas > 0 &&
        <div style={{
          marginBottom: 12, borderRadius: 14, padding: 12,
          background: lista.length ? '#fff2cc' : TOKENS.surfaceLow,
          border: `1px solid ${lista.length ? '#ecd98f' : TOKENS.border}`,
          color: lista.length ? '#7f6000' : TOKENS.textMuted
        }}>
            <div style={{ fontSize: 14, fontWeight: 800, marginBottom: lista.length ? 4 : 2 }}>Cambios: {lista.length}</div>
            {lista.length ? <ListaCambios cambios={lista} /> : <div style={{ fontSize: 12.5 }}>No modificaste nada.</div>}
          </div>
        }

        {/* Encabezado (13/11/2026): tarjeta blanca como el Resumen de Entregar, placa 24 px */}
        <div style={{ background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 14, padding: '14px 14px' }}>
          {window.CabeceraPlaca ? <window.CabeceraPlaca ticket={{ ...state, id: null }} grande /> : <b>{state.placa} · {state.codigo}</b>}
          <div style={{ fontSize: 12.5, color: TOKENS.textMuted, marginTop: 8 }}>Recogida el {String(state.fecha || '').replace(/\s/g, '')} · {window.formatHora12 ? window.formatHora12(state.horaRecogida) : state.horaRecogida}</div>
        </div>

        <div style={{ marginTop: 10, background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 14, display: 'grid', gridTemplateColumns: '1fr 1fr 1fr' }}>
          {dato('Aseguradora', state.aseguradora)}
          <div style={{ borderLeft: `1px solid ${TOKENS.border}` }}>{dato('Taller', state.taller)}</div>
          <div style={{ borderLeft: `1px solid ${TOKENS.border}` }}>{dato('Sede', state.sede)}</div>
        </div>

        {/* Items: total + por tipo, con las mismas fichas de Recoger */}
        <Card style={{ marginTop: 12, padding: '14px 14px', background: TOKENS.surface }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div style={{ fontSize: 15, fontWeight: 700, color: TOKENS.text }}>Items</div>
            <span style={{ fontSize: 11, fontWeight: 800, background: TOKENS.navyDark, color: '#fff', borderRadius: 999, padding: '3px 9px', letterSpacing: '0.04em' }}>TOTAL: {totalUnits}</span>
          </div>
          <TotalesPlaca items={items} />
          {items.map((it, i) => <FichaItem key={it.id || i} item={it} index={i} />)}
        </Card>

        {/* Fotos de la recogida (solo para ver) */}
        <Card style={{ marginTop: 12, padding: '14px 14px', background: TOKENS.surface }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <div style={{ fontSize: 15, fontWeight: 700, color: TOKENS.text }}>Fotos de la recogida</div>
            <span style={{ fontSize: 11.5, fontWeight: 600, color: TOKENS.textMuted }}>{fotos.length} {fotos.length === 1 ? 'foto' : 'fotos'}</span>
          </div>
          {fotos.length === 0 ?
          <div style={{ fontSize: 12.5, color: TOKENS.textSubtle, marginTop: 6 }}>Sin fotos.</div> :
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, marginTop: 8 }}>
              {fotos.map((src, i) =>
            <img key={i} src={src} alt={`Foto ${i + 1}`} onClick={() => setVerFoto(i)}
            style={{ width: '100%', aspectRatio: '1', objectFit: 'cover', borderRadius: 10, display: 'block', cursor: 'zoom-in' }} />
            )}
            </div>
          }
        </Card>

        {/* Acciones al final (sin barra fija) */}
        <div style={{ display: 'grid', gap: 8, marginTop: 16 }}>
          <Button variant="primary" full icon={I.checkCircle(18, '#fff')} onClick={() => isEditing ? setConfirmSave(true) : setConfirmGenerar(true)}
          style={{ padding: '14px', fontSize: 15 }}>
            {isEditing ? 'Guardar cambios' : 'Generar ticket'}
          </Button>
          <Button variant="outline" full icon={I.pencil(16, TOKENS.text)} onClick={() => setConfirmModificar(true)} style={{ padding: '13px', fontSize: 15 }}>Modificar</Button>
        </div>
      </div>

      {verFoto !== null && fotos[verFoto] && window.FotoGrande && <window.FotoGrande src={{ src: fotos[verFoto], list: fotos }} onClose={() => setVerFoto(null)} />}

      {confirmGenerar &&
      <ConfirmActionModal
        icon={I.checkCircle(24, TOKENS.success)}
        tone="primary"
        title={`¿Generar el ticket ${state.codigo}?`}
        message="Después de generarlo no podrás modificarlo desde aquí. Para corregir o eliminar la entrada tendrás que pedírselo a un administrador."
        cancelLabel="Revisar otra vez"
        confirmLabel="Generar ticket"
        onConfirm={() => {setConfirmGenerar(false);onCerrar();}}
        onDismiss={() => setConfirmGenerar(false)} />
      }

      {confirmModificar &&
      <ConfirmActionModal
        icon={I.pencil(24, TOKENS.primary)}
        tone="primary"
        title="¿Modificar la recogida?"
        message={'Vas a volver a la recogida para hacer cambios. Al terminar, toca "Guardar cambios" para volver al resumen.'}
        confirmLabel="Modificar"
        onConfirm={() => {setConfirmModificar(false);onModificar();}}
        onDismiss={() => setConfirmModificar(false)} />
      }

      {confirmSave &&
      <ConfirmActionModal
        icon={I.save(24, wasDelivered ? TOKENS.danger : TOKENS.primary)}
        tone={wasDelivered ? 'danger' : 'primary'}
        title="¿Guardar cambios?"
        message={wasDelivered ?
        `Vas a corregir los datos de identificación del registro entregado ${state.codigo}. El comprobante y los items no se modifican. La acción queda auditada.` :
        `Se sobrescribirá la información del registro ${state.codigo} con los cambios actuales.`}
        confirmLabel="Guardar cambios"
        onConfirm={() => {setConfirmSave(false);onCerrar();}}
        onDismiss={() => setConfirmSave(false)} />
      }
    </div>);
}

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

        )}
      </div>
    </Card>);

}

function ItemRow({ item, idx, onEdit }) {
  const isRin = item.tipo === 'rin';
  const isLlanta = item.tipo === 'llanta';
  const isValvula = item.tipo === 'valvula';
  const icon = isRin ? I.rin : isLlanta ? I.llanta : I.ajustes;
  const photos = (Array.isArray(item.photos) ? item.photos : []).filter(Boolean);
  const [lightboxIdx, setLightboxIdx] = React.useState(null);
  const photoTitle = `Item ${String(idx + 1).padStart(2, '0')} · ${isRin ? `Rin ${item.tamano}″` : isLlanta ? item.referencia || 'Llanta' : 'Válvula'}`;

  return (
    <div style={{
      background: TOKENS.surfaceLow, borderRadius: 12, padding: '14px 14px'
    }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
      <div style={{
          width: 34, height: 34, borderRadius: 9, background: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: TOKENS.primary, border: `1px solid ${TOKENS.border}`, flexShrink: 0, marginTop: 2
        }}>{icon(18, TOKENS.primary)}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: TOKENS.text }}>
          {isRin && `Rin ${item.tamano}″${item.material ? ` ${item.material}` : ''}`}
          {isLlanta && `${item.marca ? item.marca + ' ' : ''}${item.referencia || 'Llanta'}`}
          {isValvula && `Válvula ${item.valvulaSensor === 'Sí' ? 'TPMS' : 'estándar'}`}
        </div>
        <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 4, display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 4, lineHeight: 1.5 }}>
          {isRin && <>
            <span>{item.huecos}</span>
            <span>·</span>
            <span>Tapa</span>
            <Chip tone={item.tapa === 'Sí' ? 'success' : 'danger'}>{item.tapa === 'Sí' ? 'SÍ' : 'NO'}</Chip>
            <span>·</span>
            <span>T. Válvula</span>
            <Chip tone={item.tapaValvula === 'Sí' ? 'success' : 'danger'}>{item.tapaValvula === 'Sí' ? 'SÍ' : 'NO'}</Chip>
          </>}
          {isLlanta && <span>{(() => {
                const g = llantaBreakdown(item, 'dot');
                return g.length > 1 ? `${g.length} DOT distintos` : `DOT: ${g[0] && g[0].value || item.dot || '—'}`;
              })()}</span>}
          {isValvula && <span>{item.valvulaSensor === 'Sí' ? 'Con sensor TPMS' : 'Sin sensor'}</span>}
        </div>
        {/* DOT agrupado cuando difieren */}
        {isLlanta && llantaBreakdown(item, 'dot').length > 1 &&
          <div style={{ marginTop: 6 }}><LlantaDotValue item={item} align="flex-start" /></div>
          }
        {/* Calidad agrupada cuando difieren */}
        {isLlanta && llantaBreakdown(item, 'calidad').length > 1 &&
          <div style={{ marginTop: 6 }}><LlantaCalidadValue item={item} align="flex-start" /></div>
          }
        {item.observaciones &&
          <div style={{
            fontSize: 11, color: TOKENS.textMuted, marginTop: 8, padding: '6px 10px',
            background: '#fff', borderRadius: 6, border: `1px dashed ${TOKENS.border}`
          }}>
            <b style={{ color: TOKENS.text }}>Obs:</b> {item.observaciones}
          </div>
          }
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 8, flexShrink: 0 }}>
        {isLlanta && (() => {
            const g = llantaBreakdown(item, 'calidad');
            return g.length > 1 ?
            <Chip tone="neutral">{`${g.length} calidades`}</Chip> :
            <Chip tone={calidadTone(g[0] && g[0].value || item.calidad)}>{g[0] && g[0].value || item.calidad}</Chip>;
          })()}
        <div style={{
            fontSize: 13, fontWeight: 700, color: TOKENS.primary,
            background: '#fff', padding: '4px 10px', borderRadius: 6,
            border: `1px solid ${TOKENS.border}`, minWidth: 30, textAlign: 'center', fontFamily: 'monospace'
          }}>×{item.cantidad}</div>

        {/* Editar — botón sutil debajo de la cantidad (solo en modo edición) */}
        {onEdit &&
          <button
            type="button"
            onClick={onEdit}
            style={{
                display: 'inline-flex', alignItems: 'center', gap: 5,
                padding: '6px 10px', borderRadius: 8, fontSize: 12, fontWeight: 700,
                background: TOKENS.surface, color: TOKENS.text,
                border: `1px solid ${TOKENS.border}`, cursor: 'pointer', fontFamily: 'inherit'
               }}>
            {I.pencil(13, TOKENS.text)}
            <span>Editar</span>
          </button>
          }
      </div>
      </div>

      {/* Fotos del item — dentro de la columna de info, alineadas bajo la información */}
      {photos.length > 0 &&
      <div style={{ marginTop: 12 }}>
          <div style={{
          fontSize: 10, fontWeight: 700, color: TOKENS.textMuted,
          letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 6,
          display: 'flex', alignItems: 'center', gap: 5
        }}>
            {I.cam(13, TOKENS.textMuted)}
            <span>{photos.length} {photos.length === 1 ? 'foto adjunta' : 'fotos adjuntas'}</span>
          </div>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {photos.map((src, i) =>
          <PhotoReal key={i} src={src} idx={i + 1} onClick={() => setLightboxIdx(i)} />)}
          </div>
        </div>
      }
      </div>
      </div>
      {lightboxIdx != null &&
      <PhotoLightbox
        photos={photos}
        index={lightboxIdx}
        onIndex={setLightboxIdx}
        onClose={() => setLightboxIdx(null)}
        title={photoTitle} />
      }
    </div>);

}

Object.assign(window, { RecogerScreen, GrabarScreen, getNextCode, ConfirmActionModal, diffRecogida, FichaItem, TotalesPlaca });

// ─── Confirm changes modal ──────────────────────────────────────────────
function ConfirmActionModal({ icon, tone = 'danger', title, message, confirmLabel = 'Confirmar', cancelLabel = 'Cancelar', onConfirm, onDismiss, ticket }) {
  // Color por tipo de acción (12/11/2026): guardar = azul · generar = verde · modificar = amarillo · eliminar/descartar = rojo
  const accent = tone === 'danger' ? TOKENS.danger : tone === 'warn' ? '#f2c037' : tone === 'success' ? TOKENS.success : TOKENS.primary;
  const accentBg = tone === 'danger' ? TOKENS.dangerBg : tone === 'warn' ? '#fff2cc' : tone === 'success' ? TOKENS.successBg : TOKENS.primaryBg;
  const accentText = tone === 'warn' ? '#3a2c00' : '#fff';
  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(11,28,48,0.5)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: 16
    }} onClick={onDismiss}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: TOKENS.surface, borderRadius: 16, padding: '22px 20px',
        width: '100%', maxWidth: 340, boxShadow: '0 20px 60px rgba(11,28,48,0.3)'
      }}>
        <div style={{
          width: 52, height: 52, borderRadius: 999, background: accentBg,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          margin: '0 auto 14px'
        }}>{icon}</div>
        <div style={{ fontSize: 17, fontWeight: 700, color: TOKENS.text, textAlign: 'center', marginBottom: 6 }}>{title}</div>
        {ticket && window.CabeceraPlaca && <div style={{ display: 'flex', justifyContent: 'center', margin: '4px 0 10px' }}><window.CabeceraPlaca ticket={ticket} /></div>}
        
        <div style={{ fontSize: 13, color: TOKENS.textMuted, textAlign: 'center', lineHeight: 1.5, marginBottom: 18 }}>{message}</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <button type="button" onClick={onDismiss} style={{
            padding: '12px', borderRadius: 10, fontSize: 14, fontWeight: 700,
            background: TOKENS.surface, color: TOKENS.text, border: `1px solid ${TOKENS.border}`,
            cursor: 'pointer', fontFamily: 'inherit'
          }}>{cancelLabel}</button>
          <button type="button" onClick={onConfirm} style={{
            padding: '12px', borderRadius: 10, fontSize: 14, fontWeight: 700,
            background: accent, color: accentText, border: 'none',
            cursor: 'pointer', fontFamily: 'inherit'
          }}>{confirmLabel}</button>
        </div>
      </div>
    </div>);

}

// ─── Confirm changes modal ──────────────────────────────────────────────
function ConfirmEditModal({ before, after, onConfirm, onDismiss }) {
  const fields = before.tipo === 'rin' ?
  [['Producto', 'RIN', 'RIN'], ['Tamaño', before.tamano + '"', after.tamano + '"'],
  ['Material', before.material, after.material], ['Huecos', before.huecos, after.huecos],
  ['Tapa', before.tapa, after.tapa], ['T. Válvula', before.tapaValvula, after.tapaValvula],
  ['Cantidad', before.cantidad, after.cantidad]] :
  before.tipo === 'llanta' ?
  [['Producto', 'LLANTA', 'LLANTA'], ['Marca', before.marca, after.marca],
  ['Referencia', before.referencia, after.referencia], ['DOT', before.dot, after.dot],
  ['Calidad', before.calidad, after.calidad], ['Cantidad', before.cantidad, after.cantidad]] :
  [['Producto', 'VÁLVULA', 'VÁLVULA'], ['Con sensor', before.valvulaSensor, after.valvulaSensor],
  ['Cantidad', before.cantidad, after.cantidad]];

  const obsBefore = before.observaciones || '';
  const obsAfter = after.observaciones || '';
  if (obsBefore || obsAfter) fields.push(['Observaciones', obsBefore || '—', obsAfter || '—']);

  const changes = fields.filter(([k, b, a]) => String(b) !== String(a));

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(11,28,48,0.5)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: 16
    }}>
      <div style={{
        background: TOKENS.surface, borderRadius: 18, padding: 22, width: '100%', maxWidth: 380,
        boxShadow: '0 16px 40px rgba(0,0,0,0.2)', maxHeight: '85vh', overflow: 'auto'
      }}>
        <div style={{
          width: 52, height: 52, borderRadius: 999, background: TOKENS.primaryBg,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          margin: '0 auto 12px', color: TOKENS.primary
        }}>{I.pencil(26, TOKENS.primary)}</div>
        <div style={{ fontSize: 17, fontWeight: 700, color: TOKENS.text, textAlign: 'center' }}>
          ¿Confirmar cambios?
        </div>
        <div style={{ fontSize: 13, color: TOKENS.textMuted, textAlign: 'center', marginTop: 6, lineHeight: 1.5 }}>
          {changes.length === 0 ? 'No se detectaron cambios.' : `Vas a modificar ${changes.length} ${changes.length === 1 ? 'campo' : 'campos'}:`}
        </div>

        {changes.length > 0 &&
        <div style={{
          marginTop: 14, background: TOKENS.surfaceLow, borderRadius: 10,
          border: `1px solid ${TOKENS.border}`, padding: '4px 12px'
        }}>
            {changes.map(([k, b, a]) =>
          <div key={k} style={{
            padding: '10px 0', fontSize: 13,
            borderBottom: `1px solid ${TOKENS.border}`
          }}>
                <div style={{ fontSize: 11, fontWeight: 700, color: TOKENS.textMuted, letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 4 }}>
                  {k}
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                  <span style={{
                textDecoration: 'line-through', color: TOKENS.textMuted,
                fontSize: 13, fontWeight: 500
              }}>{String(b || '—')}</span>
                  <span style={{ color: TOKENS.textMuted }}>→</span>
                  <span style={{ color: TOKENS.primary, fontWeight: 700, fontSize: 13 }}>
                    {String(a || '—')}
                  </span>
                </div>
              </div>
          )}
          </div>
        }

        <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
          <Button variant="outline" full onClick={onDismiss}>Volver</Button>
          <Button variant="primary" full onClick={onConfirm} icon={I.check(16, '#fff')}>
            {changes.length === 0 ? 'Cerrar' : 'Confirmar'}
          </Button>
        </div>
      </div>
    </div>);

}

Object.assign(window, { ConfirmEditModal });