// Lavadero Curupí — Booking flow (multi-step)

const { useState: useStateB, useMemo: useMemoB, useEffect: useEffectB } = React;

function Booking({ onBack, initial = {} }) {
  const [step, setStep] = useStateB(0);
  const [data, setData] = useStateB({
    brand: '',
    model: '',
    manualSize: '',
    plate: '',
    dirtLevel: '',
    serviceIds: initial.service ? [initial.service] : [],
    date: '',
    time: '',
    name: '',
    phone: '',
    email: '',
    payMethod: '',
    notes: '',
  });
  const [reservaId, setReservaId] = useStateB(null);
  const [submitting, setSubmitting] = useStateB(false);
  const [submitError, setSubmitError] = useStateB(null);
  const [apiServices, setApiServices] = useStateB(null);
  const [apiSizes, setApiSizes] = useStateB(null);
  const [loadError, setLoadError] = useStateB(false);

  const API_BASE = window.LC_API_BASE || 'https://curupi-api-production.up.railway.app';

  useEffectB(() => {
    Promise.all([
      fetch(API_BASE + '/servicios').then(r => { if (!r.ok) throw new Error('servicios'); return r.json(); }),
      fetch(API_BASE + '/tamanos').then(r => { if (!r.ok) throw new Error('tamanos'); return r.json(); }),
    ])
      .then(([servicios, tamanos]) => {
        setApiServices(servicios);
        setApiSizes(tamanos);
      })
      .catch(() => setLoadError(true));
  }, []);

  if (loadError) return (
    <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 16 }}>
      <p style={{ color: 'var(--text-muted)' }}>No se pudieron cargar los servicios.</p>
      <button className="btn btn-primary" onClick={() => window.location.reload()}>Reintentar</button>
    </div>
  );
  if (!apiServices || !apiSizes) return (
    <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <div style={{ color: 'var(--text-muted)' }}>Cargando…</div>
    </div>
  );

  const steps = ['Vehículo', 'Servicio', 'Fecha y hora', 'Tus datos', 'Pago', 'Confirmado'];

  const METODO_MAP = { mp: 'credito', transfer: 'transferencia', local: 'efectivo' };

  const sizeId = data.manualSize || 'chico';
  const size = apiSizes.find(s => s.id === sizeId);
  const isMoto = sizeId === 'moto';
  const selectedServices = apiServices.filter(s => data.serviceIds.includes(s.id));
  const service = selectedServices[0] || null;
  const getPrecio = (s) => (s.precios && sizeId && s.precios[sizeId]) ? s.precios[sizeId].precio : s.precio_base;
  const getDuracion = (s) => (s.precios && sizeId && s.precios[sizeId]) ? s.precios[sizeId].duracion_min : (s.duracion_min || 0);
  const finalPrice = selectedServices.reduce((acc, s) => acc + getPrecio(s), 0);
  const finalDuration = selectedServices.reduce((acc, s) => acc + getDuracion(s), 0);

  const update = (k, v) => setData(d => ({ ...d, [k]: v }));
  const prev = () => setStep(s => Math.max(s - 1, 0));

  const next = async () => {
    if (step === 4) {
      setSubmitting(true);
      setSubmitError(null);
      try {
        const base = {
          cliente_nombre:    data.name,
          cliente_telefono:  data.phone,
          cliente_email:     data.email || undefined,
          vehiculo_marca:    data.brand || undefined,
          vehiculo_modelo:   data.model || undefined,
          vehiculo_patente:  data.plate || undefined,
          tamanio:           sizeId,
          fecha:             data.date,
          hora_inicio:       data.time + ':00',
          notas:             data.notes || undefined,
          nivel_suciedad:    data.dirtLevel || undefined,
          origen:            'web',
          metodo_pago:       METODO_MAP[data.payMethod] || data.payMethod,
        };
        let lastId;
        for (const sid of data.serviceIds) {
          const res = await LC_API.crearReserva({ ...base, servicio_id: sid });
          lastId = res.id;
        }
        setReservaId(lastId);
        setStep(5);
      } catch (err) {
        setSubmitError(err.message || 'Error al confirmar la reserva. Intenta de nuevo.');
      } finally {
        setSubmitting(false);
      }
      return;
    }
    setStep(s => Math.min(s + 1, steps.length - 1));
  };

  const canNext = () => {
    if (step === 0) return data.manualSize && data.dirtLevel;
    if (step === 1) return data.serviceIds.length > 0 && !selectedServices.some(s => s.consultar);
    if (step === 2) return data.date && data.time;
    if (step === 3) return data.name && data.phone && /^[+\d\s-]{8,}$/.test(data.phone);
    if (step === 4) return data.payMethod;
    return true;
  };

  return (
    <div style={{ minHeight: '100vh', background: 'var(--bg)' }}>
      {/* Header */}
      <div style={{
        position: 'sticky', top: 0, zIndex: 10,
        background: 'color-mix(in oklab, var(--bg) 90%, transparent)', backdropFilter: 'blur(18px)',
        borderBottom: '1px solid var(--border)',
      }}>
        <div className="container" style={{ padding: '20px 28px', display: 'flex', alignItems: 'center', gap: 20 }}>
          <button onClick={onBack} className="btn btn-ghost btn-sm">
            <LCIcons.ArrowLeft size={14} /> Volver
          </button>
          <div className="row gap-2" style={{ alignItems: 'center', flex: 1 }}>
            <CurupiLogo />
            <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 17 }}>Reservar turno</span>
          </div>
          <div className="mono" style={{ fontSize: 11, color: 'var(--text-muted)' }}>
            PASO {step + 1} / {steps.length}
          </div>
        </div>
        {/* Progress */}
        <div style={{ display: 'flex', height: 3 }}>
          {steps.map((_, i) => (
            <div key={i} style={{
              flex: 1, background: i <= step ? 'var(--accent)' : 'var(--surface-2)',
              transition: 'background .3s ease',
            }} />
          ))}
        </div>
      </div>

      <div style={{ maxWidth: 920, margin: '0 auto', padding: '40px 28px 120px' }}>
        {/* Step labels */}
        <div style={{
          display: 'flex', gap: 8, marginBottom: 40,
          fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.1em',
          color: 'var(--text-faint)', textTransform: 'uppercase',
          overflowX: 'auto',
        }}>
          {steps.map((label, i) => (
            <div key={i} style={{
              padding: '6px 12px', borderRadius: 999, whiteSpace: 'nowrap',
              background: i === step ? 'var(--accent-soft)' : 'transparent',
              color: i === step ? 'var(--accent)' : i < step ? 'var(--text)' : 'var(--text-faint)',
              border: i === step ? '1px solid color-mix(in oklab, var(--accent) 30%, transparent)' : '1px solid transparent',
            }}>
              {i + 1}. {label}
            </div>
          ))}
        </div>

        <div key={step} className="reveal">
          {step === 0 && <StepVehicle data={data} update={update} sizes={apiSizes} />}
          {step === 1 && <StepService data={data} update={update} sizes={apiSizes} services={apiServices} sizeMult={size?.multiplicador || 1} isMoto={isMoto} sizeId={sizeId} />}
          {step === 2 && <StepDateTime data={data} update={update} />}
          {step === 3 && <StepContact data={data} update={update} />}
          {step === 4 && <StepPayment data={data} update={update} service={service} finalPrice={finalPrice} size={size} finalDuration={finalDuration} />}
          {step === 5 && <StepConfirm data={data} service={service} finalPrice={finalPrice} size={size} onBack={onBack} reservaId={reservaId} finalDuration={finalDuration} />}
        </div>
      </div>

      {/* Footer nav */}
      {step < 5 && (
        <div style={{
          position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: 10,
          background: 'color-mix(in oklab, var(--bg) 92%, transparent)', backdropFilter: 'blur(18px)',
          borderTop: '1px solid var(--border)',
          padding: '20px 28px',
        }}>
          <div style={{ maxWidth: 920, margin: '0 auto', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16 }}>
            <div>
              {selectedServices.length > 0 && (
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-muted)', letterSpacing: '0.08em' }}>
                  {selectedServices.map(s => s.nombre).join(' + ')} {data.brand && `· ${data.brand} ${data.model}`}
                </div>
              )}
              {finalPrice > 0 && (
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 22, marginTop: 2 }}>
                  ${finalPrice.toLocaleString('es-UY')} <span className="mono" style={{ fontSize: 11, color: 'var(--text-faint)', fontWeight: 400 }}>UYU</span>
                </div>
              )}
              {selectedServices.some(s => s.consultar) && (
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, marginTop: 2, color: 'var(--accent)' }}>
                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 400, color: 'var(--text-faint)', marginRight: 4 }}>desde</span>
                  ${selectedServices.reduce((a, s) => a + s.precio_base, 0).toLocaleString('es-UY')}
                </div>
              )}
            </div>
            <div className="col gap-2" style={{ alignItems: 'flex-end' }}>
              {submitError && (
                <div className="mono" style={{ fontSize: 11, color: '#e05252', textAlign: 'right' }}>
                  ⚠ {submitError}
                </div>
              )}
              <div className="row gap-2">
                {step > 0 && <button className="btn btn-ghost" onClick={prev} disabled={submitting}>Atrás</button>}
                {step === 1 && selectedServices.some(s => s.consultar) ? (
                  <a
                    href={`https://wa.me/${LC_DATA.brand.whatsapp.replace(/\D/g, '')}?text=${encodeURIComponent(`Hola! Quiero consultar sobre ${selectedServices.filter(s => s.consultar).map(s => s.nombre).join(' y ')} para mi ${data.brand || 'vehículo'} ${data.model || ''}.`.trim())}`}
                    target="_blank" rel="noopener noreferrer"
                    className="btn btn-wa btn-lg"
                    style={{ opacity: data.serviceIds.length > 0 ? 1 : 0.4, pointerEvents: data.serviceIds.length > 0 ? 'auto' : 'none' }}>
                    <LCIcons.WhatsApp size={16} /> Consultar por WhatsApp
                  </a>
                ) : (
                  <button className="btn btn-primary btn-lg" onClick={next} disabled={!canNext() || submitting}
                    style={{ opacity: canNext() && !submitting ? 1 : 0.4, pointerEvents: canNext() && !submitting ? 'auto' : 'none' }}>
                    {submitting ? 'Confirmando…' : step === 4 ? 'Confirmar reserva' : 'Continuar'} {!submitting && <LCIcons.ArrowRight size={14} />}
                  </button>
                )}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── Combobox helpers ──────────────────────────────────────────
function Dropdown({ children }) {
  return (
    <div style={{
      position: 'absolute', top: 'calc(100% + 6px)', left: 0, right: 0, zIndex: 30,
      background: 'var(--surface)', border: '1px solid var(--border)',
      borderRadius: 14, boxShadow: '0 8px 32px -8px rgba(0,0,0,.18)',
      maxHeight: 260, overflowY: 'auto',
    }}>
      {children}
    </div>
  );
}

function DropdownItem({ label, badge, onMouseDown }) {
  return (
    <button onMouseDown={onMouseDown} style={{
      width: '100%', textAlign: 'left', padding: '11px 16px',
      background: 'transparent', border: 'none', cursor: 'pointer',
      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      fontWeight: 600, fontSize: 14, color: 'var(--text)',
      borderBottom: '1px solid var(--border)',
    }}>
      <span>{label}</span>
      {badge && (
        <span className="mono" style={{ fontSize: 10, color: 'var(--text-faint)', fontWeight: 400 }}>{badge}</span>
      )}
    </button>
  );
}

// ─── STEP 0 ── Vehicle ──────────────────────────────────────────
function StepVehicle({ data, update, sizes }) {
  return (
    <div>
      <h2 style={{ fontSize: 'clamp(28px, 4vw, 44px)', marginBottom: 12 }}>Tu vehículo</h2>
      <p style={{ color: 'var(--text-muted)', marginBottom: 32, maxWidth: 540 }}>
        Selecciona el tipo de vehículo para calcular el precio y tiempo del servicio.
      </p>

      {/* Tipo de vehículo */}
      <div style={{ marginBottom: 28 }}>
        <label>¿Qué tipo de vehículo es?</label>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: 10 }}>
          {sizes.map(s => (
            <button key={s.id} onClick={() => update('manualSize', s.id)} style={{
              padding: '14px 16px', borderRadius: 12, textAlign: 'left',
              background: data.manualSize === s.id ? 'var(--accent-soft)' : 'var(--surface)',
              border: '1px solid', borderColor: data.manualSize === s.id ? 'var(--accent)' : 'var(--border)',
              color: data.manualSize === s.id ? 'var(--accent)' : 'var(--text)',
              fontWeight: 600, fontSize: 14, transition: 'all .2s',
            }}>
              <div>{s.nombre}</div>
            </button>
          ))}
        </div>
      </div>

      {/* Nivel de suciedad */}
      {data.manualSize && (
        <div className="reveal" style={{ marginBottom: 8 }}>
          <label>¿Cuál es el nivel de suciedad?</label>
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginBottom: 12 }}>
            {[{ id: 'bajo', label: 'Bajo' }, { id: 'medio', label: 'Medio' }, { id: 'alto', label: 'Alto' }].map(opt => (
              <button key={opt.id} onClick={() => update('dirtLevel', opt.id)} style={{
                padding: '14px 28px', borderRadius: 12, fontWeight: 600, fontSize: 14, transition: 'all .2s',
                background: data.dirtLevel === opt.id ? 'var(--accent-soft)' : 'var(--surface)',
                border: '1px solid', borderColor: data.dirtLevel === opt.id ? 'var(--accent)' : 'var(--border)',
                color: data.dirtLevel === opt.id ? 'var(--accent)' : 'var(--text)',
              }}>
                {opt.label}
              </button>
            ))}
          </div>
          {(data.dirtLevel === 'medio' || data.dirtLevel === 'alto') && (
            <div className="reveal" style={{
              padding: '12px 16px', borderRadius: 10, fontSize: 13,
              background: 'color-mix(in oklab, #f59e0b 12%, transparent)',
              border: '1px solid color-mix(in oklab, #f59e0b 35%, transparent)',
              color: 'var(--text)',
            }}>
              ⚠️ Con suciedad {data.dirtLevel === 'alto' ? 'alta' : 'media'} el servicio puede llevar más tiempo y aplicar un pequeño recargo. Te avisamos el monto exacto al momento de la entrega.
            </div>
          )}
        </div>
      )}
    </div>
  );
}

// ─── STEP 1 ── Service ─────────────────────────────────────────
function StepService({ data, update, sizes, services, sizeMult, isMoto, sizeId }) {
  const filteredServices = isMoto
    ? services.filter(s => s.id === 'carroceria')
    : services;

  const toggleService = (id, consultar) => {
    if (consultar) { window.open('https://wa.me/' + LC_DATA.brand.whatsapp.replace(/\D/g, ''), '_blank'); return; }
    const ids = data.serviceIds.includes(id)
      ? data.serviceIds.filter(x => x !== id)
      : [...data.serviceIds, id];
    update('serviceIds', ids);
  };

  return (
    <div>
      <h2 style={{ fontSize: 'clamp(28px, 4vw, 44px)', marginBottom: 12 }}>¿Qué servicios necesitás?</h2>
      <p style={{ color: 'var(--text-muted)', marginBottom: 32, maxWidth: 540 }}>
        {isMoto
          ? 'Servicio disponible para tu moto.'
          : `Puedes elegir más de uno. El precio se ajusta al tamaño de tu vehículo.`}
      </p>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 16 }}>
        {filteredServices.map(s => {
          const precioEntry = s.precios && sizeId && s.precios[sizeId];
          const finalP = precioEntry ? precioEntry.precio : s.precio_base;
          const duracion = precioEntry ? precioEntry.duracion_min : s.duracion_min;
          const selected = data.serviceIds.includes(s.id);
          const iconMap = {
            carroceria: 'Droplet', interior: 'Sparkles', tapizados: 'Shine',
            pulido: 'Crown', opticas: 'Eye', motor: 'Engine', chasis: 'Car',
          };
          const Icon = LCIcons[iconMap[s.slug || s.id]] || LCIcons.Sparkles;
          const handleClick = () => toggleService(s.id, s.consultar);
          return (
            <button key={s.id} onClick={handleClick}
              style={{
                textAlign: 'left', padding: 24, borderRadius: 18,
                background: selected ? 'var(--accent-soft)' : 'var(--surface)',
                border: '1px solid', borderColor: selected ? 'var(--accent)' : 'var(--border)',
                transition: 'all .2s', cursor: 'pointer',
                position: 'relative',
              }}>
              {s.consultar && (
                <div className="chip" style={{ position: 'absolute', top: 16, right: 16, background: 'var(--surface-2)', color: 'var(--text-muted)' }}>
                  📞 Consultar
                </div>
              )}
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
                <div style={{
                  width: 40, height: 40, borderRadius: 10,
                  background: selected ? 'var(--accent)' : 'var(--accent-soft)',
                  color: selected ? 'var(--accent-ink)' : 'var(--accent)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <Icon size={18} />
                </div>
                <div>
                  <div style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 700, color: selected ? 'var(--accent)' : 'var(--text)' }}>{s.nombre}</div>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--text-muted)' }}>
                    {s.consultar ? 'Desde 60 min' : `~${duracion} min`}
                  </div>
                </div>
              </div>
              {s.desc && <p style={{ fontSize: 13, color: 'var(--text-muted)', marginBottom: 16 }}>{s.desc}</p>}
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', paddingTop: 16, borderTop: '1px dashed var(--border)' }}>
                <span className="mono" style={{ fontSize: 11, color: 'var(--text-faint)' }}>TOTAL</span>
                {s.consultar ? (
                  <span style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 700, color: selected ? 'var(--accent)' : 'var(--text)' }}>
                    <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 400, color: 'var(--text-faint)', marginRight: 4 }}>desde</span>
                    ${s.precio_base.toLocaleString('es-UY')}
                  </span>
                ) : (
                  <span style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 700, color: selected ? 'var(--accent)' : 'var(--text)' }}>
                    ${finalP.toLocaleString('es-UY')}
                  </span>
                )}
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ─── STEP 2 ── Date & Time ─────────────────────────────────────
function StepDateTime({ data, update }) {
  const [slotsData, setSlotsData] = useStateB([]);
  const [loadingSlots, setLoadingSlots] = useStateB(false);

  const today = new Date();
  const days = [];
  for (let i = 0; i < 10; i++) {
    const d = new Date(today);
    d.setDate(today.getDate() + i);
    if (d.getDay() === 0) continue; // domingo cerrado
    days.push(d);
  }

  useEffectB(() => {
    if (!data.date || !data.serviceIds?.[0]) return;
    setLoadingSlots(true);
    LC_API.getSlots(data.date, data.serviceIds[0])
      .then(res => setSlotsData(Array.isArray(res) ? res : (res.slots || [])))
      .catch(() => setSlotsData([]))
      .finally(() => setLoadingSlots(false));
  }, [data.date, data.serviceIds?.[0]]);

  const slots = slotsData.map(s => ({
    t: s.hora,
    period: parseInt(s.hora) < 13 ? 'AM' : 'PM',
    disponible: s.disponible,
  }));

  const occupied = (_, time) => {
    const slot = slots.find(s => s.t === time);
    return slot ? !slot.disponible : false;
  };

  const dayNames = ['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb'];
  const monthNames = ['ENE', 'FEB', 'MAR', 'ABR', 'MAY', 'JUN', 'JUL', 'AGO', 'SEP', 'OCT', 'NOV', 'DIC'];

  return (
    <div>
      <h2 style={{ fontSize: 'clamp(28px, 4vw, 44px)', marginBottom: 12 }}>¿Cuándo te queda cómodo?</h2>
      <p style={{ color: 'var(--text-muted)', marginBottom: 32, maxWidth: 540 }}>
        Horarios disponibles en tiempo real. Cupos cada 45 minutos.
      </p>

      <label>Día</label>
      <div style={{ display: 'flex', gap: 10, overflowX: 'auto', paddingBottom: 12, marginBottom: 32 }}>
        {days.map((d, i) => {
          const iso = d.toISOString().slice(0, 10);
          const selected = data.date === iso;
          return (
            <button key={i} onClick={() => update('date', iso)} style={{
              flexShrink: 0, padding: '14px 18px', borderRadius: 14, minWidth: 84,
              background: selected ? 'var(--accent)' : 'var(--surface)',
              border: '1px solid', borderColor: selected ? 'var(--accent)' : 'var(--border)',
              color: selected ? 'var(--accent-ink)' : 'var(--text)',
              textAlign: 'center', transition: 'all .2s',
            }}>
              <div className="mono" style={{ fontSize: 10, opacity: 0.7, letterSpacing: '0.1em' }}>
                {dayNames[d.getDay()].toUpperCase()}
              </div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 700, lineHeight: 1, margin: '6px 0' }}>
                {d.getDate()}
              </div>
              <div className="mono" style={{ fontSize: 10, opacity: 0.7 }}>{monthNames[d.getMonth()]}</div>
            </button>
          );
        })}
      </div>

      {data.date && (
        <div className="reveal">
          {['AM', 'PM'].map(period => (
            <div key={period} style={{ marginBottom: 24 }}>
              <label>
                {period === 'AM' ? '🌅 Mañana · 9:00 a 13:00' : '🌇 Tarde · 14:00 a 18:00'}
              </label>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(90px, 1fr))', gap: 8 }}>
                {slots.filter(s => s.period === period).map(s => {
                  const taken = occupied(data.date, s.t);
                  const selected = data.time === s.t;
                  return (
                    <button key={s.t} disabled={taken} onClick={() => update('time', s.t)}
                      style={{
                        padding: '12px 8px', borderRadius: 10,
                        background: selected ? 'var(--accent)' : taken ? 'transparent' : 'var(--surface)',
                        border: '1px solid', borderColor: selected ? 'var(--accent)' : 'var(--border)',
                        color: selected ? 'var(--accent-ink)' : taken ? 'var(--text-faint)' : 'var(--text)',
                        fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 600,
                        textDecoration: taken ? 'line-through' : 'none',
                        cursor: taken ? 'not-allowed' : 'pointer',
                        opacity: taken ? 0.4 : 1,
                        transition: 'all .15s',
                      }}>
                      {s.t}
                    </button>
                  );
                })}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ─── STEP 3 ── Contact ─────────────────────────────────────────
function StepContact({ data, update }) {
  const [clienteEncontrado, setClienteEncontrado] = useStateB(null);
  const [lookupDone, setLookupDone] = useStateB(false);

  useEffectB(() => {
    if (!data.phone || data.phone.replace(/\D/g, '').length < 8) return;
    const t = setTimeout(() => {
      LC_API.buscarCliente(data.phone)
        .then(res => {
          setLookupDone(true);
          if (res.encontrado) {
            setClienteEncontrado(res);
            if (!data.name && res.cliente.nombre) update('name', res.cliente.nombre);
            if (!data.email && res.cliente.email) update('email', res.cliente.email);
          }
        })
        .catch(() => setLookupDone(true));
    }, 600);
    return () => clearTimeout(t);
  }, [data.phone]);

  return (
    <div>
      <h2 style={{ fontSize: 'clamp(28px, 4vw, 44px)', marginBottom: 12 }}>¿Cómo te contactamos?</h2>
      <p style={{ color: 'var(--text-muted)', marginBottom: 32, maxWidth: 540 }}>
        Te enviamos la confirmación y el recordatorio por WhatsApp.
      </p>

      {clienteEncontrado && (
        <div className="reveal" style={{
          padding: '14px 18px', borderRadius: 12, marginBottom: 24,
          background: 'var(--accent-soft)', border: '1px solid color-mix(in oklab, var(--accent) 30%, transparent)',
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <LCIcons.Check size={16} style={{ color: 'var(--accent)', flexShrink: 0 }} />
          <div>
            <div style={{ fontWeight: 600, fontSize: 14, color: 'var(--accent)' }}>
              ¡Hola de nuevo, {clienteEncontrado.cliente.nombre.split(' ')[0]}!
            </div>
            <div className="mono" style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>
              {clienteEncontrado.cliente.visitas_total} visita{clienteEncontrado.cliente.visitas_total !== 1 ? 's' : ''} anteriores
              {clienteEncontrado.premios?.length > 0 && ` · ${clienteEncontrado.premios.length} premio${clienteEncontrado.premios.length !== 1 ? 's' : ''} disponible${clienteEncontrado.premios.length !== 1 ? 's' : ''}`}
            </div>
          </div>
        </div>
      )}

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, maxWidth: 640 }} className="contact-form">
        <div>
          <label>Nombre y apellido</label>
          <input value={data.name} onChange={e => update('name', e.target.value)} placeholder="Andrés Pereyra" />
        </div>
        <div>
          <label>WhatsApp</label>
          <input value={data.phone} onChange={e => { update('phone', e.target.value); setClienteEncontrado(null); setLookupDone(false); }} placeholder="092 211 407" type="tel" />
        </div>
        <div style={{ gridColumn: '1 / -1' }}>
          <label>Email <span style={{ color: 'var(--text-faint)' }}>(opcional, para factura)</span></label>
          <input value={data.email} onChange={e => update('email', e.target.value)} placeholder="andres@email.com" type="email" />
        </div>
        <div style={{ gridColumn: '1 / -1' }}>
          <label>Notas para el equipo <span style={{ color: 'var(--text-faint)' }}>(opcional)</span></label>
          <textarea value={data.notes} onChange={e => update('notes', e.target.value)}
            placeholder="Ej: traigo cucha de perro en el baúl, cuidado con la antena, etc."
            rows={3} style={{ resize: 'vertical', fontFamily: 'inherit' }} />
        </div>
      </div>

      <style>{`
        @media (max-width: 600px) { .contact-form { grid-template-columns: 1fr !important; } }
      `}</style>
    </div>
  );
}

// ─── STEP 4 ── Payment ─────────────────────────────────────────
function StepPayment({ data, update, service, finalPrice, size, finalDuration }) {
  const methods = [
    { id: 'mp', name: 'Mercado Pago', desc: 'Tarjeta, dinero en cuenta, o link de pago', icon: 'CreditCard', popular: true },
    { id: 'transfer', name: 'Transferencia BROU / Itaú', desc: 'Te enviamos los datos al confirmar', icon: 'Dollar' },
    { id: 'local', name: 'Efectivo o POS en el local', desc: 'Pagás cuando retirás el auto', icon: 'Car' },
  ];

  return (
    <div>
      <h2 style={{ fontSize: 'clamp(28px, 4vw, 44px)', marginBottom: 12 }}>¿Cómo quieres pagar?</h2>
      <p style={{ color: 'var(--text-muted)', marginBottom: 32, maxWidth: 540 }}>
        Reservas sin tarjeta. Puedes pagar después.
      </p>

      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 32 }} className="pay-grid">
        <div className="col gap-2">
          {methods.map(m => {
            const Icon = LCIcons[m.icon];
            const selected = data.payMethod === m.id;
            return (
              <button key={m.id} onClick={() => update('payMethod', m.id)}
                style={{
                  display: 'flex', alignItems: 'center', gap: 16, padding: 20,
                  borderRadius: 16, textAlign: 'left',
                  background: selected ? 'var(--accent-soft)' : 'var(--surface)',
                  border: '1px solid', borderColor: selected ? 'var(--accent)' : 'var(--border)',
                  color: 'var(--text)', transition: 'all .2s', position: 'relative',
                }}>
                <div style={{
                  width: 44, height: 44, borderRadius: 12,
                  background: selected ? 'var(--accent)' : 'var(--surface-2)',
                  color: selected ? 'var(--accent-ink)' : 'var(--text)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                }}>
                  <Icon size={20} />
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <span style={{ fontWeight: 600, fontSize: 16 }}>{m.name}</span>
                    {m.popular && <span className="chip accent">recomendado</span>}
                  </div>
                  <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 2 }}>{m.desc}</div>
                </div>
                <div style={{
                  width: 22, height: 22, borderRadius: 999,
                  border: '2px solid', borderColor: selected ? 'var(--accent)' : 'var(--border-strong)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  background: selected ? 'var(--accent)' : 'transparent',
                }}>
                  {selected && <LCIcons.Check size={12} style={{ color: 'var(--accent-ink)' }} />}
                </div>
              </button>
            );
          })}
        </div>

        <Summary data={data} selectedServices={selectedServices} finalPrice={finalPrice} size={size} finalDuration={finalDuration} />
      </div>

      <style>{`
        @media (max-width: 800px) { .pay-grid { grid-template-columns: 1fr !important; } }
      `}</style>
    </div>
  );
}

function Summary({ data, selectedServices = [], finalPrice, size, finalDuration }) {
  const service = selectedServices[0] || null;
  const formatDate = (iso) => {
    if (!iso) return '';
    const d = new Date(iso);
    const days = ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'];
    const months = ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'setiembre', 'octubre', 'noviembre', 'diciembre'];
    return `${days[d.getDay()]} ${d.getDate()} de ${months[d.getMonth()]}`;
  };

  return (
    <aside className="card" style={{ padding: 24, height: 'fit-content', position: 'sticky', top: 100 }}>
      <div className="mono" style={{ fontSize: 11, color: 'var(--text-faint)', letterSpacing: '0.15em', marginBottom: 20 }}>
        RESUMEN DE TU RESERVA
      </div>

      <SummaryRow icon="Car" label="Vehículo" value={[data.brand, data.model].filter(Boolean).join(' ') || size?.nombre} sub={data.brand ? size?.nombre : undefined} />
      <SummaryRow icon="Sparkles" label={selectedServices.length > 1 ? 'Servicios' : 'Servicio'} value={selectedServices.map(s => s.nombre).join(' + ') || '—'} sub={finalDuration > 0 ? `~${finalDuration} min` : undefined} />
      {data.dirtLevel && <SummaryRow icon="Sparkles" label="Nivel de suciedad" value={{ bajo: 'Bajo', medio: 'Medio', alto: 'Alto' }[data.dirtLevel]} />}
      <SummaryRow icon="Calendar" label="Día" value={formatDate(data.date)} sub={data.time && `${data.time} hs`} />
      <SummaryRow icon="User" label="A nombre de" value={data.name || '—'} sub={data.phone} />

      <div style={{ paddingTop: 20, marginTop: 16, borderTop: '1px dashed var(--border)' }}>
        {selectedServices.map(s => {
          const p = (s.precios && size && s.precios[size.id]) ? s.precios[size.id].precio : s.precio_base;
          return (
            <div key={s.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 4 }}>
              <span style={{ color: 'var(--text-muted)' }}>{s.nombre}{s.consultar ? ' (desde)' : ''}</span>
              <span className="mono">${p.toLocaleString('es-UY')}</span>
            </div>
          );
        })}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 20, paddingTop: 16, borderTop: '1px solid var(--border)' }}>
          <span style={{ fontWeight: 600, fontSize: 16 }}>Total</span>
          <span style={{ fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 700, color: 'var(--accent)' }}>
            ${finalPrice.toLocaleString('es-UY')}
          </span>
        </div>
      </div>
    </aside>
  );
}

function SummaryRow({ icon, label, value, sub }) {
  const Icon = LCIcons[icon];
  return (
    <div style={{ display: 'flex', gap: 12, padding: '12px 0', borderBottom: '1px solid var(--border)' }}>
      <div style={{ color: 'var(--accent)', flexShrink: 0, marginTop: 2 }}>
        <Icon size={16} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="mono" style={{ fontSize: 10, color: 'var(--text-faint)', letterSpacing: '0.1em', marginBottom: 2 }}>
          {label.toUpperCase()}
        </div>
        <div style={{ fontSize: 14, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis' }}>{value}</div>
        {sub && <div className="mono" style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>{sub}</div>}
      </div>
    </div>
  );
}

// ─── STEP 5 ── Confirmation ────────────────────────────────────
function StepConfirm({ data, service, finalPrice, size, onBack, reservaId, finalDuration }) {
  const ref = reservaId ? `CRP-${reservaId}` : `CRP-${Math.floor(Math.random() * 9000 + 1000)}`;

  const formatDate = (iso) => {
    const d = new Date(iso);
    const days = ['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb'];
    const months = ['ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'set', 'oct', 'nov', 'dic'];
    return `${days[d.getDay()]} ${d.getDate()} ${months[d.getMonth()]}`;
  };

  return (
    <div style={{ textAlign: 'center', maxWidth: 580, margin: '0 auto', padding: '20px 0' }}>
      <div style={{
        width: 88, height: 88, borderRadius: 999, margin: '0 auto 28px',
        background: 'var(--accent)', color: 'var(--accent-ink)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: '0 20px 60px -20px color-mix(in oklab, var(--accent) 80%, transparent)',
      }}>
        <LCIcons.Check size={40} style={{ strokeWidth: 3 }} />
      </div>

      <span className="eyebrow">RESERVA CONFIRMADA · {ref}</span>
      <h2 style={{ fontSize: 'clamp(32px, 5vw, 52px)', margin: '16px 0' }}>
        ¡Listo, {data.name.split(' ')[0]}!
      </h2>
      <p style={{ color: 'var(--text-muted)', fontSize: 17, marginBottom: 36 }}>
        Te enviamos la confirmación por WhatsApp al {data.phone}. <br />
        Te esperamos el <strong style={{ color: 'var(--text)' }}>{formatDate(data.date)} a las {data.time}</strong>.
      </p>

      <div className="card" style={{ padding: 24, textAlign: 'left', marginBottom: 24 }}>
        <SummaryRow icon="Car" label="Vehículo" value={`${data.brand} ${data.model}`} sub={data.plate} />
        <SummaryRow icon="Sparkles" label="Servicio" value={service?.nombre} sub={`~${finalDuration} min`} />
        <SummaryRow icon="Calendar" label="Día y hora" value={formatDate(data.date)} sub={`${data.time} hs`} />
        <SummaryRow icon="Pin" label="Dónde" value={LC_DATA.brand.address} sub="Lascano, Rocha" />
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', paddingTop: 20, marginTop: 16, borderTop: '1px dashed var(--border)' }}>
          <span style={{ fontWeight: 600, fontSize: 16 }}>Total a pagar</span>
          <span style={{ fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 700, color: 'var(--accent)' }}>
            ${finalPrice.toLocaleString('es-UY')}
          </span>
        </div>
      </div>

      <div className="row gap-2 center" style={{ flexWrap: 'wrap' }}>
        <button className="btn btn-wa">
          <LCIcons.WhatsApp size={16} /> Ver chat en WhatsApp
        </button>
        <button className="btn btn-ghost" onClick={onBack}>Volver al inicio</button>
      </div>

      <p className="mono" style={{ fontSize: 11, color: 'var(--text-faint)', marginTop: 32 }}>
        {'>'} puedes cancelar o reagendar respondiendo en el chat hasta 2h antes.
      </p>
    </div>
  );
}

window.LCBooking = Booking;
