// ─── Consultar screen ───────────────────────────────────────────────────
// Lista de TODOS los registros (pendientes + entregados), con filtros.

function ConsultarScreen({ onBack, onNav, role, onEditTicket, initialFilter, initialDate, initialSeverity, initialSelectedId, onInitialConsumed }) {
  const isAdmin = role === 'admin';
  const [query, setQuery] = React.useState('');
  const [filter, setFilter] = React.useState(initialFilter || 'todos'); // 'todos' | 'pendiente' | 'entregado'
  // Filtros de atributo (18/11/2026): Express y Garantía, se combinan con el estado.
  const [fExp, setFExp] = React.useState(false);
  const [fGar, setFGar] = React.useState(false);
  const [dateMode, setDateMode] = React.useState('dia'); // 'dia' | 'rango'
  const [day, setDay] = React.useState(initialDate === 'hoy' ? new Date() : null);
  const [rangeFrom, setRangeFrom] = React.useState(null);
  const [rangeTo, setRangeTo] = React.useState(null);
  const [calOpen, setCalOpen] = React.useState(false);
  const [selectedId, setSelectedId] = React.useState(initialSelectedId || null);
  const [view, setView] = React.useState(initialSelectedId ? 'resumen' : 'list'); // 'list' | 'resumen' | 'comprobante' | 'entrega' | 'success'
  // Sub-filtro de estado bajo Pendientes (13/11/2026): mismos términos de Inicio y Entregar.
  // orden: 0 Vencido · 1 Retrasado · 2 Vence hoy · 3 En plazo. Los enlaces viejos (aldia/atrasado/critico) se traducen.
  const ESTADOS = [[0, 'Vencido'], [1, 'Retrasado'], [2, 'Vence hoy'], [3, 'En plazo']];
  const desdeSev = (arr) => {
    const m = { critico: [0], atrasado: [1], aldia: [2, 3] };
    const out = [];(arr || []).forEach((x) => (typeof x === 'number' ? [x] : m[x] || []).forEach((o) => out.includes(o) || out.push(o)));
    return out.length ? out : [0, 1, 2, 3];
  };
  const [sevFilter, setSevFilter] = React.useState(desdeSev(initialSeverity));
  const [lastDelivered, setLastDelivered] = React.useState(null);
  // Preset de fecha activo: null | 'hoy' | '7' | '15' | '30' | 'custom'
  const [datePreset, setDatePreset] = React.useState(initialDate === 'hoy' ? 'hoy' : null);
  const [presetMenuOpen, setPresetMenuOpen] = React.useState(false);
  // Paginación local: cuántos registros se muestran (tope inicial 30, +30 por "Ver más").
  const [shown, setShown] = React.useState(30);

  // Aplica un preset de fecha rápido (o abre el calendario para "custom").
  const applyPreset = (p) => {
    setDatePreset(p);
    if (p === 'hoy') { setDateMode('dia'); setDay(new Date()); setRangeFrom(null); setRangeTo(null); setCalOpen(false); }
    else if (p === '7' || p === '15' || p === '30') {
      const n = Number(p);
      const to = new Date();
      const from = new Date(); from.setDate(from.getDate() - (n - 1));
      setDateMode('rango'); setDay(null); setRangeFrom(from); setRangeTo(to); setCalOpen(false);
    } else if (p === 'custom') { setCalOpen((o) => !o); }
  };
  const clearDate = () => { setDatePreset(null); setDay(null); setRangeFrom(null); setRangeTo(null); setCalOpen(false); };

  // Volver al tope de 30 cada vez que cambia la búsqueda o cualquier filtro.
  React.useEffect(() => { setShown(30); }, [query, filter, datePreset, day, rangeFrom, rangeTo, sevFilter.join('|')]);

  // Resetear scroll al cambiar de sub-vista o de registro seleccionado.
  React.useEffect(() => { if (window.rdScrollTop) window.rdScrollTop(); }, [view, selectedId]);

  // Reabrir la ficha al volver de una edición cancelada
  React.useEffect(() => {
    if (initialSelectedId) {
      setSelectedId(initialSelectedId);
      setView('resumen');
      onInitialConsumed && onInitialConsumed();
    }
    // eslint-disable-next-line
  }, []);

  // Data sources
  const [savedTickets, setSavedTickets] = React.useState(loadPendientesSaved());
  const [entregados, setEntregados] = React.useState(loadEntregados());
  const [anuMap, setAnuMap] = React.useState(window.loadAnulacionMap());
  // Modales de anular / reactivar
  const [anularTarget, setAnularTarget] = React.useState(null);
  const [confirmEditar, setConfirmEditar] = React.useState(false);
  const [reactivarTarget, setReactivarTarget] = React.useState(null);
  React.useEffect(() => {
    const refresh = () => {
      setSavedTickets(loadPendientesSaved());
      setEntregados(loadEntregados());
      setAnuMap(window.loadAnulacionMap());
    };
    refresh();
    window.addEventListener('storage', refresh);
    window.addEventListener('focus', refresh);
    window.addEventListener('rodando-anulaciones', refresh);
    return () => {
      window.removeEventListener('storage', refresh);
      window.removeEventListener('focus', refresh);
      window.removeEventListener('rodando-anulaciones', refresh);
    };
  }, []);

  const ConfirmModal = window.ConfirmActionModal;
  const AnularModal = window.AnularTicketModal;
  const doAnular = ({ motivo, nota }) => {
    if (!anularTarget) return;
    const yo = (window.usuarioActual && window.usuarioActual()) || {};
    window.anularTicket(anularTarget, { motivo, nota, por: yo.nombre || '' });
    if (window.notifyAnulacion) window.notifyAnulacion(anularTarget, { motivo, por: yo.usuario || '' });
    setAnularTarget(null);
    setSelectedId(null); setView('list');
    setAnuMap(window.loadAnulacionMap());
  };
  const doReactivar = () => {
    if (!reactivarTarget) return;
    window.reactivarTicket(reactivarTarget, { por: ((window.usuarioActual && window.usuarioActual()) || {}).nombre || '' });
    setReactivarTarget(null);
    setSelectedId(null); setView('list');
    setAnuMap(window.loadAnulacionMap());
  };

  const anularReactivarModals = (
    <>
      {anularTarget && AnularModal && (
        <AnularModal ticket={anularTarget} onConfirm={doAnular} onDismiss={() => setAnularTarget(null)} />
      )}
      {reactivarTarget && ConfirmModal && (
        <ConfirmModal
          tone="primary"
          icon={I.reactivar(26, TOKENS.primary)}
          title="Reactivar registro"
          message={`El registro ${reactivarTarget.codigo} volverá a la cola de Entregar como pendiente. El SLA se reiniciará desde hoy.`}
          confirmLabel="Reactivar"
          onConfirm={doReactivar}
          onDismiss={() => setReactivarTarget(null)} />
      )}
    </>
  );

  const deliveredIds = new Set(entregados.map((e) => e.ticketId));

  // Keep filters in sync when re-entering via a deep-link (dashboard metric).
  React.useEffect(() => {setFilter(initialFilter || 'todos');}, [initialFilter]);
  React.useEffect(() => {
    if (initialDate === 'hoy') {setDateMode('dia');setDay(new Date());setRangeFrom(null);setRangeTo(null);setDatePreset('hoy');} else
    if (initialDate === 'all') {setDay(null);setRangeFrom(null);setRangeTo(null);setDatePreset(null);}
  }, [initialDate]);

  // Build unified records: pendientes (saved + demo, minus delivered) + entregados
  const savedIds = new Set(savedTickets.map((t) => t.id));
  const basePend = [...savedTickets, ...PENDIENTES_DEMO].
  filter((t) => !deliveredIds.has(t.id)).
  map((t) => ({ ...t, _source: savedIds.has(t.id) ? 'pendiente-saved' : 'pendiente-demo' }));

  // Separar pendientes activos (incl. reactivados) de anulados
  const pendientesAll = [];
  const anuladosAll = [];
  basePend.forEach((t) => {
    const anu = anuMap.get(t.id);
    if (anu && anu.estadoActual === 'anulado') {
      anuladosAll.push({ ...t, _status: 'anulado', _anulacion: anu });
    } else {
      pendientesAll.push({ ...window.withAnulacion(t, anuMap), _status: 'pendiente' });
    }
  });

  const entregadosAll = entregados.map((e) => ({
    id: e.ticketId,
    codigo: e.codigo,
    placa: e.placa,
    idType: e.idType,
    fecha: e.fechaRecogido,
    fechaEntrega: e.fechaEntrega,
    horaEntrega: e.horaEntrega,
    aseguradora: e.aseguradora,
    taller: e.taller,
    sede: e.sede,
    items: e.items,
    factura: e.factura,
    recibePor: e.recibePor,
    foto: e.foto,
    fotosPlaca: e.fotosPlaca || [],
    recogidoPor: e.recogidoPor || '',
    entregadoPor: e.entregadoPor || '',
    express: !!e.express,
    _status: 'entregado',
    _source: 'entregado',
    _entrega: e
  }));

  // El mensajero ve solo lo que él recogió o entregó (13/11/2026). Los registros
  // viejos sin usuario se muestran a todos. El administrador ve todo.
  const yo = (window.usuarioActual && window.usuarioActual() || {}).usuario || '';
  const esMio = (t) => isAdmin || !yo || (!t.recogidoPor && !t.entregadoPor) || t.recogidoPor === yo || t.entregadoPor === yo;
  [pendientesAll, entregadosAll, anuladosAll].forEach((arr) => { for (let i = arr.length - 1; i >= 0; i--) if (!esMio(arr[i])) arr.splice(i, 1); });
  let all = [...pendientesAll, ...entregadosAll, ...anuladosAll];
  // Sort by fecha desc (most recent first)
  // Prioridad (18/11/2026): garantía abierta > express pendiente > el resto; dentro de cada grupo, lo más reciente primero.
  const rango = (t) => (window.garantiaAbierta && window.garantiaAbierta(t.id)) ? 0 : (t.express && t._status === 'pendiente') ? 1 : 2;
  all.sort((a, b) => {
    const r = rango(a) - rango(b);
    if (r) return r;
    const da = parseFechaDDMMYYYY(a.fechaEntrega || a.fecha) || new Date(0);
    const db = parseFechaDDMMYYYY(b.fechaEntrega || b.fecha) || new Date(0);
    return db - da;
  });

  // Filter (status)
  if (filter !== 'todos') {
    all = all.filter((t) => t._status === filter);
  }

  const garDe = (t) => window.garantiasDe ? window.garantiasDe(t.id) : [];
  const nExp = all.filter((t) => t.express).length;
  const nGar = all.filter((t) => garDe(t).length > 0).length;
  if (fExp) all = all.filter((t) => t.express);
  if (fGar) {
    all = all.filter((t) => garDe(t).length > 0);
    all.sort((a, b) => (garDe(a).some((g) => g.estado === 'abierta') ? 0 : 1) - (garDe(b).some((g) => g.estado === 'abierta') ? 0 : 1));
  }

  // Sub-filtro de severidad SLA (solo bajo Pendientes)
  if (filter === 'pendiente') {
    const today = new Date();
    all = all.filter((t) => sevFilter.includes(window.estadoProcesos ? window.estadoProcesos(t).orden : 3));
  }

  // Filter (date). Basis = delivery date when viewing Entregados, otherwise the
  // pickup (recogida) date — so "Recogidos · Hoy" lines up with the dashboard
  // metric, which counts pickup events.
  const basisStr = (t) => filter === 'entregado' ? t.fechaEntrega || t.fecha : t.fecha;
  const recDate = (t) => parseFechaDDMMYYYY(basisStr(t));
  const hasDateFilter = dateMode === 'dia' && day || dateMode === 'rango' && (rangeFrom || rangeTo);
  if (dateMode === 'dia' && day) {
    all = all.filter((t) => {const d = recDate(t);return d && window.sameISO(d, day);});
  } else if (dateMode === 'rango' && (rangeFrom || rangeTo)) {
    const lo = window.startOfDay(rangeFrom);
    const hi = rangeTo ? new Date(rangeTo.getFullYear(), rangeTo.getMonth(), rangeTo.getDate(), 23, 59, 59) : null;
    all = all.filter((t) => {
      const d = recDate(t);
      if (!d) return false;
      if (lo && d < lo) return false;
      if (hi && d > hi) return false;
      return true;
    });
  }

  // Search
  const q = query.trim().toLowerCase();
  const filtered = q ?
  all.filter((t) =>
  (t.placa || '').toLowerCase().includes(q) ||
  (t.codigo || '').toLowerCase().includes(q) ||
  (t.taller || '').toLowerCase().includes(q) ||
  (t.aseguradora || '').toLowerCase().includes(q) ||
  (t.sede || '').toLowerCase().includes(q) ||
  (t.factura || '').toLowerCase().includes(q)
  ) :
  all;

  const totalPend = pendientesAll.length;
  const totalEntregados = entregadosAll.length;
  const totalAnulados = anuladosAll.length;

  // Tope local de render: solo mostramos los primeros `shown` (recientes primero).
  const visible = filtered.slice(0, shown);
  const hayMas = filtered.length > shown;

  const selected = selectedId ? [...pendientesAll, ...entregadosAll, ...anuladosAll].find((t) => t.id === selectedId) : null;

  // Detail navigation
  if (selected && view === 'success' && lastDelivered) {
    return <EntregaSuccessScreen
      entrega={lastDelivered}
      onMenu={() => {setSelectedId(null);setView('list');setLastDelivered(null);}}
      onSiguiente={() => {
        setSelectedId(null);setView('list');setLastDelivered(null);
        setEntregados(loadEntregados());
        setSavedTickets(loadPendientesSaved());
      }} />;

  }

  if (selected && view === 'entrega') {
    return <EntregaConfirmScreen
      ticket={selected}
      onBack={() => setView('resumen')}
      onSaved={(entry) => {
        setLastDelivered(entry);
        setEntregados(loadEntregados());
        setSavedTickets(loadPendientesSaved());
        setView('success');
      }} />;

  }

  if (selected && view === 'comprobante' && selected._entrega) {
    return <ImprimirEntregaScreen
      entrega={selected._entrega}
      onBack={() => setView('resumen')}
      onPrint={() => alert('Enviado a impresora Bluetooth.')} />;

  }
  if (selected && view === 'imprimir') {
    return <ImprimirScreen
      ticket={selected}
      onBack={() => setView('resumen')}
      onPrint={() => alert('Enviado a impresora Bluetooth.')} />;

  }
  // Resúmenes nuevos (13/11/2026) para mensajero y administrador (este con sus acciones al final).
  if (selected) {
    const volver = () => {setSelectedId(null);setView('list');};
    const ConfirmM = window.ConfirmActionModal;
    const editar = isAdmin && onEditTicket && selected._status !== 'anulado' ? () => setConfirmEditar(true) : undefined;
    const modals = <>
      {anularReactivarModals}
      {confirmEditar && ConfirmM &&
      <ConfirmM icon={I.pencil(24, TOKENS.primary)} tone="primary"
      title={selected._status === 'entregado' ? '¿Editar un registro entregado?' : `¿Editar el registro ${selected.codigo}?`}
      message={selected._status === 'entregado' ? 'Solo podrás corregir los datos de identificación. Los ítems y el comprobante firmado no se modifican.' : 'Vas a cambiar los datos de esta recogida. Al guardar, el cambio queda registrado.'}
      confirmLabel="Editar" onConfirm={() => {setConfirmEditar(false);onEditTicket(selected);}} onDismiss={() => setConfirmEditar(false)} />
      }
    </>;
    if (selected._status === 'entregado') {
      return <>
        <ResumenEntregadoScreen entrega={selected._entrega} onBack={volver} onImprimir={() => setView('comprobante')} admin={isAdmin} onEditar={editar} />
        {modals}
      </>;
    }
    const anuEv = selected._status === 'anulado' && selected._anulacion ? window.lastEventoTipo(selected._anulacion, 'anulado') : null;
    return <>
      <ResumenEntregaScreen
        ticket={selected}
        anulado={selected._status === 'anulado' ? anuEv || {} : null}
        puedeSolicitarAnulacion={!isAdmin && selected._status === 'pendiente'}
        admin={isAdmin}
        onEditar={editar}
        onAnular={isAdmin && selected._status === 'pendiente' ? () => setAnularTarget(selected) : undefined}
        onReactivar={isAdmin && selected._status === 'anulado' ? () => setReactivarTarget(selected) : undefined}
        onBack={volver}
        onEntregar={() => setView('entrega')}
        onImprimir={() => setView('imprimir')} />
      {modals}
    </>;
  }
  return (
    <div style={{ background: TOKENS.bg, display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
      <AppHeader title="Consultar" onBack={onBack} />
      <div style={{ padding: 16, flex: 1 }}>

        {/* Search bar */}
        <div style={{ position: 'relative', marginBottom: 10 }}>
          <div style={{
            position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)',
            color: TOKENS.textMuted, pointerEvents: 'none', display: 'flex'
          }}>{I.consultar(16, TOKENS.textMuted)}</div>
          <input
            type="text"
            className="ad-search"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Placa, orden, factura o taller"
            style={{
              width: '100%', boxSizing: 'border-box',
              border: `1px solid ${TOKENS.borderInput}`,
              background: TOKENS.surface,
              borderRadius: 12, padding: '12px 40px 12px 38px',
              fontSize: 14, color: TOKENS.text, fontFamily: 'inherit', outline: 'none'
            }} />
          
          {query &&
          <button type="button" onClick={() => setQuery('')} style={{
            position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)',
            background: 'transparent', border: 'none', padding: 6, cursor: 'pointer',
            display: 'flex', color: TOKENS.textMuted
          }} aria-label="Limpiar búsqueda">
              {I.x(16, TOKENS.textMuted)}
            </button>
          }
        </div>

        {/* Filter chips — fila única con scroll horizontal (no se rompe el layout) */}
        <div className="rd-chiprow" style={{ display: 'flex', flexWrap: 'nowrap', gap: 8, margin: '4px 0 14px', overflowX: 'auto', paddingBottom: 2 }}>
          <FilterChip active={filter === 'todos'} onClick={() => setFilter('todos')}>
            Todos · {totalPend + totalEntregados + totalAnulados}
          </FilterChip>
          <FilterChip active={filter === 'pendiente'} onClick={() => setFilter('pendiente')} tone="pendiente">
            Pendientes · {totalPend}
          </FilterChip>
          <FilterChip active={filter === 'entregado'} onClick={() => setFilter('entregado')} tone="success">
            Entregados · {totalEntregados}
          </FilterChip>
          <FilterChip active={filter === 'anulado'} onClick={() => setFilter('anulado')} tone="anulado">
            Anulados · {totalAnulados}
          </FilterChip>
        </div>

        <div style={{ display: 'flex', gap: 8, margin: '-6px 0 12px', flexWrap: 'wrap' }}>
          <FilterChip active={fExp} activeSoft={{ bg: '#fce7f3', fg: '#be185d', bd: '#e879b0' }} onClick={() => setFExp(!fExp)}>⚡ Express · {nExp}</FilterChip>
          <FilterChip active={fGar} activeSoft={{ bg: '#e6f7fa', fg: '#0e7490', bd: '#5bb8cc' }} onClick={() => setFGar(!fGar)}>↺ Garantía · {nGar}</FilterChip>
        </div>

        {/* Sub-filtro de severidad (solo bajo Pendientes) */}
        {/* Opción A (18/11/2026): estado de los pendientes como una línea discreta de puntos */}
        {filter === 'pendiente' &&
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '-2px 2px 12px', flexWrap: 'wrap' }}>
            <span style={{ fontSize: 10.5, fontWeight: 800, color: TOKENS.textMuted, letterSpacing: '0.06em', textTransform: 'uppercase' }}>Estado</span>
            {ESTADOS.map(([lvl, label]) => {
              const on = sevFilter.includes(lvl);
              const dot = ['#c0392b', '#d9772b', '#e0b100', '#2f9e5b'][lvl];
              return (
                <button key={lvl} type="button" aria-pressed={on}
                onClick={() => setSevFilter((prev) => prev.includes(lvl) ? prev.filter((x) => x !== lvl) : [...prev, lvl])}
                style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '4px 0', border: 0, background: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12.5, fontWeight: on ? 600 : 500, color: on ? TOKENS.text : TOKENS.textSubtle, opacity: on ? 1 : 0.6 }}>
                  <span style={{ width: 8, height: 8, borderRadius: 999, background: dot }} />{label}
                </button>);
            })}
          </div>
        }

        {/* Date filter: campo (calendario) + chip Hoy con dropdown de rangos rápidos */}
        <div style={{ position: 'relative', marginBottom: 12 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{
              fontSize: 11, fontWeight: 700, color: TOKENS.textMuted, letterSpacing: '0.04em',
              textTransform: 'uppercase', flexShrink: 0
            }}>Fecha</span>

            {/* Barra: selección de fecha / rango (abre calendario) */}
            <button data-cal-toggle="1" onClick={() => { setCalOpen((o) => !o); setPresetMenuOpen(false); }} style={{
              flex: 1, display: 'flex', alignItems: 'center', gap: 8, minWidth: 0,
              padding: '10px 12px', borderRadius: 12, cursor: 'pointer', fontFamily: 'inherit',
              border: `1px solid ${calOpen || hasDateFilter ? TOKENS.primary : TOKENS.borderInput}`,
              background: hasDateFilter ? TOKENS.surfaceLow : TOKENS.surface,
              color: hasDateFilter ? TOKENS.text : TOKENS.textMuted
            }}>
              <span style={{ display: 'flex', color: hasDateFilter ? TOKENS.primary : TOKENS.textMuted }}>
                {I.cal(16)}
              </span>
              <span style={{
                flex: 1, textAlign: 'left', fontSize: 13.5, fontWeight: hasDateFilter ? 700 : 500,
                whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'
              }}>
                {!hasDateFilter ? 'Todas las fechas' :
                dateMode === 'dia' ? window.fechaCorta(day) :
                rangeFrom && rangeTo ? `${window.fechaCorta(rangeFrom)} – ${window.fechaCorta(rangeTo)}` :
                rangeFrom ? `Desde ${window.fechaCorta(rangeFrom)}` :
                `Hasta ${window.fechaCorta(rangeTo)}`}
              </span>
              <span style={{ display: 'flex', color: TOKENS.textMuted, transform: calOpen ? 'rotate(180deg)' : 'none', transition: 'transform .15s' }}>
                {I.chev(15)}
              </span>
            </button>

            {/* Chip Hoy + caret que despliega rangos rápidos (7 / 15 / 30 días) */}
            <div style={{ position: 'relative', flexShrink: 0 }}>
              {(() => {
                const presetActive = ['hoy', '7', '15', '30'].includes(datePreset);
                const presetLabel = datePreset === '7' ? '7 días' : datePreset === '15' ? '15 días' : datePreset === '30' ? '30 días' : 'Hoy';
                const accent = presetActive ? '#fff' : TOKENS.textMuted;
                return (
                  <div style={{ display: 'flex', alignItems: 'stretch' }}>
                    <button onClick={() => presetActive ? clearDate() : applyPreset('hoy')}
                      onMouseEnter={(e) => { if (!presetActive) e.currentTarget.style.background = TOKENS.surfaceLow; }}
                      onMouseLeave={(e) => { if (!presetActive) e.currentTarget.style.background = TOKENS.surface; }}
                      style={{
                      padding: '7px 10px 7px 13px', borderRadius: '999px 0 0 999px', fontSize: 12, fontWeight: 700,
                      border: `1px solid ${presetActive ? TOKENS.primary : TOKENS.border}`, borderRight: 'none',
                      background: presetActive ? TOKENS.primary : TOKENS.surface,
                      color: presetActive ? '#fff' : TOKENS.text,
                      cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap', letterSpacing: '0.02em',
                      transition: 'background .12s'
                    }}>{presetLabel}</button>
                    <button onClick={() => { setPresetMenuOpen((o) => !o); setCalOpen(false); }} aria-label="Más rangos"
                      onMouseEnter={(e) => { if (!presetActive) e.currentTarget.style.background = TOKENS.surfaceLow; }}
                      onMouseLeave={(e) => { if (!presetActive) e.currentTarget.style.background = TOKENS.surface; }}
                      style={{
                      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '7px 9px',
                      borderRadius: '0 999px 999px 0', cursor: 'pointer', fontFamily: 'inherit',
                      border: `1px solid ${presetActive ? TOKENS.primary : TOKENS.border}`,
                      background: presetActive ? TOKENS.primary : TOKENS.surface, color: accent,
                      transition: 'background .12s'
                    }}>
                      <span style={{ display: 'flex', transform: presetMenuOpen ? 'rotate(180deg)' : 'none', transition: 'transform .15s' }}>
                        {I.chev(14, accent)}
                      </span>
                    </button>
                  </div>
                );
              })()}

              {presetMenuOpen &&
              <>
                <div onClick={() => setPresetMenuOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 40 }} />
                <div style={{
                  position: 'absolute', top: 'calc(100% + 6px)', right: 0, zIndex: 41, minWidth: 168,
                  background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 12,
                  boxShadow: '0 12px 28px rgba(11,28,48,0.16)', overflow: 'hidden', padding: 4
                }}>
                  {[['hoy', 'Hoy'], ['7', 'Últimos 7 días'], ['15', 'Últimos 15 días'], ['30', 'Últimos 30 días']].map(([val, label]) => {
                    const on = datePreset === val;
                    return (
                      <button key={val} onClick={() => { applyPreset(val); setPresetMenuOpen(false); }}
                        onMouseEnter={(e) => { if (!on) e.currentTarget.style.background = TOKENS.surfaceLow; }}
                        onMouseLeave={(e) => { if (!on) e.currentTarget.style.background = 'transparent'; }}
                        style={{
                        display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, width: '100%',
                        padding: '10px 12px', borderRadius: 8, cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left',
                        border: 'none', background: on ? TOKENS.surfaceLow : 'transparent',
                        color: TOKENS.text, fontSize: 13, fontWeight: on ? 700 : 600,
                        transition: 'background .12s'
                      }}>
                        {label}
                        {on && <span style={{ display: 'flex', color: TOKENS.primary }}>{I.check(15, TOKENS.primary)}</span>}
                      </button>);
                  })}
                </div>
              </>
              }
            </div>
          </div>

          {calOpen &&
          <CalendarPopover
            mode={dateMode} day={day} from={rangeFrom} to={rangeTo}
            onChange={(next) => {
              setDateMode(next.mode);
              setDay(next.day);
              setRangeFrom(next.from);
              setRangeTo(next.to);
              setDatePreset('custom');
            }}
            onClose={() => setCalOpen(false)} />
          }
        </div>

        {/* Active context banner (from dashboard deep-link or manual date filter) */}
        {hasDateFilter &&
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12,
          padding: '9px 12px', borderRadius: 10,
          background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`
        }}>
            <span style={{ display: 'flex', color: TOKENS.primary, flexShrink: 0 }}>{I.cal(15, TOKENS.primary)}</span>
            <span style={{ fontSize: 12.5, fontWeight: 600, flex: 1, display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 }}>
              <span style={{ color: TOKENS.textMuted, fontWeight: 600, fontSize: 11.5, letterSpacing: '0.02em' }}>Mostrando {filter === 'entregado' ? 'entregados' : filter === 'pendiente' ? 'pendientes' : 'recogidos'}:</span>
              <span style={{ fontWeight: 700, color: TOKENS.text, fontSize: 13 }}>
                {dateMode === 'dia' ? window.fechaCorta(day) :
            rangeFrom && rangeTo ? `${window.fechaCorta(rangeFrom)} – ${window.fechaCorta(rangeTo)}` :
            rangeFrom ? `desde ${window.fechaCorta(rangeFrom)}` :
            `hasta ${window.fechaCorta(rangeTo)}`}
              </span>
            </span>
            <button onClick={() => {setDay(null);setRangeFrom(null);setRangeTo(null);setDatePreset(null);}} style={{
            display: 'inline-flex', alignItems: 'center', gap: 4, background: 'transparent',
            border: 'none', color: TOKENS.textMuted, fontSize: 12, fontWeight: 700,
            cursor: 'pointer', fontFamily: 'inherit', padding: 4
          }}>{I.x(14, TOKENS.textMuted)} Quitar</button>
          </div>
        }

        {/* Result count */}
        <div style={{ marginBottom: 10, padding: '0 4px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span style={{ fontSize: 10.5, fontWeight: 800, color: TOKENS.textMuted, letterSpacing: '0.06em', textTransform: 'uppercase' }}>{isAdmin ? 'Registros' : 'Mis registros'}</span>
            <span style={{ fontSize: 11.5, fontWeight: 700, color: TOKENS.textSubtle }}>{hayMas ? `${visible.length} de ${filtered.length}` : filtered.length}</span>
          </div>
        </div>

        {/* List */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {filtered.length === 0 &&
          <div style={{
            padding: 36, textAlign: 'center', color: TOKENS.textMuted, fontSize: 13,
            background: TOKENS.surfaceLow, borderRadius: 12, border: `1px dashed ${TOKENS.border}`,
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10
          }}>
              <div style={{
              width: 52, height: 52, borderRadius: 999, background: TOKENS.surfaceContainer,
              display: 'flex', alignItems: 'center', justifyContent: 'center'
            }}>{I.consultar(24, TOKENS.textSubtle)}</div>
              <div>
                <div style={{ fontWeight: 700, color: TOKENS.text, fontSize: 14, marginBottom: 4 }}>
                  {filter === 'pendiente' && sevFilter.length === 0 ? 'Selecciona un estado' : 'Sin resultados'}
                </div>
                <div>{filter === 'pendiente' && sevFilter.length === 0 ?
                  'Activa al menos un estado (Vencido, Retrasado, Vence hoy o En plazo) para ver registros.' :
                  'No encontramos registros que coincidan con tu búsqueda.'}</div>
              </div>
            </div>
          }
          {visible.map((t) =>
          <ConsultaCard key={t.id} ticket={t} onClick={() => {setSelectedId(t.id);setView('resumen');}} />
          )}
        </div>

        {/* Ver más registros (paginación local de 30 en 30) */}
        {hayMas &&
        <button type="button" onClick={() => setShown((s) => s + 30)} style={{
          width: '100%', marginTop: 14, padding: '13px 16px', borderRadius: 12,
          border: `1px solid ${TOKENS.border}`, background: TOKENS.surface, color: TOKENS.text,
          fontSize: 13.5, fontWeight: 700, fontFamily: 'inherit', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8
        }}>
          {I.chev(16)} Ver más registros
          <span style={{ color: TOKENS.textMuted, fontWeight: 600 }}>· {filtered.length - shown} restantes</span>
        </button>
        }
      </div>
      <BottomNav current="consultar" onNav={onNav || onBack} />
      {anularReactivarModals}
    </div>);

}

function HeroStat({ n, label, tone }) {
  const c =
  tone === 'pendiente' ? TOKENS.pendienteOnDark :
  tone === 'entregado' ? TOKENS.successOnDark :
  '#fff';
  return (
    <div style={{
      background: 'rgba(255,255,255,0.08)', borderRadius: 10,
      padding: '10px 12px', textAlign: 'center'
    }}>
      <div style={{ fontSize: 22, fontWeight: 700, color: c, lineHeight: 1 }}>{n}</div>
      <div style={{ fontSize: 10, opacity: 0.75, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', marginTop: 4 }}>
        {label}
      </div>
    </div>);

}

function FilterChip({ active, onClick, children, tone, activeColor, activeSoft }) {
  const accent = activeColor || TOKENS.primary; // regla de color (13/11/2026): la selección siempre en azul
  return (
    <button onClick={onClick} style={{
      padding: '7px 12px', borderRadius: 999, fontSize: 12, fontWeight: 700,
      // activeSoft (18/11/2026): Express y Garantía encendidos en su tono suave, como en las tarjetas.
      border: `1px solid ${active ? activeSoft ? activeSoft.bd : accent : TOKENS.border}`,
      background: active ? activeSoft ? activeSoft.bg : accent : TOKENS.surface,
      color: active ? activeSoft ? activeSoft.fg : '#fff' : TOKENS.text,
      cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap',
      letterSpacing: '0.02em', flexShrink: 0
    }}>{children}</button>);

}

// Tarjeta de Consultar (13/11/2026): la misma de Entregar. Placa en el recuadro gris,
// un solo chip de estado, taller/sede/aseguradora y abajo ítems + "Ver ›".
function ConsultaCard({ ticket, onClick }) {
  const sum = ticketSummary(ticket);
  const st = ticket._status;
  const corta = (f) => { const m = String(f || '').match(/(\d{1,2})\s*\/\s*(\d{1,2})/); return m ? `${m[1].padStart(2, '0')}/${m[2].padStart(2, '0')}` : ''; };
  const e = st === 'entregado' ? { label: `Entregado · ${corta(ticket.fechaEntrega)}`, bg: window.ENTREGADO_COLOR ? window.ENTREGADO_COLOR.bg : TOKENS.success, fg: '#fff' } :
  st === 'anulado' ? { label: 'Anulado', bg: TOKENS.anuladoBg, fg: TOKENS.anuladoText } :
  (() => { const x = window.estadoProcesos ? window.estadoProcesos(ticket) : null; return x ? { label: `${x.label} · ${x.dias} d`, bg: x.bg, fg: x.fg } : null; })();
  const partes = [
  sum.rines > 0 && `${sum.rines} ${sum.rines === 1 ? 'rin' : 'rines'}`,
  sum.llantas > 0 && `${sum.llantas} ${sum.llantas === 1 ? 'llanta' : 'llantas'}`,
  sum.valvulas > 0 && `${sum.valvulas} ${sum.valvulas === 1 ? 'válvula' : 'válvulas'}`].
  filter(Boolean).join(' · ') || 'Sin ítems';
  const espera = st === 'pendiente' && window.anulacionEnEspera && window.anulacionEnEspera(ticket.id);
  return <TarjetaPlaca ticket={ticket} onClick={onClick}
    chip={e && <span style={{ fontSize: 11.5, fontWeight: 500, borderRadius: 999, padding: '3px 9px', whiteSpace: 'nowrap', background: e.bg, color: e.fg }}>{e.label}</span>}
    extra={espera && window.ChipSolicitud ? <ChipSolicitud /> : st === 'entregado' && window.correccionEnEspera && window.correccionEnEspera(ticket._entrega ? ticket._entrega.ticketId : ticket.id) ? <window.ChipCorreccion /> : null} />;
}

function ConsultaRow({ ticket, onClick, onAnular, onReactivar }) {
  const sum = ticketSummary(ticket);
  const isDelivered = ticket._status === 'entregado';
  const isAnulado = ticket._status === 'anulado';
  const anuEvento = isAnulado && ticket._anulacion ? window.lastEventoTipo(ticket._anulacion, 'anulado') : null;

  // Composición por tipo (sin detalles — esos van en la ficha)
  const partes = [];
  if (sum.rines) partes.push(`${sum.rines} ${sum.rines === 1 ? 'rin' : 'rines'}`);
  if (sum.llantas) partes.push(`${sum.llantas} ${sum.llantas === 1 ? 'llanta' : 'llantas'}`);
  if (sum.valvulas) partes.push(`${sum.valvulas} ${sum.valvulas === 1 ? 'válvula' : 'válvulas'}`);
  const composicion = partes.join(' · ');

  // Severidad (solo pendientes)
  const sevLabels = { aldia: 'Al día', atrasado: 'Atrasado', critico: 'Crítico' };
  const sev = !isDelivered && !isAnulado && window.ticketSeverity ?
  window.ticketSeverity(ticket, new Date()) : null;
  const sevMeta = sev ? window.SEVERITY_META[sev.level] : null;

  return (
    <Card style={{ padding: '14px 14px', cursor: 'pointer' }}>
      <div onClick={onClick} style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
        {/* Columna izquierda: icono camión + contador de piezas debajo */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, flexShrink: 0 }}>
          <div style={{
            width: 42, height: 42, borderRadius: 10,
            background: isDelivered ? TOKENS.successBg : isAnulado ? TOKENS.anuladoBg : TOKENS.surfaceLow,
            color: isDelivered ? TOKENS.success : isAnulado ? TOKENS.anulado : TOKENS.primary,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            border: `1px solid ${TOKENS.border}`
          }}>{isDelivered ? I.check(22, TOKENS.success) : isAnulado ? I.ban(22, TOKENS.anulado) : I.truck(22, TOKENS.primary)}</div>
          <div style={{
            display: 'flex', flexDirection: 'column', alignItems: 'center',
            background: TOKENS.surface, padding: '4px 8px', borderRadius: 8,
            border: `1px solid ${TOKENS.border}`, minWidth: 42
          }}>
            <span style={{ fontSize: 16, fontWeight: 800, color: TOKENS.text, lineHeight: 1, fontFamily: 'monospace' }}>{sum.total}</span>
            <span style={{ fontSize: 8.5, fontWeight: 700, color: TOKENS.textMuted, letterSpacing: '0.06em', textTransform: 'uppercase', marginTop: 2 }}>
              {sum.total === 1 ? 'pieza' : 'piezas'}
            </span>
          </div>
        </div>

        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            fontSize: 11, fontWeight: 700, color: TOKENS.primary,
            background: TOKENS.surfaceLow, padding: '3px 8px', borderRadius: 6,
            border: `1px solid ${TOKENS.border}`, letterSpacing: '0.04em',
            fontFamily: 'monospace', marginBottom: 6
          }}>
            <span style={{ color: TOKENS.textMuted, fontWeight: 600 }}>N°</span>
            <span>{ticket.codigo}</span>
          </div>
          <div style={{
            fontSize: 18, fontWeight: 700, color: TOKENS.text,
            letterSpacing: '0.04em', wordBreak: 'break-all', lineHeight: 1.1
          }}>
            {ticket.placa}
          </div>
          <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 4 }}>
            {isDelivered ?
            <>Entregado: {ticket.fechaEntrega} · {window.formatHora12(ticket.horaEntrega)}</> :
            isAnulado && anuEvento ?
            <>Anulado: {anuEvento.fecha} · {window.formatHora12(anuEvento.hora)}</> :
            <>{ticket.fecha}{ticket.horaRecogida ? ` - ${window.formatHora12(ticket.horaRecogida)}` : ''}</>
            }
          </div>
          {isAnulado && anuEvento && anuEvento.motivo &&
          <div style={{
            display: 'inline-block', marginTop: 6, padding: '3px 9px',
            background: TOKENS.anuladoBg, color: TOKENS.anuladoText,
            borderRadius: 999, fontSize: 11, fontWeight: 700
          }}>{anuEvento.motivo}</div>
          }
          <div style={{ fontSize: 13, color: TOKENS.text, marginTop: 6, fontWeight: 600 }}>
            {ticket.taller} <span style={{ color: TOKENS.textMuted, fontWeight: 500 }}>· {ticket.sede}</span>
          </div>
          <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>
            {window.catAseguradoraCorta ? window.catAseguradoraCorta(ticket.aseguradora) : ticket.aseguradora}
          </div>
          {sum.total > 0 &&
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 8 }}>
              {sum.rines > 0 && <MiniStat n={sum.rines} label="Rines" />}
              {sum.llantas > 0 && <MiniStat n={sum.llantas} label="Llantas" />}
              {sum.valvulas > 0 && <MiniStat n={sum.valvulas} label="Válv." />}
            </div>
          }
          {isDelivered && ticket.factura &&
          <div style={{ fontSize: 11, color: TOKENS.textMuted, marginTop: 4 }}>
              Factura: <b style={{ color: TOKENS.text, fontFamily: 'monospace' }}>{ticket.factura}</b>
            </div>
          }
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 8, flexShrink: 0, alignSelf: 'stretch' }}>
          {isDelivered && <Chip tone="success">ENTREGADO</Chip>}
          {isAnulado && <Chip tone="anulado">ANULADO</Chip>}
          {sev && <SeverityTag level={sev.level} />}
          {sev && <DaysCount dias={sev.dias} level={sev.level} />}

          <div style={{ marginTop: 'auto', display: 'flex', flexDirection: 'column', gap: 6, alignItems: 'stretch', minWidth: 100 }}>
            {!isDelivered && !isAnulado && onAnular &&
            <button onClick={(e) => {e.stopPropagation();onAnular();}} style={{
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 5,
              padding: '7px 12px', borderRadius: 8, fontSize: 11, fontWeight: 700,
              background: TOKENS.anuladoBg, color: TOKENS.anuladoText,
              border: `1px solid ${TOKENS.anuladoBorder}`, cursor: 'pointer',
              fontFamily: 'inherit', letterSpacing: '0.02em'
            }}>{I.ban(12, TOKENS.anulado)} Anular</button>
            }
            {isAnulado && onReactivar &&
            <button onClick={(e) => {e.stopPropagation();onReactivar();}} style={{
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 5,
              padding: '7px 12px', borderRadius: 8, fontSize: 11, fontWeight: 700,
              background: TOKENS.primary, color: '#fff',
              border: 'none', cursor: 'pointer', fontFamily: 'inherit', letterSpacing: '0.02em'
            }}>{I.reactivar(12, '#fff')} Reactivar</button>
            }
            <button onClick={(e) => {e.stopPropagation();onClick && onClick();}} style={{
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 4,
              padding: '7px 12px', borderRadius: 8, fontSize: 11, fontWeight: 700,
              background: (isDelivered || isAnulado) ? '#fff' : TOKENS.primary,
              color: (isDelivered || isAnulado) ? TOKENS.text : '#fff',
              border: (isDelivered || isAnulado) ? `1px solid ${TOKENS.border}` : 'none',
              cursor: 'pointer', fontFamily: 'inherit', letterSpacing: '0.02em'
            }}>
              {isDelivered ? <>{I.print(12, TOKENS.text)} Detalle</> : <>{I.consultar(12, isAnulado ? TOKENS.text : '#fff')} Ver</>}
            </button>
          </div>
        </div>
      </div>
    </Card>);

}

Object.assign(window, { ConsultarScreen });