// ─── Notificaciones: pantalla, toasts y modales ─────────────────────────
// Depende de notifications.jsx (modelo + helpers) y shared.jsx (UI base).

// ── Modal: motivo de rechazo (campo libre) ──────────────────────────────
function RejectReasonModal({ notif, onDismiss, onConfirm }) {
  const [motivo, setMotivo] = React.useState('');
  const canSend = motivo.trim().length > 0;
  return (
    <div onClick={onDismiss} style={{
      position: 'fixed', inset: 0, background: 'rgba(11,28,48,0.5)', zIndex: 1200,
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: TOKENS.surface, borderRadius: '18px 18px 0 0',
        width: '100%', maxWidth: 440, padding: 18, paddingBottom: 24,
      }}>
        <div style={{ width: 36, height: 4, borderRadius: 2, background: TOKENS.border, margin: '0 auto 14px' }} />
        <div style={{ width: 46, height: 46, borderRadius: 999, background: TOKENS.dangerBg, display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 10 }}>{I.x(22, TOKENS.danger)}</div>
        <div style={{ fontSize: 19, fontWeight: 700, color: TOKENS.text, letterSpacing: '-0.01em' }}>
          ¿Rechazar esta ruta?
        </div>
        <div style={{ fontSize: 13, color: TOKENS.textMuted, marginTop: 3, marginBottom: 14 }}>
          {notif.taller} · {accionLabel(notif.accion)}. El motivo se le enviará al administrador.
        </div>
        <FieldLabel>Motivo del rechazo *</FieldLabel>
        <textarea
          value={motivo}
          onChange={(e) => setMotivo(e.target.value)}
          placeholder="Ej: tengo sobrecarga en el sur y no alcanzo hoy…"
          rows={4}
          autoFocus
          style={{
            width: '100%', boxSizing: 'border-box',
            border: `1px solid ${TOKENS.borderInput}`, background: TOKENS.surfaceLow,
            borderRadius: 10, padding: '10px 14px', fontSize: 14, color: TOKENS.text,
            fontFamily: 'inherit', outline: 'none', resize: 'vertical',
          }} />
        <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
          <Button variant="outline" full onClick={onDismiss}>Cancelar</Button>
          <Button variant="primary" full disabled={!canSend}
            icon={I.x(16, '#fff')}
            onClick={() => onConfirm(motivo.trim())}
            style={{ background: TOKENS.danger, borderColor: TOKENS.danger }}>
            Rechazar
          </Button>
        </div>
      </div>
    </div>);
}

// ── Acciones por deslizamiento (swipe) ───────────────────────────────────
// Mapeo: arrastrar a la IZQUIERDA = acción positiva (revelada a la derecha);
// arrastrar a la DERECHA = Rechazar (revelada a la izquierda, solo asignación).
function buildPositiveAction(notif, { onAccept, onReview, onAcknowledge }) {
  const t = notif.tipo;
  if (t === 'asignacion') return { color: TOKENS.primary, icon: I.check, label: 'Aceptar', armedLabel: 'Suelta para aceptar', run: () => onAccept(notif) };
  if (t === 'autoasignacion') return { color: TOKENS.primary, icon: I.consultar, label: 'Revisar', armedLabel: 'Suelta para revisar', run: () => onReview(notif) };
  return { color: TOKENS.textMuted, icon: I.check, label: 'Entendido', armedLabel: 'Suelta para confirmar', run: () => onAcknowledge(notif) };
}
function buildNegativeAction(notif, { onReject }) {
  if (notif.tipo === 'asignacion') return { color: TOKENS.danger, icon: I.x, label: 'Rechazar', armedLabel: 'Suelta para rechazar', run: () => onReject(notif) };
  return null;
}

function NotifActionPanel({ side, color, icon, label, armedLabel, armed, visible }) {
  const isRight = side === 'right';
  return (
    <div style={{
      position: 'absolute', inset: 0, background: color, borderRadius: 14,
      display: 'flex', alignItems: 'center',
      justifyContent: isRight ? 'flex-end' : 'flex-start',
      padding: '0 22px', opacity: visible ? 1 : 0,
    }}>
      <div style={{
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, color: '#fff',
        transform: armed ? 'scale(1.14)' : 'scale(1)', transition: 'transform 0.16s ease',
      }}>
        {icon(22, '#fff')}
        <span style={{ fontSize: 11, fontWeight: 800, letterSpacing: '0.01em', whiteSpace: 'nowrap' }}>
          {armed ? armedLabel : label}
        </span>
      </div>
    </div>);
}

function SwipeableNotif({ positive, negative, children }) {
  const wrapRef = React.useRef(null);
  const st = React.useRef({ down: false, drag: false, sx: 0, sy: 0, w: 320, id: null });
  const dxRef = React.useRef(0);
  const [dx, setDx] = React.useState(0);
  const [drag, setDrag] = React.useState(false);
  const [armed, setArmed] = React.useState(null);
  const apply = (v) => { dxRef.current = v; setDx(v); };

  const onPointerDown = (e) => {
    if (e.pointerType === 'mouse' && e.button !== 0) return;
    const s = st.current;
    s.down = true; s.drag = false;
    s.revealed = false; s.armedH = false;
    s.sx = e.clientX; s.sy = e.clientY;
    s.w = wrapRef.current?.offsetWidth || 320;
    s.id = e.pointerId;
  };

  React.useEffect(() => {
    const move = (e) => {
      const s = st.current;
      if (!s.down) return;
      const ddx = e.clientX - s.sx;
      const ddy = e.clientY - s.sy;
      if (!s.drag) {
        if (Math.abs(ddx) < 8 && Math.abs(ddy) < 8) return;
        if (Math.abs(ddx) <= Math.abs(ddy)) { s.down = false; return; } // vertical → dejar scroll
        s.drag = true; setDrag(true);
        try { wrapRef.current?.setPointerCapture(s.id); } catch (err) {}
      }
      let nx = ddx;
      if (nx < 0 && !positive) nx = 0;
      if (nx > 0 && !negative) nx = 0;
      const max = s.w * 0.9;                 // resistencia al final
      if (nx > max) nx = max + (nx - max) * 0.18;
      if (nx < -max) nx = -max + (nx + max) * 0.18;
      apply(nx);
      const mag = Math.abs(nx);
      const reveal = s.w * 0.2;
      const commit = s.w * 0.45;
      if (mag >= reveal && !s.revealed) { s.revealed = true; if (navigator.vibrate) navigator.vibrate(8); }
      else if (mag < reveal && s.revealed) { s.revealed = false; }
      const isArmed = mag >= commit;
      if (isArmed && !s.armedH) { s.armedH = true; if (navigator.vibrate) navigator.vibrate(15); }
      else if (!isArmed && s.armedH) { s.armedH = false; }
      setArmed(isArmed ? (nx < 0 ? 'pos' : 'neg') : null);
      if (e.cancelable) e.preventDefault();
    };
    const up = () => {
      const s = st.current;
      if (s.drag) {
        const commit = s.w * 0.45;
        const v = dxRef.current;
        if (v <= -commit && positive) positive.run();
        else if (v >= commit && negative) negative.run();
      }
      s.down = false; s.drag = false;
      setDrag(false); setArmed(null); apply(0);
    };
    window.addEventListener('pointermove', move, { passive: false });
    window.addEventListener('pointerup', up);
    window.addEventListener('pointercancel', up);
    return () => {
      window.removeEventListener('pointermove', move);
      window.removeEventListener('pointerup', up);
      window.removeEventListener('pointercancel', up);
    };
  }, [positive, negative]);

  return (
    <div ref={wrapRef} onPointerDown={onPointerDown} style={{
      position: 'relative', borderRadius: 14, overflow: 'hidden', touchAction: 'pan-y',
    }}>
      {positive && <NotifActionPanel side="right" {...positive} armed={armed === 'pos'} visible={dx < 0} />}
      {negative && <NotifActionPanel side="left" {...negative} armed={armed === 'neg'} visible={dx > 0} />}
      <div style={{
        position: 'relative', zIndex: 1, transform: `translateX(${dx}px)`,
        transition: drag ? 'none' : 'transform 0.3s cubic-bezier(0.2,0.85,0.25,1)', willChange: 'transform',
      }}>
        {children}
      </div>
    </div>);
}

// ── Tarjeta de aviso ─────────────────────────────────────────────────────
function NotifCard({ notif, role, onAccept, onReject, onReview, onAcknowledge, onIr, onDecidir }) {
  const c = accionColor(notif.accion);
  const pend = notif.estado === 'pendiente';
  const isAdmin = role === 'admin';
  const isRechazo = notif.tipo === 'rechazo';
  const isAnul = notif.tipo === 'anulacion';
  const isRuta = notif.tipo === 'ruta_update';
  const isNota = notif.tipo === 'nota';
  // Regla de color (13/11/2026): tarjeta neutra; solo la anulación conserva el morado.
  const accent = isAnul ? TOKENS.anulado : TOKENS.textMuted;
  const accentSoft = isAnul ? TOKENS.anuladoBg : TOKENS.surfaceLow;
  // Borde izquierdo = semáforo por estado: pendiente normal → naranja (atención);
  // crítico (rechazo/anulación) conserva su color fuerte; resuelto → neutro.
  const edgeColor = !pend ? TOKENS.border : (isRechazo ? TOKENS.danger : isAnul ? TOKENS.anulado : TOKENS.enCurso);
  const [showHist, setShowHist] = React.useState(false);
  const headIcon = isNota ? I.doc(20, TOKENS.textMuted) : isAnul ? I.ban(20, TOKENS.anulado) : isRechazo ? I.x(20, TOKENS.textMuted) : isRuta ? I.route(20, TOKENS.textMuted) : accionIcon(notif.accion, 20, TOKENS.textMuted);
  // Placa(s) del aviso: de la parada (recoger → placas; entregar → placa de cada consecutivo) o de la referencia "cod · placa".
  const placasAviso = (() => {
    try {
      if (notif.paradaId && window.loadParadas) {
        const p = window.loadParadas().find((x) => x.id === notif.paradaId);
        if (p && p.tipo === 'recoger' && (p.placas || []).length) return { placas: p.placas, extra: p.referencia ? String(p.referencia).replace(/^Recogida solicitada\s*[—-]\s*/i, '') : '' };
        if (p && p.tipo === 'entregar') {
          const all = [...(window.loadPendientesSaved ? window.loadPendientesSaved() : []), ...(window.PENDIENTES_DEMO || [])];
          const cods = (p.consecutivos || []).map(String);
          const pl = cods.map((c2) => (all.find((t) => String(t.codigo) === c2) || {}).placa).filter(Boolean);
          if (pl.length) return { placas: pl, cod: cods[0] };
        }
      }
      if (notif.accion === 'entregar' && notif.referencia) {
        const all = [...(window.loadPendientesSaved ? window.loadPendientesSaved() : []), ...(window.PENDIENTES_DEMO || [])];
        const cods = String(notif.referencia).split(/[,\s]+/).filter(Boolean);
        const pl = cods.map((c2) => (all.find((t) => String(t.codigo) === c2) || {}).placa).filter(Boolean);
        if (pl.length) return { placas: pl, cod: cods[0] };
      }
      const m = String(notif.referencia || '').match(/^(\S+)\s*·\s*(\S+)$/);
      if (m) return { placas: [m[2]], cod: m[1] };
    } catch (e) {}
    return null;
  })();
  // A dónde lleva tocar el aviso.
  const destino = isAnul || notif.tipo === 'correccion' ? 'consultar' : (isRuta || notif.tipo === 'asignacion' || notif.tipo === 'autoasignacion' || isRechazo) ? 'rutas' : null;
  const irA = () => {
    if (!destino || !onIr) return;
    if (destino === 'consultar') {
      let ticketId = null;
      try { const sol = notif.solicitudId && window.loadSolicitudesAnulacion ? window.loadSolicitudesAnulacion().find((x) => x.id === notif.solicitudId) : null; ticketId = sol ? sol.ticketId : null; } catch (e) {}
      onIr('consultar', ticketId);
    } else onIr('rutas');
  };
  const actorName = notif.actor === 'admin' ? 'El administrador' : ((window.nombreDeUsuario && window.nombreDeUsuario(notif.actor)) || 'El mensajero');

  // Encabezado contextual según tipo
  let headline, descr;
  if (notif.tipo === 'asignacion') {
    headline = `${accionLabel(notif.accion)} · ${notif.taller}`;
    descr = `Te asignaron esta ruta · Sede ${notif.sede}`;
  } else if (notif.tipo === 'autoasignacion') {
    headline = `${notif.taller} · ${accionLabel(notif.accion)}`;
    descr = `${actorName} asignó esta ruta · Sede ${notif.sede}`;
  } else if (isAnul) {
    headline = notif.titulo || `Registro anulado · ${notif.taller}`;
    descr = notif.mensaje || `${actorName} anuló un registro · Sede ${notif.sede}`;
  } else if (isRuta) {
    const kinds = new Set((notif.history || []).map((h) => h.kind).filter(Boolean));
    const mixed = (notif.count > 1) && kinds.size > 1;
    headline = mixed ? 'El admin actualizó tu ruta' : (notif.titulo || 'Tu ruta cambió');
    const latest = (notif.history && notif.history[0] && notif.history[0].detalle) || notif.detalle;
    descr = (notif.count > 1 && latest) ? `Último: ${latest}` : (notif.mensaje || 'El admin actualizó tu ruta de hoy.');
  } else if (isNota) {
    headline = notif.titulo || 'Nueva nota';
    descr = notif.mensaje || '';
  } else { // rechazo
    headline = `Ruta rechazada · ${notif.taller}`;
    descr = `${actorName} rechazó ${accionLabel(notif.accion).toLowerCase()} en ${notif.sede}`;
  }

  const resLabel = {
    aceptada: 'Aceptada', rechazada: 'Rechazada', revisada: 'Revisada', vista: 'Vista',
  }[notif.resolucion];
  const resColor = TOKENS.textMuted;

  // Solicitud de anulación que el admin todavía puede decidir (13/11/2026).
  const solAnu = isAnul && notif.solicitudId && window.loadSolicitudesAnulacion ? window.loadSolicitudesAnulacion().find((x) => x.id === notif.solicitudId) : null;
  const decidible = pend && role === 'admin' && !!onDecidir && !!solAnu && solAnu.estado === 'espera';
  const positive = pend && !decidible ? buildPositiveAction(notif, { onAccept, onReview, onAcknowledge }) : null;
  const negative = pend && !decidible ? buildNegativeAction(notif, { onReject }) : null;

  const body = (
    <div style={{
      background: TOKENS.surface, border: `1px solid ${TOKENS.border}`,
      borderRadius: 14, overflow: 'hidden', opacity: pend ? 1 : 0.72,
      borderColor: isAnul && pend ? TOKENS.anuladoBorder : TOKENS.border,
    }}>
      <div style={{ display: 'flex', gap: 12, padding: '13px 14px' }}>
        <div style={{
          width: 40, height: 40, borderRadius: 11, flexShrink: 0,
          background: accentSoft,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          {headIcon}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, justifyContent: 'space-between' }}>
            <div style={{ fontSize: 14.5, fontWeight: 700, color: TOKENS.text, letterSpacing: '-0.01em' }}>
              {headline}
            </div>
            <div style={{ fontSize: 10.5, color: TOKENS.textSubtle, fontWeight: 600, whiteSpace: 'nowrap', flexShrink: 0 }}>
              {relTime(notif.createdAt)}
            </div>
          </div>
          <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>{descr}</div>
          {notif.count > 1 && (
            <div style={{ marginTop: 8 }}>
              <button onClick={() => setShowHist((s) => !s)} style={{
                display: 'inline-flex', alignItems: 'center', gap: 5, padding: '3px 10px',
                borderRadius: 999, border: `1px solid ${TOKENS.border}`, whiteSpace: 'nowrap',
                background: TOKENS.surfaceLow,
                color: TOKENS.textMuted, fontSize: 11, fontWeight: 800, cursor: 'pointer', fontFamily: 'inherit',
              }}>
                Se actualizó {notif.count} veces
                <span style={{ display: 'inline-flex', transform: showHist ? 'rotate(180deg)' : 'none', transition: 'transform .15s' }}>{I.chev(13, TOKENS.textMuted)}</span>
              </button>
              {showHist && (
                <div style={{
                  marginTop: 8, paddingLeft: 10, borderLeft: `2px solid ${TOKENS.border}`,
                  display: 'flex', flexDirection: 'column', gap: 7,
                }}>
                  {(notif.history || []).map((h, i) => (
                    <div key={i} style={{ fontSize: 11.5, color: TOKENS.textMuted, lineHeight: 1.35 }}>
                      <span style={{ fontWeight: 700, color: TOKENS.text }}>{h.detalle || h.titulo || h.mensaje}</span>
                      <span style={{ color: TOKENS.textSubtle }}> · {relTime(h.ts)}</span>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}
          {placasAviso ? (
            <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginTop: 8, flexWrap: 'wrap', fontSize: 12, color: TOKENS.textMuted, fontWeight: 600 }}>
              <span style={{ fontFamily: "'JetBrains Mono', monospace", fontWeight: 600, fontSize: 14, background: TOKENS.surfaceLow, border: `1px solid ${TOKENS.border}`, borderRadius: 7, padding: '3px 8px', color: TOKENS.text }}>{placasAviso.placas[0]}</span>
              {placasAviso.placas.length > 1 && <span style={{ fontWeight: 700 }}>+{placasAviso.placas.length - 1}</span>}
              {placasAviso.cod && <span>N.º {placasAviso.cod}</span>}
              {placasAviso.extra && <span>{placasAviso.extra}</span>}
            </div>
          ) : notif.referencia ? (
            <div style={{
              marginTop: 8, padding: '5px 9px', background: TOKENS.surfaceLow,
              borderRadius: 7, fontSize: 12, color: TOKENS.text, fontWeight: 600,
              display: 'inline-block', maxWidth: '100%', wordBreak: 'break-word',
            }}>{notif.referencia}</div>
          ) : null}
          {(isRechazo || isAnul) && notif.motivo && (
            <div style={{
              marginTop: 8, padding: '8px 10px', background: accentSoft,
              borderRadius: 8, fontSize: 12.5, color: accent, lineHeight: 1.45,
              fontStyle: 'italic',
            }}>“{notif.motivo}”</div>
          )}

          {/* Acciones (solo si pendiente) o sello de resolución */}
          {pend ? (
            <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
              {notif.tipo === 'asignacion' && (
                <>
                  <button onClick={() => onReject(notif)} style={ghostBtn(TOKENS.text)}>
                    Rechazar
                  </button>
                  <button onClick={() => onAccept(notif)} style={solidBtn(TOKENS.primary)}>
                    {I.check(15, '#fff')} Aceptar
                  </button>
                </>
              )}
              {notif.tipo === 'autoasignacion' && (
                <button onClick={() => onReview(notif)} style={solidBtn(TOKENS.primary)}>
                  {I.consultar(15, '#fff')} Revisar ruta
                </button>
              )}
              {decidible ?
              <>
                  <button onClick={() => onDecidir(notif, 'rechazar')} style={ghostBtn(TOKENS.text)}>Rechazar</button>
                  <button onClick={() => onDecidir(notif, 'anular')} style={solidBtn(TOKENS.danger)}>{I.ban(15, '#fff')} Anular registro</button>
                </> :
              (isRechazo || isAnul || isRuta) && (
                <button onClick={() => onAcknowledge(notif)} style={ackBtn()}>
                  Entendido
                </button>
              )}
            </div>
          ) : (
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 5, marginTop: 10,
              fontSize: 11.5, fontWeight: 700, color: resColor,
            }}>
              {notif.resolucion === 'rechazada' ? I.x(14, resColor) : I.check(14, resColor)} {resLabel}{notif.resolvedAt ? ' · ' + relTime(notif.resolvedAt) : ''}
            </div>
          )}
          {destino && onIr &&
          <button type="button" onClick={irA} style={{ display: 'block', marginTop: 9, padding: 0, border: 0, background: 'none', fontFamily: 'inherit', fontSize: 12, fontWeight: 800, color: TOKENS.primary, cursor: 'pointer' }}>
              {destino === 'consultar' ? 'Ver placa ›' : 'Ver en Mi ruta ›'}
            </button>
          }
        </div>
      </div>
    </div>);

  if (pend && (positive || negative)) {
    return <SwipeableNotif positive={positive} negative={negative}>{body}</SwipeableNotif>;
  }
  return body;
}

function ghostBtn(color) {
  return {
    flex: 1, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 5,
    padding: '9px 10px', borderRadius: 10, fontSize: 12.5, fontWeight: 700,
    border: `1px solid ${color === TOKENS.danger ? TOKENS.dangerBorder : TOKENS.border}`,
    background: TOKENS.surface, color, cursor: 'pointer', fontFamily: 'inherit',
  };
}
function solidBtn(color) {
  return {
    flex: 1, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 5,
    padding: '9px 10px', borderRadius: 10, fontSize: 12.5, fontWeight: 700,
    border: 'none', background: color, color: '#fff', cursor: 'pointer', fontFamily: 'inherit',
  };
}
// Botón de "Entendido": gris claro (regla de color 13/11/2026).
function ackBtn() {
  return {
    flex: 1, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 5,
    padding: '9px 10px', borderRadius: 10, fontSize: 12.5, fontWeight: 700,
    border: `1px solid ${TOKENS.border}`,
    background: TOKENS.surfaceLow,
    color: TOKENS.text, cursor: 'pointer', fontFamily: 'inherit',
  };
}

// ── Pantalla de Notificaciones ───────────────────────────────────────────
function NotificacionesScreen({ role, onBack, onNav }) {
  const list = useNotifs(role);
  const [rejecting, setRejecting] = React.useState(null);

  const pendientes = list.filter(n => n.estado === 'pendiente')
    .sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));
  const resueltas = list.filter(n => n.estado === 'resuelta')
    .sort((a, b) => (b.resolvedAt || 0) - (a.resolvedAt || 0));

  const handleAccept = (n) => { acceptNotif(n); };
  const handleReject = (n) => setRejecting(n);
  const confirmReject = (motivo) => { rejectNotif(rejecting, motivo); setRejecting(null); };
  const handleReview = (n) => { reviewNotif(n); onNav && onNav('rutas'); };
  const handleAck = (n) => { acknowledgeNotif(n); };

  const [verAnteriores, setVerAnteriores] = React.useState(false);
  const irA = (dest, ticketId) => {
    if (dest === 'consultar' && window.__goToConsultarTicket) window.__goToConsultarTicket(ticketId);
    else onNav && onNav(dest);
  };
  const [decision, setDecision] = React.useState(null); // { notif, tipo: 'rechazar' | 'anular' }
  const cardProps = {
    role, onAccept: handleAccept, onReject: handleReject,
    onReview: handleReview, onAcknowledge: handleAck, onIr: irA,
    onDecidir: (notif, tipo) => setDecision({ notif, tipo }),
  };
  // Avisos que solo piden "Entendido" (para "Marcar todo como visto").
  const solEspera = (n) => {try {const x = n.solicitudId && window.loadSolicitudesAnulacion ? window.loadSolicitudesAnulacion().find((y) => y.id === n.solicitudId) : null;return !!(x && x.estado === 'espera' && role === 'admin');} catch (e) {return false;}};
  const informativos = pendientes.filter((n) => !['asignacion', 'autoasignacion'].includes(n.tipo) && !solEspera(n));

  return (
    <div style={{ background: TOKENS.bg, display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
      <AppHeader title="Notificaciones" onBack={onBack} bell={false} />
      <div style={{ flex: 1, padding: '16px 16px 28px', overflow: 'auto' }}>
        {list.length === 0 && (
          <div style={{
            padding: 40, textAlign: 'center', color: TOKENS.textMuted, fontSize: 13,
            background: TOKENS.surfaceLow, borderRadius: 12, border: `1px dashed ${TOKENS.border}`,
            marginTop: 12,
          }}>
            <div style={{ marginBottom: 8, display: 'flex', justifyContent: 'center' }}>{I.bell(28, TOKENS.textSubtle)}</div>
            <div style={{ fontWeight: 700, color: TOKENS.text, fontSize: 14, marginBottom: 4 }}>Sin notificaciones</div>
            <div>Aquí verás las rutas asignadas y los avisos del equipo.</div>
          </div>
        )}

        {pendientes.length > 0 && (
          <>
            <div style={{ ...notifSectionLabel, justifyContent: 'space-between' }}>
              <span>Sin resolver · {pendientes.length}</span>
              {informativos.length >= 2 &&
              <button type="button" onClick={() => informativos.forEach((n) => acknowledgeNotif(n))} style={{ border: 0, background: 'none', padding: 0, fontFamily: 'inherit', fontSize: 12, fontWeight: 800, color: TOKENS.primary, letterSpacing: 0, textTransform: 'none', cursor: 'pointer' }}>Marcar todo como visto</button>
              }
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {pendientes.map(n => <NotifCard key={n.id} notif={n} {...cardProps} />)}
            </div>
          </>
        )}

        {list.length > 0 && pendientes.length === 0 &&
        <div style={{ textAlign: 'center', color: TOKENS.textMuted, fontSize: 13, padding: '26px 10px 8px' }}>
            <div style={{ fontWeight: 700, color: TOKENS.text, fontSize: 14, marginBottom: 4 }}>Estás al día</div>
            No tienes avisos por resolver.
          </div>
        }

        {resueltas.length > 0 && (
          <>
            <button type="button" onClick={() => setVerAnteriores((v) => !v)} style={{
              width: '100%', display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 18,
              background: TOKENS.surface, border: `1px solid ${TOKENS.border}`, borderRadius: 12, padding: '11px 12px',
              fontFamily: 'inherit', fontSize: 13, fontWeight: 700, color: TOKENS.textMuted, cursor: 'pointer'
            }}>
              <span>Anteriores · {resueltas.length}</span>
              <span style={{ display: 'flex', transform: verAnteriores ? 'rotate(180deg)' : 'none', transition: 'transform .15s' }}>{I.chev(16, TOKENS.textMuted)}</span>
            </button>
            {verAnteriores &&
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 10 }}>
                {resueltas.slice(0, 30).map(n => <NotifCard key={n.id} notif={n} {...cardProps} />)}
              </div>
            }
          </>
        )}
      </div>
      <BottomNav current="notificaciones" onNav={onNav || onBack} />

      {decision && window.DecisionAnulacionModal &&
      <DecisionAnulacionModal
        solicitudId={decision.notif.solicitudId} tipo={decision.tipo}
        onDone={() => setDecision(null)} onDismiss={() => setDecision(null)} />
      }

      {rejecting && (
        <RejectReasonModal
          notif={rejecting}
          onDismiss={() => setRejecting(null)}
          onConfirm={confirmReject} />
      )}
    </div>);
}

const notifSectionLabel = {
  display: 'flex', alignItems: 'center', gap: 8,
  fontSize: 11.5, fontWeight: 700, color: TOKENS.textMuted,
  letterSpacing: '0.06em', textTransform: 'uppercase', margin: '4px 2px 11px',
};

// ── Toasts: aparecen al entrar, se auto-ocultan, abren Notificaciones ────
function NotifToasts({ role, onOpen }) {
  const [toasts, setToasts] = React.useState([]);

  React.useEffect(() => {
    let toasted = [];
    try { toasted = JSON.parse(sessionStorage.getItem('rodando.toasted') || '[]'); } catch {}
    const pend = notifsFor(role).filter(n => n.estado === 'pendiente' && !toasted.includes(n.id));
    if (pend.length === 0) return;
    setToasts(pend);
    const ids = [...toasted, ...pend.map(n => n.id)];
    try { sessionStorage.setItem('rodando.toasted', JSON.stringify(ids)); } catch {}
    const timers = pend.map((n, i) =>
      setTimeout(() => setToasts(ts => ts.filter(t => t.id !== n.id)), 4500 + i * 600));
    return () => timers.forEach(clearTimeout);
  }, [role]);

  if (toasts.length === 0) return null;

  return (
    <div style={{
      position: 'absolute', top: 10, left: 12, right: 12, zIndex: 1100,
      display: 'flex', flexDirection: 'column', gap: 8, pointerEvents: 'none',
    }}>
      {toasts.map(n => {
        const isRechazo = n.tipo === 'rechazo';
        const isAnul = n.tipo === 'anulacion';
        const isRuta = n.tipo === 'ruta_update';
        const c = isAnul ? TOKENS.anulado : TOKENS.textMuted;
        const title = n.tipo === 'nota' ? (n.titulo || 'Nueva nota') : isAnul ? (n.titulo || 'Registro anulado')
          : isRechazo ? 'Ruta rechazada'
          : isRuta ? (n.titulo || 'Tu ruta cambió')
          : n.tipo === 'autoasignacion' ? 'Nueva autoasignación'
          : 'Nueva ruta asignada';
        const sub = n.tipo === 'nota' ? (n.mensaje || '') : isAnul ? (n.mensaje || `${n.taller} · ${n.sede}`)
          : isRechazo ? `${n.taller} · ${n.sede}`
          : isRuta ? (n.mensaje || 'El admin actualizó tu ruta.')
          : n.tipo === 'autoasignacion' ? `${(window.nombreDeUsuario && window.nombreDeUsuario(n.actor)) || 'Mensajero'} · ${n.taller}`
          : `${accionLabel(n.accion)} · ${n.taller}`;
        const toastIcon = n.tipo === 'nota' ? I.doc(19, c) : isAnul ? I.ban(19, TOKENS.anulado) : isRechazo ? I.x(19, c) : isRuta ? I.route(19, c) : accionIcon(n.accion, 19, c);
        return (
          <button key={n.id}
            onClick={() => { setToasts(ts => ts.filter(t => t.id !== n.id)); onOpen && onOpen(); }}
            style={{
              pointerEvents: 'auto', display: 'flex', alignItems: 'center', gap: 11,
              width: '100%', textAlign: 'left', padding: '11px 13px', borderRadius: 13,
              background: '#fff', border: `1px solid ${TOKENS.border}`,
              boxShadow: '0 10px 30px rgba(11,28,48,0.18)', cursor: 'pointer', fontFamily: 'inherit',
              animation: 'rdToastIn 0.32s cubic-bezier(0.16,1,0.3,1)',
            }}>
            <div style={{
              width: 38, height: 38, borderRadius: 10, flexShrink: 0,
              background: isAnul ? TOKENS.anuladoBg : isRechazo ? TOKENS.dangerBg : `${c}15`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>{toastIcon}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 800, color: TOKENS.text }}>{title}</div>
              <div style={{ fontSize: 11.5, color: TOKENS.textMuted, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{sub}</div>
            </div>
            <div style={{ flexShrink: 0, display: 'flex', alignItems: 'center', gap: 3, fontSize: 11.5, fontWeight: 700, color: TOKENS.primary }}>
              Ver {I.arrowR(14, TOKENS.primary)}
            </div>
          </button>);
      })}
    </div>);
}

Object.assign(window, { NotificacionesScreen, NotifToasts, RejectReasonModal, NotifCard });
