/* ───────────────────────────────────────────────────────────────────────
   V1 — One-page checkout (desktop, redesigned)
   Left  → customer info: identification, delivery (data + address + method),
           billing.
   Right → order: items + coupon + totals, payment method, trust.
   No cross-sell.
   ─────────────────────────────────────────────────────────────────────── */

function CheckoutV1({ onSuccess, onNavigate, cart: cartProp, updateCart, removeCart }) {
  const [authMode, setAuthMode] = React.useState('guest');
  const [shipping, setShipping] = React.useState('free');
  const [payment, setPayment]   = React.useState('transfer');
  const [billing, setBilling]   = React.useState('cf');
  const [installments, setInstallments] = React.useState(12);
  const [coupon, setCoupon] = React.useState(null);
  const [fallbackCart, setFallbackCart] = React.useState(MOCK_CART);

  const usingReal = !!cartProp;
  const cart = cartProp || fallbackCart;

  const updateQty = (i, delta) => {
    const item = cart[i];
    const newQty = Math.max(1, item.qty + delta);
    if (usingReal) updateCart(item.id, newQty);
    else setFallbackCart((c) => c.map((it, j) => j === i ? { ...it, qty: newQty } : it));
  };
  const removeItem = (i) => {
    const item = cart[i];
    if (usingReal) removeCart(item.id);
    else setFallbackCart((c) => c.filter((_, j) => j !== i));
  };
  const subtotal = cart.reduce((s, i) => s + i.price * i.qty, 0);
  const shipObj = MOCK_SHIPPING.find(s => s.id === shipping);
  const paymentDiscPct = payment === 'transfer' ? 15 : 0;
  const totals = MOCK_TOTALS(subtotal, shipObj.price, paymentDiscPct, coupon ? 5 : 0);

  const nav = (path) => onNavigate ? onNavigate(path) : null;

  return (
    <div style={{ background: 'var(--bg)', minHeight: '100%' }}>
      <CheckoutHeader onNavigate={onNavigate}/>

      {/* Title */}
      <div style={{ padding: '24px 28px 0' }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', flexWrap: 'wrap', gap: 10 }}>
          <h1 style={{ fontSize: 28, fontWeight: 800, letterSpacing: '-0.02em', margin: 0 }}>Finalizar compra</h1>
          <a href="/" onClick={(e) => { e.preventDefault(); nav('/'); }}
             style={{ fontSize: 13, color: 'var(--ink-3)', textDecoration: 'underline', textUnderlineOffset: 3 }}>
            ← Seguir comprando
          </a>
        </div>
      </div>

      {/* Body grid */}
      <div style={{
        display: 'grid', gridTemplateColumns: '1fr 420px', gap: 22,
        padding: '20px 28px 40px',
        alignItems: 'start',
      }}>
        {/* ─────────── LEFT — CUSTOMER INFO ─────────── */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>

          {/* 1. Identificación */}
          <CkCard>
            <SectionTitle n="1" title="Identificación" subtitle="Ingresá si ya sos cliente, o comprá como invitado"/>
            <div style={{ display: 'flex', gap: 4, padding: 4, background: 'var(--bg-2)', borderRadius: 10, marginBottom: 14 }}>
              {[
                { id: 'guest', label: 'Soy nuevo / Compro como invitado' },
                { id: 'login', label: 'Ya tengo cuenta' },
              ].map((m) => (
                <button key={m.id} onClick={() => setAuthMode(m.id)} style={{
                  flex: 1, padding: '10px 14px', fontSize: 13, fontWeight: 600,
                  background: authMode === m.id ? '#fff' : 'transparent',
                  color: authMode === m.id ? 'var(--ink)' : 'var(--ink-3)',
                  borderRadius: 7,
                  boxShadow: authMode === m.id ? '0 1px 2px rgba(0,0,0,0.06)' : 'none',
                  transition: 'all .15s',
                }}>{m.label}</button>
              ))}
            </div>

            {authMode === 'login' ? (
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: 12 }}>
                <Field label="Email" required span={6}>
                  <Input type="email" placeholder="tu@email.com" icon="mail"/>
                </Field>
                <Field label="Contraseña" required span={6}>
                  <Input type="password" placeholder="••••••••"/>
                </Field>
                <div style={{ gridColumn: 'span 12', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <a href="#" onClick={(e) => e.preventDefault()} style={{ fontSize: 12, color: 'var(--ink-3)', textDecoration: 'underline' }}>¿Olvidaste tu contraseña?</a>
                  <button className="btn btn-dark" style={{ padding: '10px 22px', fontSize: 13 }}>Ingresar</button>
                </div>
              </div>
            ) : (
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: 12 }}>
                <Field label="Email" hint="Te enviaremos la confirmación acá" required span={6}>
                  <Input type="email" placeholder="tu@email.com" icon="mail"/>
                </Field>
                <Field label="Teléfono / WhatsApp" hint="Por dudas del envío" required span={6}>
                  <Input type="tel" placeholder="11 5555 5555" icon="phone"/>
                </Field>
                <div style={{ gridColumn: 'span 12', display: 'flex', alignItems: 'center', gap: 8 }}>
                  <input type="checkbox" defaultChecked id="cv1-create" style={{ accentColor: '#a00e0c' }}/>
                  <label htmlFor="cv1-create" style={{ fontSize: 12, color: 'var(--ink-3)' }}>
                    Crear cuenta con este email para seguir mis pedidos
                  </label>
                </div>
              </div>
            )}
          </CkCard>

          {/* 2. Entrega */}
          <CkCard>
            <SectionTitle n="2" title="Entrega"/>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: 12, marginBottom: 18 }}>
              <Field label="Nombre" required span={6}><Input placeholder="Juan" defaultValue="Juan"/></Field>
              <Field label="Apellido" required span={6}><Input placeholder="Pérez" defaultValue="Pérez"/></Field>
              <Field label="DNI" required span={6}><Input placeholder="34.555.666"/></Field>
              <Field label="Código postal" required span={6}>
                <Input placeholder="1706" icon="pin" suffix="CABA"/>
              </Field>
              <Field label="Calle" required span={8}><Input placeholder="Av. Rivadavia" defaultValue="Av. Rivadavia"/></Field>
              <Field label="Número" required span={4}><Input placeholder="1234"/></Field>
              <Field label="Depto / Piso (opcional)" span={6}><Input placeholder="3°B"/></Field>
              <Field label="Localidad" required span={6}><Input placeholder="Caballito" defaultValue="Caballito"/></Field>
              <Field label="Indicaciones para el repartidor (opcional)" span={12}>
                <Input placeholder="Timbre roto, llamar al teléfono"/>
              </Field>
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink-2)', letterSpacing: '-0.005em', marginBottom: 2 }}>Método de envío</div>
              {MOCK_SHIPPING.map((opt) => (
                <RadioOption key={opt.id} checked={shipping === opt.id} onClick={() => setShipping(opt.id)}
                  title={opt.title} subtitle={opt.subtitle} price={opt.price} badge={opt.badge} accent={opt.accent}/>
              ))}
            </div>
          </CkCard>

          {/* 3. Facturación */}
          <CkCard>
            <SectionTitle n="3" title="Datos de facturación"/>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 14 }}>
              {[
                { id: 'cf', label: 'Consumidor final', sub: 'Factura B sin discriminar IVA' },
                { id: 'ri', label: 'Responsable inscripto', sub: 'Factura A con IVA discriminado' },
              ].map((o) => (
                <button key={o.id} onClick={() => setBilling(o.id)} style={{
                  textAlign: 'left',
                  padding: '14px 16px',
                  border: '1.5px solid ' + (billing === o.id ? '#a00e0c' : 'var(--line)'),
                  background: billing === o.id ? '#FFF5F4' : 'var(--surface)',
                  borderRadius: 10,
                }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--ink)' }}>{o.label}</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>{o.sub}</div>
                </button>
              ))}
            </div>
            {billing === 'ri' && (
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: 12 }}>
                <Field label="Razón social" required span={6}><Input placeholder="Mi Empresa SRL"/></Field>
                <Field label="CUIT" required span={6}><Input placeholder="30-12345678-9"/></Field>
                <Field label="Domicilio fiscal" required span={12}><Input placeholder="Av. Corrientes 1234, CABA"/></Field>
              </div>
            )}
          </CkCard>

          {/* Confirm CTA */}
          <div style={{ display: 'flex', gap: 12, marginTop: 6 }}>
            <button onClick={() => nav('/')} className="btn btn-ghost" style={{ padding: '14px 22px', fontSize: 14, flexShrink: 0 }}>
              <Icon name="chevronLeft" size={14}/> Volver al carrito
            </button>
            <button className="btn btn-primary" onClick={onSuccess} style={{ padding: '16px 22px', fontSize: 15, flex: 1, fontWeight: 700 }}>
              Confirmar pedido · $ {totals.total.toLocaleString('es-AR')} <Icon name="arrowRight" size={15}/>
            </button>
          </div>
          <div style={{ fontSize: 11, color: 'var(--ink-4)', textAlign: 'center' }}>
            Al confirmar aceptás nuestros <a href="#" style={{ textDecoration: 'underline', color: 'var(--ink-3)' }}>Términos</a> y la <a href="#" style={{ textDecoration: 'underline', color: 'var(--ink-3)' }}>Política de privacidad</a>.
          </div>
        </div>

        {/* ─────────── RIGHT — ORDER + PAYMENT ─────────── */}
        <div style={{ position: 'sticky', top: 14, display: 'flex', flexDirection: 'column', gap: 14 }}>

          {/* Order summary */}
          <CkCard>
            <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 6 }}>
              <h3 style={{ fontSize: 16, fontWeight: 700, letterSpacing: '-0.01em', margin: 0 }}>Tu pedido</h3>
              <span className="mono" style={{ fontSize: 11, color: 'var(--ink-4)', letterSpacing: '0.06em' }}>{cart.length} productos</span>
            </div>

            <div style={{ borderTop: '1px solid var(--line)', marginTop: 12 }}>
              {cart.map((it, i) => <SummaryItem key={i} {...it}
                onChangeQty={(delta) => updateQty(i, delta)}
                onRemove={() => removeItem(i)}/>)}
            </div>

            <div style={{ marginTop: 16 }}>
              <CouponBox applied={coupon} onApply={(c) => setCoupon(c)} onRemove={() => setCoupon(null)}/>
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 18, padding: '14px 0', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
              <SummaryRow label="Subtotal" value={'$ ' + subtotal.toLocaleString('es-AR')}/>
              <SummaryRow label="Descuento producto" value={'− $ ' + totals.productDiscount.toLocaleString('es-AR')} color="#0f8a5b"/>
              {totals.paymentDiscount > 0 && (
                <SummaryRow label={`Descuento por ${payment === 'transfer' ? 'transferencia' : 'pago'} (15%)`} value={'− $ ' + totals.paymentDiscount.toLocaleString('es-AR')} color="#0f8a5b"/>
              )}
              {totals.couponDiscount > 0 && (
                <SummaryRow label={`Cupón ${coupon} (5%)`} value={'− $ ' + totals.couponDiscount.toLocaleString('es-AR')} color="#0f8a5b"/>
              )}
              <SummaryRow label="Envío" value={shipObj.price === 0 ? 'GRATIS' : shipObj.price === null ? 'A cotizar' : '$ ' + shipObj.price.toLocaleString('es-AR')}
                color={shipObj.price === 0 ? '#0f8a5b' : undefined}/>
            </div>

            <div style={{ marginTop: 14 }}>
              <SummaryRow label="Total a pagar" value={'$ ' + totals.total.toLocaleString('es-AR')} strong/>
              {payment !== 'transfer' && (
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 8 }}>
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12 }}>
                    <span style={{ background: '#0f8a5b', color: '#fff', fontSize: 10, fontWeight: 800, letterSpacing: '0.04em', padding: '3px 6px', borderRadius: 4 }}>15% OFF</span>
                    <span style={{ color: 'var(--ink-3)' }}>🔥 Abonando en 1 pago</span>
                  </span>
                  <span style={{ fontSize: 14, fontWeight: 700, color: '#0f8a5b' }}>$ {Math.round(totals.total * 0.85).toLocaleString('es-AR')}</span>
                </div>
              )}
              {payment === 'credit' && installments > 1 && (
                <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 6, textAlign: 'right' }}>
                  o {installments} cuotas sin interés de $ {Math.round(totals.total/installments).toLocaleString('es-AR')}
                </div>
              )}
            </div>
          </CkCard>

          {/* Forma de pago — moved here from left column (replaces cross-sell) */}
          <CkCard>
            <SectionTitle title="Forma de pago" icon="credit"/>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {MOCK_PAYMENT_METHODS.map((opt) => (
                <RadioOption key={opt.id} checked={payment === opt.id} onClick={() => setPayment(opt.id)}
                  title={opt.title} subtitle={opt.subtitle} badge={opt.badge} accent={opt.accent}/>
              ))}
            </div>

            {/* Conditional payment forms */}
            {payment === 'credit' && (
              <div style={{ marginTop: 14, padding: 16, background: 'var(--bg-2)', borderRadius: 10 }}>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: 10 }}>
                  <Field label="Número de tarjeta" required span={12}>
                    <Input placeholder="•••• •••• •••• ••••" icon="credit"/>
                  </Field>
                  <Field label="Nombre como figura" required span={8}><Input placeholder="JUAN PEREZ"/></Field>
                  <Field label="Venc." required span={2}><Input placeholder="MM/AA"/></Field>
                  <Field label="CVV" required span={2}><Input placeholder="•••"/></Field>
                </div>
                <div style={{ marginTop: 12 }}>
                  <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--ink-2)', marginBottom: 6 }}>Cuotas sin interés</div>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6 }}>
                    {[1, 3, 6, 12].map((n) => (
                      <button key={n} onClick={() => setInstallments(n)} style={{
                        padding: '10px 4px', textAlign: 'center',
                        border: '1.5px solid ' + (installments === n ? '#a00e0c' : 'var(--line-2)'),
                        background: installments === n ? '#FFF5F4' : '#fff',
                        borderRadius: 8,
                      }}>
                        <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink)' }}>{n}×</div>
                        <div style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 1 }}>
                          $ {Math.round(totals.total/n).toLocaleString('es-AR')}
                        </div>
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            )}
            {payment === 'transfer' && (
              <div style={{ marginTop: 12, padding: '14px 16px', background: '#FFF5F4', border: '1px solid #F0D0CE', borderRadius: 10, display: 'flex', gap: 12 }}>
                <div style={{ color: '#a00e0c', flexShrink: 0 }}><Icon name="bank" size={20}/></div>
                <div style={{ fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.5 }}>
                  Al confirmar te enviamos por email <strong>CBU, alias y monto</strong> con el <strong>15% OFF aplicado</strong>. Tenés 48 hs para transferir.
                </div>
              </div>
            )}
            {payment === 'mp' && (
              <div style={{ marginTop: 12, padding: '14px 16px', background: 'var(--bg-2)', borderRadius: 10, fontSize: 12, color: 'var(--ink-3)' }}>
                Al confirmar te redirigimos a Mercado Pago.
              </div>
            )}
          </CkCard>
        </div>
      </div>
    </div>
  );
}

window.CheckoutV1 = CheckoutV1;
