// ─── Public screens: solicitud de recogida (talleres) + seguimiento ─────
// Acceso sin login, vía URL pública con QR.
//   ?solicitud=<tallerId>           → formulario de solicitud
//   ?seguimiento=<solicitudId>      → estado de la solicitud

function getTallerById(id) {
  return TALLERES_COORDS.find((t) => t.id === id);
}

// localStorage para "mis solicitudes" en este dispositivo (taller side)
const LS_MIS_SOLICITUDES = 'rodando.mis-solicitudes';
function pushMiSolicitud(solicitudId) {
  try {
    const arr = JSON.parse(localStorage.getItem(LS_MIS_SOLICITUDES) || '[]');
    if (!arr.includes(solicitudId)) {
      arr.unshift(solicitudId);
      localStorage.setItem(LS_MIS_SOLICITUDES, JSON.stringify(arr.slice(0, 30)));
    }
  } catch {}
}
function getMisSolicitudes() {
  try { return JSON.parse(localStorage.getItem(LS_MIS_SOLICITUDES) || '[]'); }
  catch { return []; }
}

// ─── Public layout wrapper (no iOS frame, branding propio) ──────────────
function PublicShell({ children }) {
  return (
    <div style={{
      minHeight: '100vh', background: '#e9eef5',
      display: 'flex', flexDirection: 'column', alignItems: 'center',
      fontFamily: 'Inter, -apple-system, system-ui, sans-serif', color: TOKENS.text,
      padding: '0',
    }}>
      <div style={{
        width: '100%', maxWidth: 480, minHeight: '100vh',
        background: TOKENS.bg, boxSizing: 'border-box',
        boxShadow: '0 0 0 1px rgba(11,28,48,0.08)',
        display: 'flex', flexDirection: 'column',
      }}>
        {children}
      </div>
    </div>
  );
}

function PublicBrandHeader({ subtitle }) {
  return (
    <div style={{
      background: TOKENS.heroGradient, color: '#fff',
      padding: '18px 18px 16px',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <RodandoTile size={34} radius={8} />
        <div>
          <div style={{ fontSize: 17, fontWeight: 700, letterSpacing: '0.02em' }}>Rodando</div>
          <div style={{ fontSize: 11, opacity: 0.75 }}>Salvallantas · Recolección</div>
        </div>
      </div>
      {subtitle && (
        <div style={{ fontSize: 12, opacity: 0.85, marginTop: 10, lineHeight: 1.5 }}>
          {subtitle}
        </div>
      )}
    </div>
  );
}

// ─── Solicitud de recogida (taller) ──────────────────────────────────────
function PublicSolicitudScreen({ tallerId, onSent }) {
  const taller = getTallerById(tallerId);

  // Si no encuentra el taller, muestra error
  if (!taller) {
    return (
      <PublicShell>
        <PublicBrandHeader />
        <div style={{ padding: 24, textAlign: 'center', flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column' }}>
          <div style={{
            width: 64, height: 64, borderRadius: 999, background: TOKENS.dangerBg, color: TOKENS.danger,
            display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 28, fontWeight: 700, margin: '0 auto 16px',
          }}>!</div>
          <div style={{ fontSize: 18, fontWeight: 700, color: TOKENS.text }}>Enlace inválido</div>
          <div style={{ fontSize: 13, color: TOKENS.textMuted, marginTop: 6, maxWidth: 280 }}>
            No reconocemos el taller solicitado. Verifica el código QR con tu coordinador.
          </div>
        </div>
      </PublicShell>
    );
  }

  const [solicitanteId, setSolicitanteId] = React.useState(taller.usuarios[0]?.id || 'otro');
  const [solicitanteNombre, setSolicitanteNombre] = React.useState('');
  const [solicitanteCargo, setSolicitanteCargo] = React.useState('');
  const [solicitanteTelefono, setSolicitanteTelefono] = React.useState('');

  const [tiposSeleccionados, setTiposSeleccionados] = React.useState([]); // ['rin', 'llanta', 'valvula']
  const [cantidadEstim, setCantidadEstim] = React.useState('');
  const [descripcion, setDescripcion] = React.useState('');
  const [ventana, setVentana] = React.useState('cualquiera'); // 'mañana' | 'tarde' | 'cualquiera'
  const [prioridad, setPrioridad] = React.useState('normal');
  const [foto, setFoto] = React.useState(null);
  const [submitting, setSubmitting] = React.useState(false);
  const fileRef = React.useRef(null);

  const isOtro = solicitanteId === 'otro';
  const knownUser = taller.usuarios.find((u) => u.id === solicitanteId);

  // Validación
  const nombre = isOtro ? solicitanteNombre.trim() : (knownUser?.nombre || '');
  const cargo = isOtro ? solicitanteCargo.trim() : (knownUser?.cargo || '');
  const telefono = isOtro ? solicitanteTelefono.trim() : (knownUser?.telefono || '');
  const canSubmit =
    nombre.length > 1 &&
    tiposSeleccionados.length > 0 &&
    !!foto &&
    !submitting;

  const toggleTipo = (t) => setTiposSeleccionados((arr) => arr.includes(t) ? arr.filter((x) => x !== t) : [...arr, t]);

  const handleFile = (file) => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = async () => { const s = await window.downscaleDataURL(reader.result, 1100, 0.6); setFoto(s); };
    reader.readAsDataURL(file);
  };

  const handleSubmit = () => {
    if (!canSubmit) return;
    setSubmitting(true);
    const now = Date.now();
    const referencia = (() => {
      const labels = tiposSeleccionados.map((t) =>
        t === 'rin' ? 'rines' : t === 'llanta' ? 'llantas' : 'válvulas'
      );
      const qty = cantidadEstim ? `${cantidadEstim} ` : '';
      return `Recogida de ${qty}${labels.join(' + ')}`.trim();
    })();
    const ventanaTexto =
      ventana === 'mañana' ? 'Mañana (8am – 12m)' :
      ventana === 'tarde' ? 'Tarde (1pm – 6pm)' : 'Cualquier horario';
    const parada = {
      id: 'sol-' + now,
      fecha: fechaDDMMYYYY(),
      asignadoA: 'juan-diego',
      tipo: 'recoger',
      tallerId: taller.id, taller: taller.nombre, sede: taller.sede,
      direccion: taller.direccion, ciudad: taller.ciudad,
      lat: taller.lat, lng: taller.lng,
      referencia,
      tiposSeleccionados,
      cantidadEstim: cantidadEstim ? Number(cantidadEstim) : null,
      ventana, ventanaTexto,
      estado: 'pendiente',
      creadaPor: 'taller',
      solicitante: { nombre, cargo, telefono },
      prioridad,
      notas: descripcion.trim(),
      fotos: foto ? [foto] : [],
      createdAt: now, updatedAt: now,
    };
    addParada(parada);
    pushMiSolicitud(parada.id);
    onSent && onSent(parada);
  };

  return (
    <PublicShell>
      <PublicBrandHeader subtitle="Completa el formulario para que un mensajero pase a recoger los productos." />

      <div style={{ padding: 16, flex: 1 }}>
        {/* Taller card */}
        <Card style={{ marginBottom: 14, padding: '14px 16px' }}>
          <div style={{ fontSize: 10, fontWeight: 700, color: TOKENS.textMuted, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 4 }}>
            Solicitando recogida desde
          </div>
          <div style={{ fontSize: 18, fontWeight: 700, color: TOKENS.text }}>
            {taller.nombre} · {taller.sede}
          </div>
          <div style={{ fontSize: 13, color: TOKENS.textMuted, marginTop: 2 }}>
            {taller.direccion}, {taller.ciudad}
          </div>
        </Card>

        {/* Solicitante */}
        <SectionTitle>¿Quién solicita?</SectionTitle>
        <Card style={{ marginBottom: 14 }}>
          <FieldLabel>Selecciona tu nombre</FieldLabel>
          <Select
            value={solicitanteId}
            options={[
              ...taller.usuarios.map((u) => ({ value: u.id, label: `${u.nombre} — ${u.cargo}` })),
              { value: 'otro', label: '+ Otro (escribir nombre)' },
            ]}
            onChange={setSolicitanteId}
            placeholder="Seleccionar"
            searchable
          />

          {isOtro && (
            <div style={{ marginTop: 12, paddingTop: 12, borderTop: `1px dashed ${TOKENS.border}` }}>
              <FieldLabel>Nombre completo *</FieldLabel>
              <TextInput value={solicitanteNombre} onChange={setSolicitanteNombre} placeholder="Ej: Juan Pérez" />
              <div style={{ height: 10 }} />
              <FieldLabel>Cargo</FieldLabel>
              <TextInput value={solicitanteCargo} onChange={setSolicitanteCargo} placeholder="Ej: Asistente" />
              <div style={{ height: 10 }} />
              <FieldLabel>Teléfono / WhatsApp</FieldLabel>
              <TextInput value={solicitanteTelefono} onChange={setSolicitanteTelefono} placeholder="+57 300 000 0000" />
            </div>
          )}

          {!isOtro && knownUser && (
            <div style={{
              marginTop: 10, padding: '10px 12px',
              background: TOKENS.surfaceLow, borderRadius: 8,
              fontSize: 12, color: TOKENS.textMuted, lineHeight: 1.5,
            }}>
              <div><b style={{ color: TOKENS.text }}>{knownUser.nombre}</b> — {knownUser.cargo}</div>
              <div>{knownUser.telefono}</div>
            </div>
          )}
        </Card>

        {/* Qué recoger */}
        <SectionTitle>¿Qué hay que recoger?</SectionTitle>
        <Card style={{ marginBottom: 14 }}>
          <FieldLabel>Tipo de producto *</FieldLabel>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
            {[
              { v: 'rin', l: 'Rines', icon: I.rin },
              { v: 'llanta', l: 'Llantas', icon: I.llanta },
              { v: 'valvula', l: 'Válvulas', icon: I.ajustes },
            ].map((opt) => {
              const active = tiposSeleccionados.includes(opt.v);
              return (
                <button key={opt.v} onClick={() => toggleTipo(opt.v)} style={{
                  padding: '14px 6px', borderRadius: 10,
                  border: `1.5px solid ${active ? TOKENS.primary : TOKENS.borderInput}`,
                  background: active ? TOKENS.surfaceLow : TOKENS.surface,
                  color: active ? TOKENS.primary : TOKENS.text,
                  cursor: 'pointer', fontFamily: 'inherit', fontWeight: 700, fontSize: 12,
                  display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
                }}>
                  {opt.icon(22, active ? TOKENS.primary : TOKENS.textMuted)}
                  <span>{opt.l}</span>
                </button>
              );
            })}
          </div>

          <div style={{ height: 14 }} />
          <FieldLabel>Cantidad estimada (opcional)</FieldLabel>
          <TextInput
            value={cantidadEstim}
            onChange={(v) => setCantidadEstim(v.replace(/[^0-9]/g, '').slice(0, 3))}
            placeholder="Ej: 4"
            type="text"
          />

          <div style={{ height: 14 }} />
          <FieldLabel>Notas para el mensajero (opcional)</FieldLabel>
          <textarea
            value={descripcion}
            onChange={(e) => setDescripcion(e.target.value)}
            placeholder="Ej: Rines maquinados, están en bodega 2."
            rows={3}
            style={{
              width: '100%', boxSizing: 'border-box',
              border: `1px solid ${TOKENS.borderInput}`,
              background: TOKENS.surfaceLow,
              borderRadius: 10, padding: '10px 14px',
              fontSize: 13, color: TOKENS.text,
              fontFamily: 'inherit', outline: 'none', resize: 'vertical',
            }}
          />
        </Card>

        {/* Horario + prioridad */}
        <SectionTitle>Ventana y prioridad</SectionTitle>
        <Card style={{ marginBottom: 14 }}>
          <FieldLabel>Cuándo prefieres que pasen</FieldLabel>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 6 }}>
            {[
              { v: 'mañana', l: 'Mañana' },
              { v: 'tarde', l: 'Tarde' },
              { v: 'cualquiera', l: 'Cualquiera' },
            ].map((opt) => (
              <button key={opt.v} onClick={() => setVentana(opt.v)} style={{
                padding: '10px 6px', borderRadius: 8, fontSize: 12, fontWeight: 700,
                border: `1px solid ${ventana === opt.v ? TOKENS.primary : TOKENS.borderInput}`,
                background: ventana === opt.v ? TOKENS.primary : TOKENS.surfaceLow,
                color: ventana === opt.v ? '#fff' : TOKENS.text,
                cursor: 'pointer', fontFamily: 'inherit',
              }}>{opt.l}</button>
            ))}
          </div>

          <div style={{ height: 14 }} />
          <FieldLabel>Prioridad</FieldLabel>
          <div style={{ display: 'flex', gap: 6 }}>
            {[
              { v: 'normal', l: 'Normal' },
              { v: 'alta', l: 'Alta · es urgente' },
            ].map((opt) => (
              <button key={opt.v} onClick={() => setPrioridad(opt.v)} style={{
                flex: 1, padding: '10px 8px', borderRadius: 8, fontSize: 12, fontWeight: 700,
                border: `1px solid ${prioridad === opt.v ? (opt.v === 'alta' ? TOKENS.danger : TOKENS.primary) : TOKENS.borderInput}`,
                background: prioridad === opt.v ? (opt.v === 'alta' ? TOKENS.danger : TOKENS.primary) : TOKENS.surfaceLow,
                color: prioridad === opt.v ? '#fff' : TOKENS.text,
                cursor: 'pointer', fontFamily: 'inherit',
              }}>{opt.l}</button>
            ))}
          </div>
        </Card>

        {/* Foto */}
        <SectionTitle>Foto del producto *</SectionTitle>
        <Card style={{ marginBottom: 14 }}>
          <input
            ref={fileRef}
            type="file"
            accept="image/*"
            capture="environment"
            style={{ display: 'none' }}
            onChange={(e) => handleFile(e.target.files?.[0])}
          />
          {!foto ? (
            <button onClick={() => fileRef.current?.click()} style={{
              width: '100%', padding: '28px 12px', borderRadius: 12,
              border: `2px dashed ${TOKENS.borderInput}`, background: TOKENS.surfaceLow,
              color: TOKENS.primary, cursor: 'pointer', fontFamily: 'inherit',
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
            }}>
              <div style={{
                width: 52, height: 52, borderRadius: 999,
                background: TOKENS.surface, border: `1px solid ${TOKENS.border}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>{I.cam(26, TOKENS.primary)}</div>
              <div style={{ fontSize: 14, fontWeight: 700 }}>Tomar foto del producto</div>
              <div style={{ fontSize: 12, color: TOKENS.textMuted, fontWeight: 500, textAlign: 'center', maxWidth: 240 }}>
                Esto ayuda al mensajero a saber qué buscar y a hacer un acta visual del estado.
              </div>
            </button>
          ) : (
            <div>
              <img src={foto} alt="Producto a recoger" style={{
                width: '100%', borderRadius: 12, border: `1px solid ${TOKENS.border}`,
                display: 'block', maxHeight: 320, objectFit: 'contain', background: '#000',
              }} />
              <div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
                <Button variant="outline" full icon={I.cam(16, TOKENS.text)} onClick={() => fileRef.current?.click()}>
                  Cambiar
                </Button>
                <Button variant="outline" full icon={I.x(16, TOKENS.danger)} onClick={() => setFoto(null)} style={{ color: TOKENS.danger, borderColor: TOKENS.borderInput, borderWidth: 1.5 }}>
                  Quitar
                </Button>
              </div>
            </div>
          )}
        </Card>

        {!canSubmit && !submitting && (
          <div style={{
            padding: '12px 14px', background: TOKENS.warningBg, border: `1px solid ${TOKENS.warningBorder}`,
            borderRadius: 10, fontSize: 12, color: TOKENS.warningText, fontWeight: 600,
            marginBottom: 14, display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <span style={{
              display: 'inline-flex', width: 18, height: 18, borderRadius: 999,
              background: TOKENS.warning, color: TOKENS.warningText, alignItems: 'center', justifyContent: 'center',
              fontSize: 11, fontWeight: 700, flexShrink: 0,
            }}>!</span>
            <span>
              {nombre.length < 2 && 'Indica tu nombre. '}
              {tiposSeleccionados.length === 0 && 'Elige al menos un tipo de producto. '}
              {!foto && 'Adjunta una foto del producto.'}
            </span>
          </div>
        )}
      </div>

      <div style={{
        padding: '12px 16px 18px', borderTop: `1px solid ${TOKENS.border}`,
        background: TOKENS.bg, position: 'sticky', bottom: 0,
      }}>
        <Button variant="primary" full icon={I.truck(16, '#fff')} disabled={!canSubmit} onClick={handleSubmit}>
          {submitting ? 'Enviando…' : 'Solicitar recogida'}
        </Button>
      </div>
    </PublicShell>
  );
}

// ─── Pantalla de éxito tras enviar solicitud ─────────────────────────────
function SolicitudExitoScreen({ parada, onTrack, onNew }) {
  const seguimientoUrl = `${window.location.origin}${window.location.pathname}?seguimiento=${parada.id}`;

  const copyLink = async () => {
    try {
      await navigator.clipboard.writeText(seguimientoUrl);
      alert('Enlace copiado al portapapeles.');
    } catch {
      prompt('Copia este enlace:', seguimientoUrl);
    }
  };

  return (
    <PublicShell>
      <PublicBrandHeader />
      <div style={{ padding: 24, flex: 1, display: 'flex', flexDirection: 'column' }}>
        <div style={{
          width: 88, height: 88, borderRadius: 999, background: TOKENS.successBg,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          margin: '20px auto 20px',
        }}>
          <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke={TOKENS.success} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M20 6L9 17l-5-5" />
          </svg>
        </div>
        <div style={{ fontSize: 22, fontWeight: 700, color: TOKENS.text, textAlign: 'center' }}>
          ¡Solicitud enviada!
        </div>
        <div style={{ fontSize: 13, color: TOKENS.textMuted, textAlign: 'center', marginTop: 8, lineHeight: 1.5 }}>
          Un mensajero recibirá tu solicitud y la atenderá pronto. Te avisaremos por el enlace de seguimiento.
        </div>

        <div style={{
          marginTop: 24, padding: 16, background: TOKENS.surface,
          border: `1px solid ${TOKENS.border}`, borderRadius: 14,
        }}>
          <SuccessRow k="N° solicitud" v={parada.id.replace('sol-', '#')} mono />
          <Divider />
          <SuccessRow k="Taller" v={`${parada.taller} · ${parada.sede}`} />
          <Divider />
          <SuccessRow k="Solicitante" v={parada.solicitante.nombre} />
          <Divider />
          <SuccessRow k="Fecha" v={parada.fecha} />
          <Divider />
          <SuccessRow k="Estado" v="PENDIENTE" />
        </div>

        <div style={{
          marginTop: 14, padding: '12px 14px',
          background: TOKENS.surfaceLow, borderRadius: 10,
          fontSize: 12, color: TOKENS.textMuted, lineHeight: 1.5,
        }}>
          <b style={{ color: TOKENS.text }}>Guarda el enlace de seguimiento</b> para ver el estado en tiempo real:
          <div style={{
            marginTop: 6, padding: '8px 10px', background: TOKENS.surface,
            border: `1px solid ${TOKENS.border}`, borderRadius: 8,
            fontSize: 11, color: TOKENS.text, fontFamily: 'monospace',
            wordBreak: 'break-all',
          }}>{seguimientoUrl}</div>
        </div>

        <div style={{ marginTop: 18, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <Button variant="outline" full onClick={copyLink}>Copiar enlace</Button>
          <Button variant="primary" full onClick={onTrack}>Ver seguimiento</Button>
        </div>
        <div style={{ marginTop: 10 }}>
          <Button variant="outline" full onClick={onNew}>Hacer otra solicitud</Button>
        </div>
      </div>
    </PublicShell>
  );
}

// ─── Seguimiento (estado en vivo) ────────────────────────────────────────
function PublicSeguimientoScreen({ solicitudId }) {
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setTick((t) => t + 1), 4000);
    const refresh = () => setTick((t) => t + 1);
    window.addEventListener('storage', refresh);
    window.addEventListener('focus', refresh);
    return () => {
      clearInterval(id);
      window.removeEventListener('storage', refresh);
      window.removeEventListener('focus', refresh);
    };
  }, []);
  const parada = (loadParadas().find((p) => p.id === solicitudId)) || null;

  if (!parada) {
    return (
      <PublicShell>
        <PublicBrandHeader />
        <div style={{ padding: 24, textAlign: 'center', flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column' }}>
          <div style={{
            width: 64, height: 64, borderRadius: 999, background: TOKENS.dangerBg, color: TOKENS.danger,
            display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 28, fontWeight: 700, margin: '0 auto 16px',
          }}>!</div>
          <div style={{ fontSize: 18, fontWeight: 700, color: TOKENS.text }}>Solicitud no encontrada</div>
          <div style={{ fontSize: 13, color: TOKENS.textMuted, marginTop: 6, maxWidth: 280 }}>
            No encontramos esta solicitud. Verifica el enlace de seguimiento.
          </div>
        </div>
      </PublicShell>
    );
  }

  const steps = [
    { id: 'pendiente', label: 'Solicitud recibida', desc: 'Estamos asignando un mensajero.' },
    { id: 'en_curso', label: 'Mensajero en camino', desc: 'El mensajero está en ruta hacia tu taller.' },
    { id: 'completada', label: 'Recogido', desc: 'Productos recogidos exitosamente.' },
  ];
  if (parada.estado === 'cancelada') {
    steps.push({ id: 'cancelada', label: 'Cancelada', desc: 'Esta solicitud fue cancelada.' });
  }
  const currentIdx = parada.estado === 'cancelada'
    ? steps.length - 1
    : steps.findIndex((s) => s.id === parada.estado);

  return (
    <PublicShell>
      <PublicBrandHeader />
      <div style={{ padding: 16, flex: 1 }}>
        <Card style={{ marginBottom: 14, padding: '14px 16px' }}>
          <div style={{ fontSize: 10, fontWeight: 700, color: TOKENS.textMuted, letterSpacing: '0.08em', textTransform: 'uppercase' }}>
            Solicitud {parada.id.replace('sol-', '#')}
          </div>
          <div style={{ fontSize: 18, fontWeight: 700, color: TOKENS.text, marginTop: 4 }}>
            {parada.taller} · {parada.sede}
          </div>
          <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>
            {parada.direccion}
          </div>
          <div style={{ marginTop: 10, display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            <Chip tone={parada.estado === 'completada' ? 'success' : parada.estado === 'cancelada' ? 'danger' : 'neutral'}>
              {estadoLabel(parada.estado)}
            </Chip>
            {parada.prioridad === 'alta' && <Chip tone="danger">PRIORIDAD ALTA</Chip>}
          </div>
        </Card>

        {/* Stepper */}
        <Card style={{ marginBottom: 14, padding: 18 }}>
          <div style={{ fontSize: 10, fontWeight: 700, color: TOKENS.textMuted, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 14 }}>
            Estado de la recogida
          </div>
          <div>
            {steps.map((s, i) => {
              const done = i < currentIdx || (parada.estado === 'completada' && s.id === 'completada');
              const active = i === currentIdx && parada.estado !== 'cancelada';
              const isCancelled = s.id === 'cancelada';
              const color = isCancelled ? TOKENS.danger : done || active ? TOKENS.success : TOKENS.textSubtle;
              return (
                <div key={s.id} style={{ display: 'flex', gap: 12, marginBottom: i === steps.length - 1 ? 0 : 14, position: 'relative' }}>
                  {i < steps.length - 1 && (
                    <div style={{
                      position: 'absolute', left: 13, top: 28,
                      width: 2, height: '100%', background: done ? TOKENS.success : TOKENS.border,
                    }} />
                  )}
                  <div style={{
                    width: 28, height: 28, borderRadius: 999, flexShrink: 0,
                    background: done || active || isCancelled ? color : TOKENS.surface,
                    border: `2px solid ${color}`,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    color: '#fff', fontWeight: 700, zIndex: 1,
                  }}>
                    {done && I.check(14, '#fff')}
                    {active && <div style={{ width: 8, height: 8, borderRadius: 999, background: '#fff' }} />}
                    {isCancelled && <span style={{ fontSize: 16, fontWeight: 700 }}>×</span>}
                  </div>
                  <div style={{ flex: 1, paddingTop: 2 }}>
                    <div style={{ fontSize: 13, fontWeight: 700, color: done || active || isCancelled ? TOKENS.text : TOKENS.textSubtle }}>
                      {s.label}
                    </div>
                    <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 2, lineHeight: 1.4 }}>
                      {s.desc}
                    </div>
                    {active && parada.iniciadaEn && s.id === 'en_curso' && (
                      <div style={{ fontSize: 11, color: TOKENS.success, fontWeight: 600, marginTop: 4 }}>
                        Iniciada {new Date(parada.iniciadaEn).toLocaleTimeString('es-CO', { hour: '2-digit', minute: '2-digit' })}
                      </div>
                    )}
                    {done && parada.completadaEn && s.id === 'completada' && (
                      <div style={{ fontSize: 11, color: TOKENS.success, fontWeight: 600, marginTop: 4 }}>
                        Completada {new Date(parada.completadaEn).toLocaleTimeString('es-CO', { hour: '2-digit', minute: '2-digit' })}
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </Card>

        {/* Mapa de la recogida */}
        <Card style={{ marginBottom: 14, padding: 14 }}>
          <div style={{ fontSize: 10, fontWeight: 700, color: TOKENS.textMuted, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 8 }}>
            Ubicación de la recogida
          </div>
          <MapView markers={[{
            lat: parada.lat, lng: parada.lng, label: '★',
            color: estadoColor(parada.estado), popup: `<b>${parada.taller}</b>`,
          }]} height={180} />
        </Card>

        {/* Detalles */}
        <Card style={{ marginBottom: 14, padding: '14px 16px' }}>
          <div style={{ fontSize: 10, fontWeight: 700, color: TOKENS.textMuted, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 8 }}>
            Detalle
          </div>
          <SuccessRow k="Producto" v={parada.referencia} />
          <Divider />
          <SuccessRow k="Solicitante" v={parada.solicitante.nombre} />
          <Divider />
          <SuccessRow k="Ventana" v={parada.ventanaTexto || 'Cualquier horario'} />
          <Divider />
          <SuccessRow k="Fecha" v={parada.fecha} />
        </Card>

        {/* Foto */}
        {parada.fotos && parada.fotos.length > 0 && (
          <Card style={{ marginBottom: 14, padding: 14 }}>
            <div style={{ fontSize: 10, fontWeight: 700, color: TOKENS.textMuted, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 8 }}>
              Foto adjunta
            </div>
            <img src={parada.fotos[0]} alt="Producto" style={{
              width: '100%', borderRadius: 10, border: `1px solid ${TOKENS.border}`,
              maxHeight: 280, objectFit: 'contain', background: '#000', display: 'block',
            }} />
          </Card>
        )}

        <div style={{ fontSize: 11, color: TOKENS.textSubtle, textAlign: 'center', padding: '8px 14px 16px' }}>
          Actualización automática cada 4 s
        </div>
      </div>
    </PublicShell>
  );
}

// ─── Router público: lee window.location.search ─────────────────────────
function getPublicRoute() {
  try {
    const params = new URLSearchParams(window.location.search);
    if (params.has('solicitud')) return { type: 'solicitud', tallerId: params.get('solicitud') };
    if (params.has('seguimiento')) return { type: 'seguimiento', solicitudId: params.get('seguimiento') };
  } catch {}
  return null;
}

function PublicRouterRoot() {
  const [route, setRoute] = React.useState(getPublicRoute());
  const [pendingSent, setPendingSent] = React.useState(null);

  // Permite redirigir entre vistas sin recargar
  const goSeguimiento = (id) => {
    const url = new URL(window.location);
    url.searchParams.delete('solicitud');
    url.searchParams.set('seguimiento', id);
    window.history.replaceState({}, '', url);
    setRoute({ type: 'seguimiento', solicitudId: id });
    setPendingSent(null);
  };
  const goNuevaSolicitud = (tallerId) => {
    const url = new URL(window.location);
    url.searchParams.delete('seguimiento');
    url.searchParams.set('solicitud', tallerId);
    window.history.replaceState({}, '', url);
    setRoute({ type: 'solicitud', tallerId });
    setPendingSent(null);
  };

  if (!route) return null;

  if (route.type === 'solicitud') {
    if (pendingSent) {
      return <SolicitudExitoScreen
        parada={pendingSent}
        onTrack={() => goSeguimiento(pendingSent.id)}
        onNew={() => goNuevaSolicitud(route.tallerId)}
      />;
    }
    return <PublicSolicitudScreen
      tallerId={route.tallerId}
      onSent={(p) => setPendingSent(p)}
    />;
  }

  if (route.type === 'seguimiento') {
    return <PublicSeguimientoScreen solicitudId={route.solicitudId} />;
  }

  return null;
}

Object.assign(window, {
  PublicRouterRoot, PublicSolicitudScreen, PublicSeguimientoScreen, SolicitudExitoScreen,
  getPublicRoute, getTallerById, pushMiSolicitud, getMisSolicitudes,
});
