// storefront-checkout.jsx — /bolsa · /checkout · /confirmacion

// ════════════════════════════════════════════════════════════════════
// BOLSA
// ════════════════════════════════════════════════════════════════════
function Bolsa({ mobile }) {
  const s = useStore();
  const cart = s.cart;
  const subtotal = cart.reduce((sum, it) => sum + it.price * it.qty, 0);
  const SHIPPING_THRESHOLD = 1499;
  const envio = subtotal >= SHIPPING_THRESHOLD ? 0 : 99;
  const [coupon, setCoupon] = useState('');
  const [couponApplied, setCouponApplied] = useState(false);
  const discount = couponApplied ? Math.round(subtotal * 0.10) : 0;
  const total = subtotal + envio - discount;
  const cartCount = cart.reduce((n, it) => n + it.qty, 0);

  const crossSellIds = ['p03','p06','p09','p11'];
  const crossSell = crossSellIds.map(id => PRODUCTS.find(p => p.id === id)).filter(Boolean);

  return (
    <main data-screen-label="Bolsa" style={{ background: '#fff' }}>
      {/* Page header */}
      <div style={{
        padding: mobile ? '22px 16px 18px' : '40px 32px 28px',
        borderBottom: `1px solid ${C.border}`,
      }}>
        <button onClick={() => s.go('home')} style={{
          background:'transparent', border:0, padding:'4px 0', cursor:'pointer',
          fontFamily:'JetBrains Mono, monospace', fontSize: 11,
          letterSpacing:'0.22em', textTransform:'uppercase', color: C.fgMuted,
          transition:'color .15s',
        }} onMouseEnter={e => e.currentTarget.style.color = C.fg}
          onMouseLeave={e => e.currentTarget.style.color = C.fgMuted}>
          ← Seguir comprando
        </button>
        <div style={{
          marginTop: 10,
          fontFamily:'Anton, sans-serif', fontSize: mobile ? 44 : 72,
          textTransform:'uppercase', letterSpacing:'-0.015em', lineHeight: 1, paddingTop: 4,
        }}>
          Tu bolsa{cartCount > 0 && (
            <>{' '}<span style={{ color: C.accent }}>·</span>{' '}
              <span style={{ color: C.fgMuted, fontSize: mobile ? 22 : 36 }}>{cartCount} {cartCount === 1 ? 'pieza' : 'piezas'}</span>
            </>
          )}
        </div>
      </div>

      {cart.length === 0 ? (
        <BolsaEmpty mobile={mobile}/>
      ) : (
        <div style={{
          display:'grid',
          gridTemplateColumns: mobile ? '1fr' : '1.5fr 1fr',
          gap: mobile ? 32 : 48,
          padding: mobile ? '24px 16px 56px' : '48px 32px 80px',
          alignItems:'start',
        }}>
          <div>
            {cart.map((it, i) => <BolsaLine key={i} item={it} idx={i} mobile={mobile}/>)}
          </div>
          <BolsaSummary
            mobile={mobile}
            subtotal={subtotal} envio={envio} discount={discount} total={total}
            coupon={coupon} setCoupon={setCoupon}
            applyCoupon={() => setCouponApplied(true)} couponApplied={couponApplied}
          />
        </div>
      )}

      {/* Cross-sell */}
      {cart.length > 0 && (
        <section style={{
          borderTop:`1px solid ${C.fg}`,
          padding: mobile ? '24px 16px 56px' : '48px 32px 96px',
        }}>
          <div style={{
            display:'flex', alignItems:'baseline', justifyContent:'space-between',
            marginBottom: mobile ? 18 : 28, gap: 12,
          }}>
            <div style={{
              fontFamily:'Anton, sans-serif', fontSize: mobile ? 32 : 56,
              textTransform:'uppercase', letterSpacing:'-0.01em', lineHeight: 0.95,
            }}>Para completar tu look.</div>
            <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 11, letterSpacing:'0.22em', textTransform:'uppercase', color: C.fgMuted }}>
              4 sugerencias
            </div>
          </div>
          <div style={{
            display:'grid',
            gridTemplateColumns: mobile ? 'repeat(2, 1fr)' : 'repeat(4, 1fr)',
            gap: mobile ? 12 : 24,
          }}>
            {crossSell.map(p => (
              <ProductCard key={p.id} product={p} mobile={mobile} onClick={() => s.go('pdp', { slug: p.slug })} />
            ))}
          </div>
        </section>
      )}
    </main>
  );
}

function BolsaEmpty({ mobile }) {
  const s = useStore();
  return (
    <div style={{ padding: mobile ? '88px 16px 96px' : '128px 32px 144px', textAlign:'center' }}>
      <div style={{
        fontFamily:'Anton, sans-serif', fontSize: mobile ? 56 : 104,
        lineHeight: 0.95, textTransform:'uppercase', letterSpacing:'-0.015em',
        marginBottom: 12, paddingTop: 4,
      }}>
        Tu bolsa<br/>está vacía.
      </div>
      <div style={{
        fontFamily:'JetBrains Mono, monospace', fontSize: 12,
        letterSpacing:'0.22em', textTransform:'uppercase', color: C.fgMuted,
        marginBottom: 36,
      }}>
        Empieza por aquí.
      </div>
      <button className="cmd-btn-primary cmd-btn-inline" onClick={() => s.go('home')}>
        Explorar el drop {Icon.arrowR(16)}
      </button>
    </div>
  );
}

function BolsaLine({ item, idx, mobile }) {
  const s = useStore();
  const product = PRODUCTS.find(p => p.id === item.id) || {
    sizes: ['XS','S','M','L','XL'],
    colors: [{ name: item.color, hex: item.colorHex }],
  };
  return (
    <div style={{
      display:'grid',
      gridTemplateColumns: mobile ? '92px 1fr' : '120px 1fr auto',
      gap: mobile ? 14 : 24,
      padding: mobile ? '18px 0' : '28px 0',
      borderTop: idx === 0 ? `1px solid ${C.fg}` : `1px solid ${C.borderSoft}`,
    }}>
      {/* thumb — real image if available, else colored placeholder */}
      {(() => {
        const colorObj = product.colors.find(c => c.name === item.color) || product.colors[0];
        const img = resolveProductImage(product, colorObj, 'front');
        return (
          <div style={{
            aspectRatio:'4/5', background: img ? '#F4F2EC' : item.colorHex,
            position:'relative', overflow:'hidden',
          }}>
            {img ? (
              <img src={img} alt={item.name} loading="lazy" style={{
                position:'absolute', inset:0, width:'100%', height:'100%', objectFit:'cover', display:'block',
              }}/>
            ) : (
              <div style={{ position:'absolute', inset:0, background:`repeating-linear-gradient(45deg, transparent 0 10px, rgba(255,255,255,0.06) 10px 11px)` }}/>
            )}
            <div style={{
              position:'absolute', top: 7, left: 7,
              fontFamily:'JetBrains Mono, monospace', fontSize: 8,
              letterSpacing:'0.2em', textTransform:'uppercase',
              color: img ? '#0A0A0A' : contrast(item.colorHex), opacity: img ? 0.5 : 0.7,
              mixBlendMode: img ? 'multiply' : 'normal',
            }}>{item.id}</div>
          </div>
        );
      })()}

      <div>
        <div style={{
          fontFamily:'Anton, sans-serif', fontSize: mobile ? 22 : 28,
          textTransform:'uppercase', letterSpacing:'-0.005em', lineHeight: 1,
          marginBottom: mobile ? 12 : 16,
        }}>{item.name}</div>

        <div style={{ display:'flex', flexWrap:'wrap', gap: mobile ? 8 : 14, alignItems:'center', marginBottom: 14 }}>
          <BolsaSelect label="Color" value={item.color} options={product.colors.map(c => c.name)}
            onChange={(v) => {
              const next = product.colors.find(c => c.name === v);
              if (next) s.updateItem(idx, { color: next.name, colorHex: next.hex });
            }}/>
          <BolsaSelect label="Talla" value={item.size} options={product.sizes}
            onChange={(v) => s.updateItem(idx, { size: v })}/>
          <div style={{ display:'flex', alignItems:'center', border:`1px solid ${C.border}` }}>
            <button onClick={() => s.qty(idx, -1)} style={qtyStepBtn}>−</button>
            <span style={{
              minWidth: 28, fontFamily:'JetBrains Mono, monospace', fontSize: 13,
              textAlign:'center', lineHeight: '32px',
            }}>{item.qty}</span>
            <button onClick={() => s.qty(idx, 1)} style={qtyStepBtn}>+</button>
          </div>
        </div>

        {mobile && (
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline' }}>
            <button onClick={() => s.removeItem(idx)} style={lineRemoveBtn}>Eliminar</button>
            <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 14, fontWeight: 700 }}>
              ${(item.price * item.qty).toLocaleString('es-MX')}{' '}
              <span style={{ fontSize: 9, color: C.fgMuted, fontWeight: 400 }}>MXN</span>
            </div>
          </div>
        )}
      </div>

      {!mobile && (
        <div style={{ textAlign:'right' }}>
          <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 16, fontWeight: 700, lineHeight: 1.1 }}>
            ${(item.price * item.qty).toLocaleString('es-MX')}
          </div>
          <div style={{
            fontFamily:'JetBrains Mono, monospace', fontSize: 10, color: C.fgMuted,
            letterSpacing:'0.18em', textTransform:'uppercase', marginTop: 4,
          }}>MXN</div>
          <button onClick={() => s.removeItem(idx)} style={{ ...lineRemoveBtn, marginTop: 18 }}
            onMouseEnter={e => e.currentTarget.style.color = C.accent}
            onMouseLeave={e => e.currentTarget.style.color = C.fgMuted}>
            Eliminar
          </button>
        </div>
      )}
    </div>
  );
}

const qtyStepBtn = {
  width: 32, height: 32, background:'#fff', border: 0, cursor:'pointer',
  fontFamily:'JetBrains Mono, monospace', fontSize: 14, lineHeight: 1,
};

const lineRemoveBtn = {
  background:'transparent', border: 0, padding: 0, cursor:'pointer',
  fontFamily:'JetBrains Mono, monospace', fontSize: 10,
  letterSpacing:'0.22em', textTransform:'uppercase', color: C.fgMuted,
  textDecoration:'underline', transition:'color .15s',
};

function BolsaSelect({ label, value, options, onChange }) {
  return (
    <label style={{ display:'inline-flex', alignItems:'center', gap: 8 }}>
      <span style={{
        fontFamily:'JetBrains Mono, monospace', fontSize: 10,
        letterSpacing:'0.22em', textTransform:'uppercase', color: C.fgMuted,
      }}>{label}</span>
      <select value={value} onChange={e => onChange(e.target.value)} style={{
        appearance:'none', WebkitAppearance:'none', MozAppearance:'none',
        background:'#fff', color: C.fg, border:`1px solid ${C.border}`,
        padding:'7px 26px 7px 10px', cursor:'pointer',
        fontFamily:'JetBrains Mono, monospace', fontSize: 11,
        letterSpacing:'0.14em', textTransform:'uppercase', fontWeight: 700,
        backgroundImage:"url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6' fill='%230A0A0A'><path d='M0 0l5 6 5-6z'/></svg>\")",
        backgroundRepeat:'no-repeat', backgroundPosition:'right 8px center', backgroundSize:'8px',
      }}>
        {options.map(o => <option key={o} value={o}>{o}</option>)}
      </select>
    </label>
  );
}

function BolsaSummary({ mobile, subtotal, envio, discount, total, coupon, setCoupon, applyCoupon, couponApplied }) {
  const s = useStore();
  return (
    <aside style={{
      position: mobile ? 'static' : 'sticky', top: mobile ? 'auto' : 24,
      background: C.bgWarm, padding: mobile ? '24px 20px' : '32px 28px',
    }}>
      <div style={{
        fontFamily:'JetBrains Mono, monospace', fontSize: 11,
        letterSpacing:'0.22em', textTransform:'uppercase', color: C.fgMuted, marginBottom: 18,
      }}>Resumen del pedido</div>

      <SummaryRow label="Subtotal" value={`$${subtotal.toLocaleString('es-MX')} MXN`}/>
      <SummaryRow label="Envío estimado" value={envio === 0 ? 'Gratis' : `$${envio} MXN`} valueColor={envio === 0 ? C.accent : C.fg}/>
      {discount > 0 && <SummaryRow label="Descuento" value={`−$${discount.toLocaleString('es-MX')} MXN`} valueColor={C.accent}/>}

      {envio > 0 && (
        <div style={{
          marginTop: 12, padding:'10px 12px', background:'#fff', border:`1px solid ${C.border}`,
          fontFamily:'JetBrains Mono, monospace', fontSize: 10,
          letterSpacing:'0.14em', textTransform:'uppercase', color: C.fgMuted, lineHeight: 1.45,
        }}>
          Agrega ${(1499 - subtotal).toLocaleString('es-MX')} MXN más para envío gratis.
        </div>
      )}

      {/* Coupon */}
      <div style={{ marginTop: 20 }}>
        <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 10, letterSpacing:'0.22em', textTransform:'uppercase', color: C.fgMuted, marginBottom: 8 }}>Código de descuento</div>
        <div style={{ display:'flex' }}>
          <input value={coupon} onChange={e => setCoupon(e.target.value.toUpperCase())} placeholder="FITFAMM10" style={{
            flex: 1, padding:'12px 14px',
            background:'#fff', color: C.fg,
            border:`1px solid ${C.border}`, borderRight: 0, outline:'none',
            fontFamily:'JetBrains Mono, monospace', fontSize: 12,
            letterSpacing:'0.12em', textTransform:'uppercase',
          }}/>
          <button onClick={applyCoupon} disabled={!coupon || couponApplied} style={{
            background: couponApplied ? C.accent : C.fg, color:'#fff', border:0,
            padding:'0 18px', cursor:'pointer',
            fontFamily:'JetBrains Mono, monospace', fontSize: 10, fontWeight: 700,
            letterSpacing:'0.18em', textTransform:'uppercase',
            opacity: !coupon && !couponApplied ? 0.5 : 1,
          }}>{couponApplied ? '✓ Listo' : 'Aplicar'}</button>
        </div>
      </div>

      {/* Total */}
      <div style={{
        marginTop: 24, paddingTop: 20, borderTop:'1px solid rgba(0,0,0,0.14)',
        display:'flex', justifyContent:'space-between', alignItems:'baseline',
      }}>
        <span style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 11, letterSpacing:'0.22em', textTransform:'uppercase' }}>Total</span>
        <span style={{ fontFamily:'Anton, sans-serif', fontSize: 40, letterSpacing:'-0.01em' }}>
          ${total.toLocaleString('es-MX')}{' '}
          <span style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 11, color: C.fgMuted }}>MXN</span>
        </span>
      </div>

      <button className="cmd-btn-primary" onClick={() => s.go('checkout')} style={{ marginTop: 20 }}>
        Finalizar compra {Icon.arrowR(16)}
      </button>

      <div style={{
        marginTop: 12, fontFamily:'JetBrains Mono, monospace', fontSize: 10,
        letterSpacing:'0.14em', textTransform:'uppercase', color: C.fgMuted, textAlign:'center',
      }}>
        3 MSI · Envío gratis · 30 días para cambios
      </div>
    </aside>
  );
}

function SummaryRow({ label, value, valueColor }) {
  return (
    <div style={{
      display:'flex', justifyContent:'space-between', alignItems:'baseline',
      padding:'7px 0',
    }}>
      <span style={{
        fontFamily:'JetBrains Mono, monospace', fontSize: 10,
        letterSpacing:'0.22em', textTransform:'uppercase', color: C.fgMuted,
      }}>{label}</span>
      <span style={{
        fontFamily:'JetBrains Mono, monospace', fontSize: 13, fontWeight: 500,
        color: valueColor || C.fg,
      }}>{value}</span>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════════
// CHECKOUT
// ════════════════════════════════════════════════════════════════════
function Checkout({ mobile }) {
  const s = useStore();
  const subtotal = s.cart.reduce((sum, it) => sum + it.price * it.qty, 0);
  const [delivery, setDelivery] = useState('shipping');
  const [studioId, setStudioId] = useState('');
  const [pickupDate, setPickupDate] = useState('');
  const [pickupMode, setPickupMode] = useState('pay');
  const isHold = delivery === 'pickup' && pickupMode === 'hold';
  const envio = delivery === 'pickup' ? 0 : (subtotal >= 1499 ? 0 : 99);
  const total = isHold ? 0 : subtotal + envio;
  const totalLabel = isHold ? 'pagas al recoger' : `$${total.toLocaleString('es-MX')} MXN`;
  const [payment, setPayment] = useState('card');
  const [installments, setInstallments] = useState('single');

  return (
    <main data-screen-label="Checkout" style={{ background:'#fff' }}>
      <div style={{
        display:'grid',
        gridTemplateColumns: mobile ? '1fr' : '1.5fr 1fr',
        gap: mobile ? 36 : 48,
        padding: mobile ? '24px 16px 64px' : '40px 32px 96px',
        alignItems:'start',
      }}>
        <div>
          <CheckoutDelivery mobile={mobile} delivery={delivery} setDelivery={setDelivery}
            studioId={studioId} setStudioId={setStudioId}
            pickupDate={pickupDate} setPickupDate={setPickupDate}
            pickupMode={pickupMode} setPickupMode={setPickupMode}/>
          {!isHold && (
            <CheckoutPayment mobile={mobile} payment={payment} setPayment={setPayment} installments={installments} setInstallments={setInstallments}/>
          )}
          <CheckoutTerms mobile={mobile}/>

          <button className="cmd-btn-primary" onClick={() => {
              s.setLastOrder && s.setLastOrder({ type: delivery, studioId, pickupDate, mode: pickupMode });
              s.go('confirmacion');
            }}
            style={{ marginTop: 28, fontSize: mobile ? 12 : 14, padding:'22px 20px', gap: 14 }}>
            {isHold
              ? <>Confirmar apartado · 48h {Icon.arrowR(16)}</>
              : <>Completar pedido · {totalLabel} {Icon.arrowR(16)}</>}
          </button>

          <div style={{
            marginTop: 14, fontFamily:'JetBrains Mono, monospace', fontSize: 10,
            letterSpacing:'0.18em', textTransform:'uppercase', color: C.fgMuted, textAlign:'center',
          }}>
            Conexión segura · 256-bit SSL · Pago procesado por Conekta
          </div>
        </div>

        <CheckoutSummary mobile={mobile} subtotal={subtotal} envio={envio} total={total}/>
      </div>
    </main>
  );
}

function CheckoutSteps({ current, mobile }) {
  const STEPS = [
    { n: 1, label:'Envío' },
    { n: 2, label:'Pago' },
    { n: 3, label:'Confirmación' },
  ];
  return (
    <div style={{
      padding: mobile ? '20px 16px 22px' : '28px 32px 24px',
      borderBottom:`1px solid ${C.border}`,
      display:'flex', alignItems:'center', justifyContent:'center', gap: mobile ? 8 : 24, flexWrap:'wrap',
    }}>
      {STEPS.map((s, i) => (
        <React.Fragment key={s.n}>
          {i > 0 && <span style={{ width: mobile ? 18 : 36, height: 1, background: C.fgMuted, opacity: 0.4 }}/>}
          <div style={{
            display:'flex', alignItems:'center', gap: 8,
            fontFamily:'JetBrains Mono, monospace', fontSize: 11,
            letterSpacing:'0.22em', textTransform:'uppercase',
            color: s.n === current ? C.accent : C.fgMuted, fontWeight: s.n === current ? 700 : 400,
          }}>
            <span style={{
              display:'inline-flex', alignItems:'center', justifyContent:'center',
              width: 22, height: 22, borderRadius:'50%',
              border:`1.5px solid ${s.n === current ? C.accent : C.fgMuted}`,
              background: s.n === current ? C.accent : 'transparent',
              color: s.n === current ? '#fff' : 'inherit',
              fontSize: 10, fontWeight: 700,
            }}>{s.n}</span>
            {s.label}
          </div>
        </React.Fragment>
      ))}
    </div>
  );
}

function CheckoutSectionTitle({ num, label }) {
  return (
    <div style={{
      display:'flex', alignItems:'baseline', gap: 16,
      marginBottom: 18, paddingBottom: 12, borderBottom:`1px solid ${C.fg}`,
    }}>
      <span style={{
        fontFamily:'JetBrains Mono, monospace', fontSize: 11,
        letterSpacing:'0.22em', color: C.accent,
      }}>{num}</span>
      <h2 style={{
        margin: 0, fontFamily:'Anton, sans-serif', fontSize: 32,
        textTransform:'uppercase', letterSpacing:'-0.01em', lineHeight: 1, paddingTop: 2,
      }}>{label}</h2>
    </div>
  );
}

function CheckoutDelivery({ mobile, delivery, setDelivery, studioId, setStudioId, pickupDate, setPickupDate, pickupMode, setPickupMode }) {
  return (
    <section style={{ marginBottom: 40 }}>
      <CheckoutSectionTitle num="01" label="Entrega"/>
      <div style={{
        display:'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 1fr',
        gap: 12, marginBottom: 24,
      }}>
        <DeliveryTab active={delivery === 'shipping'} onClick={() => setDelivery('shipping')}
          title="Envío a domicilio" hint="Gratis desde $1,499 MXN"/>
        <DeliveryTab active={delivery === 'pickup'} onClick={() => setDelivery('pickup')}
          title="Pickup en estudio" hint="Siempre gratis"/>
      </div>
      {delivery === 'shipping'
        ? <ShippingForm mobile={mobile}/>
        : <PickupForm mobile={mobile} studioId={studioId} setStudioId={setStudioId} pickupDate={pickupDate} setPickupDate={setPickupDate} pickupMode={pickupMode} setPickupMode={setPickupMode}/>}
    </section>
  );
}

function DeliveryTab({ active, onClick, title, hint }) {
  return (
    <button onClick={onClick} style={{
      padding:'20px 22px', textAlign:'left', cursor:'pointer',
      background: active ? C.fg : '#fff', color: active ? '#fff' : C.fg,
      border: active ? `1.5px solid ${C.fg}` : `1px solid ${C.border}`,
      display:'flex', flexDirection:'column', alignItems:'flex-start', gap: 8,
      transition:'background .15s, color .15s',
    }}>
      <span style={{ fontFamily:'Anton, sans-serif', fontSize: 20, textTransform:'uppercase', letterSpacing:'-0.005em', lineHeight: 1 }}>{title}</span>
      <span style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 10, letterSpacing:'0.22em', textTransform:'uppercase', opacity: 0.72 }}>{hint}</span>
    </button>
  );
}

function ShippingForm({ mobile }) {
  return (
    <div style={{ display:'grid', gap: 14, gridTemplateColumns: mobile ? '1fr' : '1fr 1fr' }}>
      <CheckField label="Nombre completo" placeholder="Como aparece en tu INE" full/>
      <CheckField label="Correo electrónico" placeholder="tu@correo.com" type="email"/>
      <CheckField label="Teléfono" placeholder="55 1234 5678" type="tel"/>
      <CheckField label="Calle y número" placeholder="Av. Polanco 123, int. 4B" full/>
      <CheckField label="Colonia" placeholder="Polanco V Secc."/>
      <CheckField label="CP" placeholder="11550"/>
      <CheckField label="Ciudad" placeholder="CDMX"/>
      <CheckField label="Estado" placeholder="Ciudad de México"/>
      <CheckField label="Referencias (opcional)" placeholder="Junto a Café Comezón" full/>
      <label style={{ gridColumn:'1 / -1', display:'flex', alignItems:'center', gap: 10, padding:'10px 0', cursor:'pointer' }}>
        <input type="checkbox" defaultChecked style={{ accentColor: C.accent, width: 16, height: 16 }}/>
        <span style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 11, letterSpacing:'0.14em', textTransform:'uppercase' }}>Guardar dirección para próximas compras</span>
      </label>
    </div>
  );
}

function PickupForm({ mobile, studioId, setStudioId, pickupDate, setPickupDate, pickupMode, setPickupMode }) {
  const groups = {};
  STUDIOS.forEach(st => { (groups[st.city] = groups[st.city] || []).push(st); });
  const today = new Date();
  const minDate = today.toISOString().slice(0,10);
  const max = new Date(today); max.setDate(today.getDate() + 14);
  const maxDate = max.toISOString().slice(0,10);
  return (
    <div style={{ display:'grid', gap: 16 }}>
      {/* Pickup mode toggle */}
      <div>
        <div style={{
          fontFamily:'JetBrains Mono, monospace', fontSize: 11,
          letterSpacing:'0.22em', textTransform:'uppercase', color: C.fgMuted, marginBottom: 10,
        }}>¿Cómo quieres recoger?</div>
        <div style={{
          display:'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 1fr', gap: 10,
        }}>
          <PickupModeCard
            active={pickupMode === 'pay'}
            onClick={() => setPickupMode('pay')}
            title="Pagar ahora"
            hint="Lista para recoger · sin tope"
            badge="recomendado"
          />
          <PickupModeCard
            active={pickupMode === 'hold'}
            onClick={() => setPickupMode('hold')}
            title="Apartar 48h"
            hint="Pruébala antes de pagar · paga en estudio"
          />
        </div>
      </div>

      <label style={{ display:'flex', flexDirection:'column', gap: 8 }}>
        <span style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 11, letterSpacing:'0.22em', textTransform:'uppercase', color: C.fgMuted }}>Estudio para recoger</span>
        <select value={studioId || ''} onChange={e => setStudioId(e.target.value)} style={checkInputStyle}>
          <option value="">Elige un estudio…</option>
          {Object.entries(groups).map(([city, list]) => {
            const open = list.filter(st => !st.soon);
            const soon = list.filter(st => st.soon);
            return (
              <optgroup key={city} label={`${city} · ${open.length} estudios`}>
                {open.map(st => (
                  <option key={st.id} value={st.id}>{st.name}</option>
                ))}
                {soon.map(st => (
                  <option key={st.id} value={st.id} disabled>{st.name} · próximamente</option>
                ))}
              </optgroup>
            );
          })}
        </select>
      </label>
      <label style={{ display:'flex', flexDirection:'column', gap: 8 }}>
        <span style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 11, letterSpacing:'0.22em', textTransform:'uppercase', color: C.fgMuted }}>Fecha de visita</span>
        <input type="date" value={pickupDate || ''} min={minDate} max={maxDate} onChange={e => setPickupDate(e.target.value)} style={checkInputStyle}/>
        <span style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 10, letterSpacing:'0.16em', textTransform:'uppercase', color: C.fgMuted }}>
          Disponible desde hoy y hasta 14 días después.
        </span>
      </label>
      <div style={{
        background: C.bgWarm, border:`1px solid ${C.border}`, padding:'18px 20px',
        display:'flex', gap: 14, alignItems:'flex-start',
      }}>
        <div style={{
          width: 32, height: 32, borderRadius:'50%', background: C.accent,
          color:'#fff', flexShrink: 0,
          display:'flex', alignItems:'center', justifyContent:'center', fontWeight: 700,
          fontFamily:'JetBrains Mono, monospace', fontSize: 16,
        }}>i</div>
        <div style={{ fontFamily:'Roboto, sans-serif', fontSize: 13, lineHeight: 1.5, color: C.fg }}>
          {pickupMode === 'hold' ? (
            <span><strong>Apartamos tu prenda 48 horas</strong> en el estudio elegido. Si te late, pagas al recogerla. Si no, sin compromiso.</span>
          ) : (
            <span><strong>Tu prenda queda lista para recoger</strong> en el estudio elegido. Pasa cuando quieras dentro del horario.</span>
          )}
        </div>
      </div>
    </div>
  );
}

function PickupModeCard({ active, onClick, title, hint, badge }) {
  return (
    <button onClick={onClick} style={{
      padding:'16px 18px', textAlign:'left', cursor:'pointer',
      background: active ? C.fg : '#fff', color: active ? '#fff' : C.fg,
      border: active ? `1.5px solid ${C.fg}` : `1px solid ${C.border}`,
      display:'flex', flexDirection:'column', alignItems:'flex-start', gap: 6,
      transition:'background .15s, color .15s', position:'relative',
    }}>
      {badge && (
        <span style={{
          position:'absolute', top: 10, right: 10,
          padding:'3px 7px', background: C.accent, color:'#fff',
          fontFamily:'JetBrains Mono, monospace', fontSize: 8, fontWeight: 700,
          letterSpacing:'0.22em', textTransform:'uppercase',
        }}>{badge}</span>
      )}
      <span style={{ fontFamily:'Anton, sans-serif', fontSize: 18, textTransform:'uppercase', letterSpacing:'-0.005em', lineHeight: 1 }}>{title}</span>
      <span style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 10, letterSpacing:'0.18em', textTransform:'uppercase', opacity: 0.72 }}>{hint}</span>
    </button>
  );
}

const checkInputStyle = {
  padding:'14px 16px', border:`1px solid ${C.border}`, background:'#fff', color: C.fg,
  outline:'none',
  fontFamily:'JetBrains Mono, monospace', fontSize: 12, letterSpacing:'0.06em',
};

function CheckField({ label, placeholder, type = 'text', full }) {
  return (
    <label style={{ display:'flex', flexDirection:'column', gap: 8, gridColumn: full ? '1 / -1' : 'auto' }}>
      <span style={{
        fontFamily:'JetBrains Mono, monospace', fontSize: 11,
        letterSpacing:'0.22em', textTransform:'uppercase', color: C.fgMuted,
      }}>{label}</span>
      <input type={type} placeholder={placeholder} style={checkInputStyle}/>
    </label>
  );
}

function CheckoutPayment({ mobile, payment, setPayment, installments, setInstallments }) {
  const METHODS = [
    { k:'card', title:'Tarjeta', hint:'Crédito o débito · 3 MSI' },
    { k:'oxxo', title:'OXXO Pay', hint:'Pago en efectivo · 24h' },
    { k:'spei', title:'SPEI', hint:'Transferencia bancaria' },
    { k:'mp', title:'Mercado Pago', hint:'Saldo o tarjeta MP' },
  ];
  return (
    <section style={{ marginBottom: 36 }}>
      <CheckoutSectionTitle num="02" label="Pago"/>
      <div style={{
        display:'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 1fr',
        gap: 12, marginBottom: 24,
      }}>
        {METHODS.map(m => (
          <DeliveryTab key={m.k} active={payment === m.k} onClick={() => setPayment(m.k)} title={m.title} hint={m.hint}/>
        ))}
      </div>

      {payment === 'card' ? (
        <div style={{ display:'grid', gap: 14, gridTemplateColumns: mobile ? '1fr' : '2fr 2fr 1fr 1fr' }}>
          <CheckField label="Número de tarjeta" placeholder="0000 0000 0000 0000" full/>
          <CheckField label="Nombre en la tarjeta" placeholder="Como aparece" full/>
          <CheckField label="Vencimiento" placeholder="MM / AA"/>
          <CheckField label="CVV" placeholder="•••"/>

          <div style={{ gridColumn:'1 / -1', marginTop: 8 }}>
            <div style={{
              fontFamily:'JetBrains Mono, monospace', fontSize: 11,
              letterSpacing:'0.22em', textTransform:'uppercase', color: C.fgMuted, marginBottom: 10,
            }}>Plan de pago</div>
            <div style={{ display:'flex', gap: 10, flexWrap:'wrap' }}>
              {[
                { k:'single', label:'Un solo pago' },
                { k:'msi3', label:'3 meses sin intereses' },
              ].map(p => (
                <button key={p.k} onClick={() => setInstallments(p.k)} style={{
                  padding:'10px 16px', cursor:'pointer',
                  background: installments === p.k ? C.fg : '#fff',
                  color: installments === p.k ? '#fff' : C.fg,
                  border: installments === p.k ? `1.5px solid ${C.fg}` : `1px solid ${C.border}`,
                  fontFamily:'JetBrains Mono, monospace', fontSize: 11, fontWeight: 700,
                  letterSpacing:'0.14em', textTransform:'uppercase',
                }}>{p.label}</button>
              ))}
            </div>
          </div>

          <label style={{ gridColumn:'1 / -1', display:'flex', alignItems:'center', gap: 10, padding:'8px 0', cursor:'pointer' }}>
            <input type="checkbox" style={{ accentColor: C.accent, width: 16, height: 16 }}/>
            <span style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 11, letterSpacing:'0.14em', textTransform:'uppercase' }}>Guardar tarjeta para futuras compras</span>
          </label>
        </div>
      ) : (
        <PaymentInfoBox method={payment}/>
      )}
    </section>
  );
}

function PaymentInfoBox({ method }) {
  const info = {
    oxxo: { title:'OXXO Pay', body:'Te generamos un código de barras. Acude a cualquier OXXO en las próximas 24 horas y paga en efectivo. Tu pedido se confirma al recibir el pago.' },
    spei: { title:'SPEI', body:'Recibes los datos bancarios al confirmar. Realiza la transferencia desde tu app bancaria. El pago se acredita en minutos.' },
    mp:   { title:'Mercado Pago', body:'Te redirigimos a Mercado Pago para confirmar el pago con tu saldo o tarjeta guardada. Vuelves automáticamente al sitio.' },
  };
  const i = info[method];
  if (!i) return null;
  return (
    <div style={{
      background: C.bgWarm, border:`1px solid ${C.border}`, padding:'20px 22px',
      display:'flex', gap: 14, alignItems:'flex-start',
    }}>
      <div style={{
        width: 32, height: 32, borderRadius:'50%', background: C.accent,
        color:'#fff', flexShrink: 0,
        display:'flex', alignItems:'center', justifyContent:'center',
        fontFamily:'JetBrains Mono, monospace', fontWeight: 700, fontSize: 16,
      }}>i</div>
      <div>
        <div style={{
          fontFamily:'Anton, sans-serif', fontSize: 20,
          textTransform:'uppercase', letterSpacing:'-0.005em', marginBottom: 6, lineHeight: 1,
        }}>{i.title}</div>
        <div style={{ fontFamily:'Roboto, sans-serif', fontSize: 13, color: C.fg, lineHeight: 1.5 }}>{i.body}</div>
      </div>
    </div>
  );
}

function CheckoutTerms({ mobile }) {
  return (
    <section>
      <CheckoutSectionTitle num="03" label="Confirmación"/>
      <div style={{ display:'flex', flexDirection:'column', gap: 14 }}>
        <label style={{ display:'flex', alignItems:'flex-start', gap: 12, cursor:'pointer' }}>
          <input type="checkbox" defaultChecked style={{ accentColor: C.accent, width: 16, height: 16, marginTop: 3 }}/>
          <span style={{ fontFamily:'Roboto, sans-serif', fontSize: 13, lineHeight: 1.55 }}>
            Acepto los <a href="#" style={{ color: C.accent }}>términos y condiciones</a>, la <a href="#" style={{ color: C.accent }}>política de privacidad</a> y la política de devoluciones.
          </span>
        </label>
        <label style={{ display:'flex', alignItems:'flex-start', gap: 12, cursor:'pointer' }}>
          <input type="checkbox" defaultChecked style={{ accentColor: C.accent, width: 16, height: 16, marginTop: 3 }}/>
          <span style={{ fontFamily:'Roboto, sans-serif', fontSize: 13, lineHeight: 1.55 }}>
            Quiero recibir drops, comunidad y descuentos exclusivos al correo.
          </span>
        </label>
      </div>
    </section>
  );
}

function CheckoutSummary({ mobile, subtotal, envio, total }) {
  const s = useStore();
  const cart = s.cart;
  return (
    <aside style={{
      position: mobile ? 'static' : 'sticky', top: mobile ? 'auto' : 24,
      background: C.bgWarm, padding: mobile ? '22px 20px' : '28px',
    }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom: 18 }}>
        <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 11, letterSpacing:'0.22em', textTransform:'uppercase', color: C.fgMuted }}>Tu pedido</div>
        <button onClick={() => s.go('bolsa')} style={{
          background:'transparent', border: 0, padding: 0, cursor:'pointer',
          fontFamily:'JetBrains Mono, monospace', fontSize: 10,
          letterSpacing:'0.22em', textTransform:'uppercase', color: C.accent, textDecoration:'underline',
        }}>← Editar bolsa</button>
      </div>

      <div style={{
        display:'flex', flexDirection:'column', gap: 14,
        marginBottom: 18, paddingBottom: 16,
        borderBottom:'1px solid rgba(0,0,0,0.12)',
      }}>
        {cart.map((it, i) => {
          const prod = PRODUCTS.find(p => p.id === it.id);
          const colorObj = prod && prod.colors.find(c => c.name === it.color);
          const img = prod && resolveProductImage(prod, colorObj || (prod && prod.colors[0]), 'front');
          return (
          <div key={i} style={{ display:'grid', gridTemplateColumns:'52px 1fr auto', gap: 12, alignItems:'center' }}>
            <div style={{ position:'relative', width: 52, height: 64, background: img ? '#F4F2EC' : it.colorHex, overflow:'hidden' }}>
              {img ? (
                <img src={img} alt={it.name} loading="lazy" style={{
                  position:'absolute', inset:0, width:'100%', height:'100%', objectFit:'cover', display:'block',
                }}/>
              ) : (
                <div style={{ position:'absolute', inset:0, background:`repeating-linear-gradient(45deg, transparent 0 6px, rgba(255,255,255,0.06) 6px 7px)` }}/>
              )}
              <span style={{
                position:'absolute', top: -4, right: -4, minWidth: 18, height: 18, padding:'0 5px',
                borderRadius: 9, background: C.fg, color:'#fff', fontSize: 9, fontWeight: 700,
                fontFamily:'JetBrains Mono, monospace',
                display:'inline-flex', alignItems:'center', justifyContent:'center',
                border:`2px solid ${C.bgWarm}`,
              }}>{it.qty}</span>
            </div>
            <div>
              <div style={{ fontFamily:'Anton, sans-serif', fontSize: 14, textTransform:'uppercase', letterSpacing:'-0.005em', lineHeight: 1.05 }}>{it.name}</div>
              <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 9, letterSpacing:'0.18em', textTransform:'uppercase', color: C.fgMuted, marginTop: 3 }}>
                {it.color} · {it.size}
              </div>
            </div>
            <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 12, fontWeight: 700 }}>
              ${(it.price * it.qty).toLocaleString('es-MX')}
            </div>
          </div>
        );})}
      </div>

      <SummaryRow label="Subtotal" value={`$${subtotal.toLocaleString('es-MX')} MXN`}/>
      <SummaryRow label="Envío" value={envio === 0 ? 'Gratis' : `$${envio} MXN`} valueColor={envio === 0 ? C.accent : C.fg}/>

      <div style={{
        marginTop: 18, paddingTop: 16, borderTop:'1px solid rgba(0,0,0,0.12)',
        display:'flex', justifyContent:'space-between', alignItems:'baseline',
      }}>
        <span style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 11, letterSpacing:'0.22em', textTransform:'uppercase' }}>Total</span>
        <span style={{ fontFamily:'Anton, sans-serif', fontSize: 32, letterSpacing:'-0.01em' }}>
          ${total.toLocaleString('es-MX')}{' '}
          <span style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 10, color: C.fgMuted }}>MXN</span>
        </span>
      </div>
    </aside>
  );
}

// ════════════════════════════════════════════════════════════════════
// CONFIRMACIÓN
// ════════════════════════════════════════════════════════════════════
function Confirmacion({ mobile }) {
  const s = useStore();
  // Differentiate by order type + pickup mode
  const isPickup = s.lastOrderType === 'pickup';
  const isHold   = isPickup && s.lastOrderMode === 'hold';
  const studio = isPickup && s.lastOrderStudio ? STUDIOS.find(st => st.id === s.lastOrderStudio) : null;
  const order = 'CMD-26-001847';
  const total = s.cart.reduce((sum, it) => sum + it.price * it.qty, 0);
  // ETA
  const today = new Date();
  const eta1 = new Date(today); eta1.setDate(today.getDate() + 5);
  const eta2 = new Date(today); eta2.setDate(today.getDate() + 9);
  const etaStr = `Entre el ${eta1.getDate()} y ${eta2.getDate()} de ${eta2.toLocaleDateString('es-MX', { month:'long' })}`;

  return (
    <main data-screen-label="Confirmación" style={{ background:'#fff' }}>
      {/* Hero */}
      <section style={{
        padding: mobile ? '40px 16px 48px' : '72px 32px 80px',
        borderBottom:`1px solid ${C.border}`,
      }}>
        <div style={{
          display:'inline-flex', alignItems:'center', gap: 12, marginBottom: 18,
          fontFamily:'JetBrains Mono, monospace', fontSize: 12,
          letterSpacing:'0.22em', textTransform:'uppercase', color: C.accent,
        }}>
          <span style={{
            width: 24, height: 24, borderRadius:'50%', background: C.accent,
            color:'#fff', display:'inline-flex', alignItems:'center', justifyContent:'center',
            fontSize: 12, fontWeight: 700,
          }}>✓</span>
          {isHold ? 'Apartado confirmado' : (isPickup ? 'Pago confirmado · Pickup' : 'Pago confirmado')}
        </div>
        <div style={{
          fontFamily:'Anton, sans-serif', fontSize: mobile ? 56 : 'clamp(88px, 10vw, 160px)',
          lineHeight: 0.9, letterSpacing:'-0.02em', textTransform:'uppercase',
          paddingTop: 4, marginBottom: 22,
        }}>
          {isHold ? (<>Apartada<br/><span style={{ color: C.accent }}>por 48 horas.</span></>)
            : isPickup ? (<>Compra<br/>finalizada.<br/><span style={{ color: C.accent }}>Lista para recoger.</span></>)
            : (<>Pedido<br/>realizado.</>)}
        </div>
        <div style={{
          display:'flex', flexWrap:'wrap', gap: mobile ? 12 : 28, alignItems:'baseline',
          fontFamily:'JetBrains Mono, monospace', fontSize: mobile ? 11 : 13,
          letterSpacing:'0.16em', textTransform:'uppercase', color: C.fgMuted,
        }}>
          <span>Orden ·{' '}<span style={{ color: C.fg, fontWeight: 700 }}>#{order}</span></span>
          <span style={{ opacity: 0.4 }}>/</span>
          <span>Total · <span style={{ color: C.fg, fontWeight: 700 }}>${total.toLocaleString('es-MX')} MXN</span></span>
          <span style={{ opacity: 0.4 }}>/</span>
          <span>Confirmación al correo</span>
        </div>
      </section>

      {/* Tracking */}
      <section style={{
        padding: mobile ? '36px 16px 44px' : '64px 32px 72px',
        borderBottom:`1px solid ${C.border}`,
      }}>
        <div style={{
          fontFamily:'JetBrains Mono, monospace', fontSize: 11,
          letterSpacing:'0.22em', textTransform:'uppercase', color: C.fgMuted, marginBottom: 24,
        }}>{isPickup ? 'Detalles del apartado' : 'Estatus del pedido'}</div>
        {isPickup ? (
          <PickupConfirmDetails mobile={mobile} studio={studio} pickupDate={s.lastOrderDate} isHold={isHold} total={total}/>
        ) : (
          <React.Fragment>
            <TrackingLine current={0} mobile={mobile}/>
            <div style={{
              display:'grid', gridTemplateColumns: mobile ? '1fr' : 'repeat(3, 1fr)',
              gap: mobile ? 18 : 32, marginTop: 40,
            }}>
              <InfoBlock label="Llegada estimada" value={etaStr.charAt(0).toUpperCase() + etaStr.slice(1)}/>
              <InfoBlock label="Dirección de envío" value="Av. Polanco 123, int. 4B · Polanco V Secc. · CDMX 11550"/>
              <InfoBlock label="Número de guía" value="Pendiente · te avisamos al asignar"/>
            </div>
          </React.Fragment>
        )}
      </section>

      {/* Cross-sell estudio */}
      <section style={{
        background: C.fg, color:'#fff',
        padding: mobile ? '52px 16px 60px' : '96px 32px 112px',
      }}>
        <div style={{
          display:'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 1fr',
          gap: mobile ? 28 : 56, alignItems:'center',
        }}>
          <div>
            <div style={{
              fontFamily:'JetBrains Mono, monospace', fontSize: 11,
              letterSpacing:'0.22em', textTransform:'uppercase', color: C.accent, marginBottom: 14,
            }}>Mientras te llega</div>
            <div style={{
              fontFamily:'Anton, sans-serif', fontSize: mobile ? 52 : 'clamp(64px, 6.5vw, 108px)',
              lineHeight: 0.92, letterSpacing:'-0.015em', textTransform:'uppercase',
              paddingTop: 4, marginBottom: 22,
            }}>
              Pasa por<br/>el <span style={{ color: C.accent }}>estudio</span>.
            </div>
            <p style={{
              margin: 0, marginBottom: 28, maxWidth: 460,
              fontFamily:'Roboto, sans-serif', fontSize: mobile ? 15 : 17,
              color:'rgba(255,255,255,0.78)', lineHeight: 1.5,
            }}>
              Reserva una clase mientras tu pedido viaja. La gente que entrena con nosotros también es la que diseñó esto.
            </p>
            <a href="https://commandostudio.com/mx/" target="_blank" rel="noopener noreferrer" style={{
              display:'inline-flex', alignItems:'center', gap: 12,
              padding:'16px 24px', border:'1.5px solid #fff',
              fontFamily:'JetBrains Mono, monospace', fontSize: 12, fontWeight: 700,
              letterSpacing:'0.22em', textTransform:'uppercase', color:'#fff',
              textDecoration:'none', cursor:'pointer', transition:'background .2s, color .2s',
            }} onMouseEnter={e => { e.currentTarget.style.background = '#fff'; e.currentTarget.style.color = C.fg; }}
              onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = '#fff'; }}>
              Reservar clase en Commando Studio
              <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
            </a>
          </div>
          <div style={{
            aspectRatio:'4/5', background:'#1A1714',
            position:'relative', overflow:'hidden',
          }}>
            <div style={{ position:'absolute', inset:0, background:`repeating-linear-gradient(45deg, transparent 0 18px, rgba(255,255,255,0.04) 18px 19px)` }}/>
            <div style={{
              position:'absolute', top: 14, left: 14,
              fontFamily:'JetBrains Mono, monospace', fontSize: 10,
              letterSpacing:'0.22em', textTransform:'uppercase', color:'rgba(255,255,255,0.55)',
            }}>Studio · Polanco · 04/24</div>
            <div style={{
              position:'absolute', bottom: 14, left: 14, right: 14,
              fontFamily:'JetBrains Mono, monospace', fontSize: 10,
              letterSpacing:'0.22em', textTransform:'uppercase', color:'rgba(255,255,255,0.4)',
            }}>[ Frame placeholder ]</div>
          </div>
        </div>
      </section>

      {/* Actions */}
      <section style={{ padding: mobile ? '36px 16px 56px' : '64px 32px 80px' }}>
        <div style={{
          display:'grid',
          gridTemplateColumns: mobile ? '1fr' : 'repeat(3, 1fr)',
          gap: mobile ? 12 : 16,
        }}>
          <button className="cmd-btn-secondary" onClick={() => alert('Mock: compartir orden #' + order)}>
            Compartir en Instagram
          </button>
          <button className="cmd-btn-secondary" onClick={() => alert('Mock: ver detalles del pedido #' + order)}>
            Ver mi pedido
          </button>
          <button className="cmd-btn-secondary" onClick={() => { s.clearCart && s.clearCart(); s.go('home'); }}>
            Volver a la tienda
          </button>
        </div>
        <div style={{
          marginTop: 36,
          fontFamily:'JetBrains Mono, monospace', fontSize: 11,
          letterSpacing:'0.18em', textTransform:'uppercase', color: C.fgMuted,
          textAlign:'center', lineHeight: 1.7,
        }}>
          ¿Algo no salió bien?<br/>
          <a href="tel:5585250802" style={{ color: C.accent, textDecoration:'none' }}>55 8525 0802</a>
          <span style={{ opacity: 0.4 }}> · </span>
          <a href="mailto:hola@commandostudio.com" style={{ color: C.accent, textDecoration:'none' }}>hola@commandostudio.com</a>
        </div>
      </section>
    </main>
  );
}

function PickupConfirmDetails({ mobile, studio, pickupDate, isHold, total }) {
  const dateLabel = pickupDate
    ? new Date(pickupDate + 'T00:00:00').toLocaleDateString('es-MX', { weekday:'long', day:'numeric', month:'long' })
    : 'Por confirmar';
  return (
    <div style={{
      display:'grid', gridTemplateColumns: mobile ? '1fr' : '1.2fr 1fr',
      gap: mobile ? 18 : 32, alignItems:'start',
    }}>
      <div style={{
        background: C.bgWarm, border:`1px solid ${C.border}`,
        padding: mobile ? '20px 18px' : '28px 28px',
      }}>
        <div style={{
          fontFamily:'JetBrains Mono, monospace', fontSize: 10,
          letterSpacing:'0.22em', textTransform:'uppercase', color: C.accent, marginBottom: 12,
        }}>{isHold ? 'Apartado por 48 horas' : 'Pagada · lista para recoger'}</div>
        <div style={{
          fontFamily:'Anton, sans-serif', fontSize: mobile ? 32 : 44,
          textTransform:'uppercase', letterSpacing:'-0.01em', lineHeight: 1, marginBottom: 14,
        }}>
          {studio ? studio.name : 'Estudio'}<br/>
          <span style={{ color: C.fgMuted, fontSize: mobile ? 18 : 22 }}>{studio ? studio.city : ''}</span>
        </div>
        <div style={{ fontFamily:'Roboto, sans-serif', fontSize: 14, color:'#333', lineHeight: 1.5 }}>
          {isHold
            ? 'Presenta tu confirmación en recepción. Pruébala con calma. Si te late, pagas en estudio; si no, sin compromiso.'
            : 'Tu prenda ya está pagada y reservada en el estudio. Presenta tu confirmación en recepción y te la entregan al instante.'}
        </div>
      </div>
      <div style={{ display:'grid', gap: 18 }}>
        <InfoBlock label="Fecha de visita" value={dateLabel}/>
        <InfoBlock label="Horario de recepción" value="Lunes a viernes · 7:00 — 21:00 · Sábados · 8:00 — 14:00"/>
        <InfoBlock label={isHold ? 'Total a pagar en estudio' : 'Total pagado'} value={`$${(total || 0).toLocaleString('es-MX')} MXN`}/>
        <InfoBlock label="Trae contigo" value="Tu correo de confirmación o el número de orden."/>
      </div>
    </div>
  );
}

function InfoBlock({ label, value }) {
  return (
    <div>
      <div style={{
        fontFamily:'JetBrains Mono, monospace', fontSize: 10,
        letterSpacing:'0.22em', textTransform:'uppercase', color: C.fgMuted, marginBottom: 6,
      }}>{label}</div>
      <div style={{
        fontFamily:'Roboto, sans-serif', fontSize: 14, lineHeight: 1.45, color: C.fg,
      }}>{value}</div>
    </div>
  );
}

function TrackingLine({ current, mobile }) {
  const STEPS = ['Procesado','En producción','En camino','Entregado'];
  const pct = STEPS.length > 1 ? (current / (STEPS.length - 1)) * 100 : 0;
  return (
    <div style={{
      position:'relative',
      display:'grid', gridTemplateColumns: `repeat(${STEPS.length}, 1fr)`, gap: 0,
    }}>
      {/* connector line (back) */}
      <div style={{
        position:'absolute',
        top: 11, left: `${50 / STEPS.length}%`, right: `${50 / STEPS.length}%`,
        height: 2, background: C.border, zIndex: 0,
      }}/>
      {/* connector line (filled) */}
      <div style={{
        position:'absolute',
        top: 11, left: `${50 / STEPS.length}%`,
        width: `calc((100% - ${100 / STEPS.length}%) * ${pct / 100})`,
        height: 2, background: C.accent, zIndex: 0,
      }}/>
      {STEPS.map((label, i) => (
        <div key={i} style={{
          display:'flex', flexDirection:'column', alignItems:'center',
          position:'relative', zIndex: 1,
        }}>
          <div style={{
            width: 24, height: 24, borderRadius:'50%',
            border:`2px solid ${i <= current ? C.accent : C.border}`,
            background: i <= current ? C.accent : '#fff',
            color:'#fff', fontSize: 10, fontWeight: 700,
            display:'flex', alignItems:'center', justifyContent:'center',
            marginBottom: 12, transition:'background .25s, border-color .25s',
          }}>{i < current ? '✓' : (i === current ? '●' : '')}</div>
          <div style={{
            fontFamily:'JetBrains Mono, monospace', fontSize: mobile ? 9 : 11,
            letterSpacing:'0.16em', textTransform:'uppercase',
            color: i <= current ? C.fg : C.fgMuted,
            fontWeight: i === current ? 700 : 400,
            textAlign:'center', lineHeight: 1.3,
          }}>{label}</div>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { Bolsa, Checkout, Confirmacion });
