/* ───────────────────────────────────────────────────────────────────────
   V3 — Mobile conversational checkout (uses the site's main HeaderBar).
   Accordion sections in order:
     1) ¿Quién hace la compra?
     2) Datos de facturación (CF/RI + dirección + método de envío)
     3) Confirmá tu pedido (items editables + cupón + totales)
     4) ¿Cómo querés pagar?
   ─────────────────────────────────────────────────────────────────────── */

function CheckoutV3({ onSuccess, onNavigate, cart: cartProp, updateCart, removeCart }) {
  const [open, setOpen] = React.useState('contact');
  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 [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 SECTIONS = [
    { k: 'contact',  n: 1, t: '¿Quién hace la compra?',  sub: 'Datos para contactarte',         icon: 'user',
      summary: () => 'Juan Pérez · juan@email.com' },
    { k: 'billing',  n: 2, t: 'Datos de facturación',    sub: 'CF/RI + dirección + envío',      icon: 'award',
      summary: () => `${billing === 'cf' ? 'Consumidor final' : 'Responsable inscripto'} · ${shipObj.title}` },
    { k: 'review',   n: 3, t: 'Confirmá tu pedido',       sub: 'Revisá los productos y totales', icon: 'check',
      summary: () => `${cart.length} productos · $ ${totals.total.toLocaleString('es-AR')}` },
    { k: 'payment',  n: 4, t: '¿Cómo querés pagar?',      sub: 'Con descuento, en cuotas o MP',  icon: 'credit',
      summary: () => MOCK_PAYMENT_METHODS.find(p => p.id === payment).title },
  ];

  const COMPLETED = (k) => {
    const order = SECTIONS.map(s => s.k);
    const ix = order.indexOf(open);
    return order.indexOf(k) < ix;
  };

  const Section = ({ s, children }) => {
    const isOpen = open === s.k;
    const done = COMPLETED(s.k);
    return (
      <div style={{
        background: 'var(--surface)',
        border: '1px solid ' + (isOpen ? 'var(--ink)' : 'var(--line)'),
        borderRadius: 'var(--r-lg)',
        overflow: 'hidden',
        transition: 'border-color .2s',
      }}>
        <button onClick={() => setOpen(isOpen ? null : s.k)} style={{
          width: '100%', textAlign: 'left',
          padding: '16px 16px',
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <div style={{
            width: 32, height: 32, borderRadius: 16,
            background: done ? '#0f8a5b' : isOpen ? 'var(--ink)' : 'var(--bg-2)',
            color: (done || isOpen) ? '#fff' : 'var(--ink-3)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 13, fontWeight: 800, flexShrink: 0,
          }}>{done ? <Icon name="check" size={15}/> : s.n}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 14, fontWeight: 700, letterSpacing: '-0.01em', color: 'var(--ink)', lineHeight: 1.25 }}>{s.t}</div>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {done ? s.summary() : s.sub}
            </div>
          </div>
          {done && !isOpen && (
            <span style={{ fontSize: 12, color: 'var(--ink-3)', fontWeight: 600, textDecoration: 'underline' }}>Editar</span>
          )}
          {!done && !isOpen && (
            <Icon name="chevronDown" size={18} className=""/>
          )}
        </button>
        {isOpen && (
          <div style={{ padding: '4px 16px 18px', borderTop: '1px solid var(--line)' }}>
            <div style={{ paddingTop: 16 }}>
              {children}
            </div>
          </div>
        )}
      </div>
    );
  };

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

      {/* Sticky cart — always visible, expand to edit */}
      <CartSticky cart={cart} totals={totals} shipObj={shipObj}
        updateQty={updateQty} removeItem={removeItem} onNavigate={onNavigate}/>

      {/* Title strip — replaces the previous dark hero */}
      <div style={{ padding: '16px 14px 8px' }}>
        <div className="eyebrow" style={{ color: 'var(--ink-3)', fontSize: 10 }}><span className="dot" style={{ background: '#a00e0c' }}/>FALTA POCO</div>
        <h1 style={{ fontSize: 22, fontWeight: 800, letterSpacing: '-0.025em', margin: '6px 0 0', lineHeight: 1.15 }}>
          Finalizá tu compra
        </h1>
      </div>

      {/* Sections */}
      <div style={{ padding: '12px 14px 32px', display: 'flex', flexDirection: 'column', gap: 10 }}>

        {/* 1. CONTACT */}
        <Section s={SECTIONS[0]}>
          <div style={{ display: 'flex', gap: 4, padding: 4, background: 'var(--bg-2)', borderRadius: 10, marginBottom: 16 }}>
            {[
              { id: 'guest', label: 'Soy nuevo' },
              { 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',
              }}>{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>
          ) : (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: 12 }}>
              <Field label="Nombre" required span={6}><Input placeholder="Juan"/></Field>
              <Field label="Apellido" required span={6}><Input placeholder="Pérez"/></Field>
              <Field label="Email" required hint="Te enviamos la confirmación acá" span={12}><Input type="email" placeholder="tu@email.com" icon="mail"/></Field>
              <Field label="WhatsApp" required hint="Por si necesitamos coordinar" span={12}><Input type="tel" placeholder="11 5555 5555" icon="phone"/></Field>
            </div>
          )}

          <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 18 }}>
            <button onClick={() => setOpen('billing')} className="btn btn-primary" style={{ padding: '12px 22px', fontSize: 14, fontWeight: 700 }}>
              Continuar <Icon name="arrowRight" size={14}/>
            </button>
          </div>
        </Section>

        {/* 2. BILLING (factura + dirección + envío) */}
        <Section s={SECTIONS[1]}>
          {/* Tipo de factura */}
          <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink-2)', marginBottom: 8, letterSpacing: '-0.005em' }}>Tipo de factura</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 16 }}>
            {[
              { id: 'cf', label: 'Consumidor final', sub: 'Factura B' },
              { id: 'ri', label: 'Responsable inscripto', sub: 'Factura A' },
            ].map((o) => (
              <button key={o.id} onClick={() => setBilling(o.id)} style={{
                textAlign: 'left', padding: '12px 14px',
                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 }}>{o.label}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>{o.sub}</div>
              </button>
            ))}
          </div>

          {billing === 'cf' && (
            <div style={{ marginBottom: 16 }}>
              <Field label="DNI del titular" required><Input placeholder="34.555.666"/></Field>
            </div>
          )}
          {billing === 'ri' && (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: 12, marginBottom: 16 }}>
              <Field label="Razón social" required span={12}><Input placeholder="Mi Empresa SRL"/></Field>
              <Field label="CUIT" required span={12}><Input placeholder="30-12345678-9"/></Field>
            </div>
          )}

          {/* Dirección */}
          <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink-2)', marginBottom: 8, letterSpacing: '-0.005em' }}>Dirección</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: 12, marginBottom: 18 }}>
            <Field label="CP" required span={4}><Input defaultValue="1706" icon="pin"/></Field>
            <Field label="Localidad" required span={8}><Input defaultValue="Caballito"/></Field>
            <Field label="Calle" required span={8}><Input placeholder="Av. Rivadavia"/></Field>
            <Field label="Número" required span={4}><Input placeholder="1234"/></Field>
            <Field label="Piso / Depto (opcional)" span={12}><Input placeholder="3°B"/></Field>
          </div>

          {/* Método de envío */}
          <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink-2)', marginBottom: 8, letterSpacing: '-0.005em' }}>Método de envío</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {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>
          {shipping === 'pickup' && (
            <div style={{ marginTop: 12, padding: '12px 14px', background: 'var(--bg-2)', borderRadius: 10, display: 'flex', gap: 10 }}>
              <div style={{ color: '#a00e0c', flexShrink: 0 }}><Icon name="store" size={18}/></div>
              <div style={{ fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.5 }}>
                Sucursal Haedo · Tres Arroyos 456 · Lun a Vie 9–18 hs.
              </div>
            </div>
          )}

          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 18 }}>
            <button onClick={() => setOpen('contact')} className="btn btn-ghost" style={{ padding: '12px 18px', fontSize: 13 }}>← Volver</button>
            <button onClick={() => setOpen('review')} className="btn btn-primary" style={{ padding: '12px 22px', fontSize: 14, fontWeight: 700 }}>
              Continuar <Icon name="arrowRight" size={14}/>
            </button>
          </div>
        </Section>

        {/* 3. REVIEW — editable cart */}
        <Section s={SECTIONS[2]}>
          <div style={{ borderTop: '1px solid var(--line)' }}>
            {cart.map((it, i) => <SummaryItem key={i} {...it}
              onChangeQty={(delta) => updateQty(i, delta)}
              onRemove={() => removeItem(i)}/>)}
          </div>
          {cart.length === 0 && (
            <div style={{ padding: '24px 0', textAlign: 'center', color: 'var(--ink-3)', fontSize: 13 }}>
              No hay productos en el carrito.
              <button onClick={() => onNavigate && onNavigate('/')} style={{ display: 'block', margin: '12px auto 0', fontSize: 13, fontWeight: 700, color: '#a00e0c', textDecoration: 'underline' }}>
                Seguir comprando
              </button>
            </div>
          )}

          {cart.length > 0 && (
            <>
              <div style={{ marginTop: 18 }}>
                <CouponBox applied={coupon} onApply={(c) => setCoupon(c)} onRemove={() => setCoupon(null)}/>
              </div>

              <div style={{ marginTop: 18, padding: '14px 16px', background: 'var(--bg-2)', borderRadius: 10, display: 'flex', flexDirection: 'column', gap: 10 }}>
                <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 transferencia (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 style={{ height: 1, background: 'var(--line)', margin: '4px 0' }}/>
                <SummaryRow label="Total" value={'$ ' + totals.total.toLocaleString('es-AR')} strong/>
              </div>
            </>
          )}

          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 18 }}>
            <button onClick={() => setOpen('billing')} className="btn btn-ghost" style={{ padding: '12px 18px', fontSize: 13 }}>← Volver</button>
            <button onClick={() => setOpen('payment')} disabled={cart.length === 0}
              className="btn btn-primary" style={{ padding: '12px 22px', fontSize: 14, fontWeight: 700, opacity: cart.length === 0 ? 0.5 : 1 }}>
              Continuar al pago <Icon name="arrowRight" size={14}/>
            </button>
          </div>
        </Section>

        {/* 4. PAYMENT */}
        <Section s={SECTIONS[3]}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {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>

          {payment === 'transfer' && (
            <div style={{ marginTop: 14, 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 }}>
                Te enviamos por mail <strong>CBU/alias y monto con 15% OFF aplicado</strong>. Tenés 48 hs para transferir.
              </div>
            </div>
          )}
          {payment === 'credit' && (
            <div style={{ marginTop: 14, padding: '14px 16px', background: '#E9F6EF', border: '1px solid #B8E0CA', borderRadius: 10, fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.5 }}>
              <strong>Hasta 12 cuotas sin interés</strong> con todas las tarjetas. Completás los datos en el siguiente paso.
            </div>
          )}
          {payment === 'mp' && (
            <div style={{ marginTop: 14, padding: '12px 14px', background: 'var(--bg-2)', borderRadius: 10, fontSize: 12, color: 'var(--ink-3)' }}>
              Te redirigimos a Mercado Pago para completar el pago.
            </div>
          )}

          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 16 }}>
            <input type="checkbox" defaultChecked id="cv3-terms" style={{ accentColor: '#a00e0c' }}/>
            <label htmlFor="cv3-terms" style={{ fontSize: 11, color: 'var(--ink-3)' }}>
              Acepto los <a href="#" style={{ textDecoration: 'underline', color: 'var(--ink-2)' }}>Términos</a> y la <a href="#" style={{ textDecoration: 'underline', color: 'var(--ink-2)' }}>Política de privacidad</a>.
            </label>
          </div>

          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 14, gap: 10 }}>
            <button onClick={() => setOpen('review')} className="btn btn-ghost" style={{ padding: '12px 18px', fontSize: 13 }}>← Volver</button>
            <button onClick={onSuccess} className="btn btn-primary" style={{ padding: '14px 18px', fontSize: 14, fontWeight: 700, flex: 1 }}>
              Pagar · $ {totals.total.toLocaleString('es-AR')} <Icon name="check" size={14}/>
            </button>
          </div>
        </Section>

      </div>
    </div>
  );
}

/* Sticky cart at the top — collapsed shows item-count + total;
   expanded shows items with +/−/Quitar. */
function CartSticky({ cart, totals, shipObj, updateQty, removeItem, onNavigate }) {
  const [expanded, setExpanded] = React.useState(false);
  const [headerH, setHeaderH] = React.useState(0);

  React.useEffect(() => {
    const measure = () => {
      // Find the site's sticky header so this bar sits right below it.
      const hdr = document.querySelector('header');
      if (hdr) {
        const rect = hdr.getBoundingClientRect();
        // header is sticky top:0, so when visible its top is 0
        setHeaderH(rect.height);
      }
    };
    measure();
    window.addEventListener('resize', measure);
    return () => window.removeEventListener('resize', measure);
  }, []);

  const count = cart.reduce((s, i) => s + i.qty, 0);
  return (
    <div style={{
      position: 'sticky', top: headerH, zIndex: 20,
      background: 'var(--surface)',
      borderBottom: '1px solid var(--line)',
      boxShadow: expanded ? '0 6px 24px rgba(0,0,0,0.08)' : 'none',
      transition: 'box-shadow .2s',
    }}>
      <button onClick={() => setExpanded(!expanded)} style={{
        width: '100%', display: 'flex', alignItems: 'center', gap: 12,
        padding: '12px 14px', textAlign: 'left',
      }}>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          {cart.slice(0, 3).map((it, i) => (
            <div key={i} style={{
              width: 34, height: 34, borderRadius: 17, background: '#fff',
              border: '2px solid var(--bg-2)', marginLeft: i > 0 ? -10 : 0,
              display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden', position: 'relative',
            }}>
              {it.img ? <img src={it.img} alt="" style={{ width: '100%', height: '100%', objectFit: 'contain', padding: 2 }}/> : <Icon name="package" size={14}/>}
              <span style={{
                position: 'absolute', top: -4, right: -4, minWidth: 16, height: 16,
                padding: '0 4px', borderRadius: 8, background: 'var(--ink)', color: '#fff',
                fontSize: 9, fontWeight: 800,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>{it.qty}</span>
            </div>
          ))}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{count} {count === 1 ? 'producto' : 'productos'} en el carrito</div>
          <div style={{ fontSize: 15, fontWeight: 800, letterSpacing: '-0.01em', color: 'var(--ink)' }}>Total $ {totals.total.toLocaleString('es-AR')}</div>
        </div>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 12, fontWeight: 600, color: 'var(--ink-3)' }}>
          {expanded ? 'Ocultar' : 'Ver'}
          <div style={{ transform: expanded ? 'rotate(180deg)' : 'none', transition: 'transform .2s', display: 'inline-flex' }}>
            <Icon name="chevronDown" size={14}/>
          </div>
        </div>
      </button>

      {expanded && (
        <div style={{ borderTop: '1px solid var(--line)', padding: '4px 14px 14px', maxHeight: '52vh', overflowY: 'auto' }}>
          {cart.length === 0 ? (
            <div style={{ padding: '18px 0', textAlign: 'center', color: 'var(--ink-3)', fontSize: 13 }}>
              No hay productos en el carrito.
              <button onClick={() => onNavigate && onNavigate('/')} style={{ display: 'block', margin: '10px auto 0', fontSize: 13, fontWeight: 700, color: '#a00e0c', textDecoration: 'underline' }}>
                Seguir comprando
              </button>
            </div>
          ) : (
            <>
              <div>
                {cart.map((it, i) => <SummaryItem key={i} {...it}
                  onChangeQty={(delta) => updateQty(i, delta)}
                  onRemove={() => removeItem(i)}/>)}
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginTop: 12 }}>
                <SummaryRow label="Subtotal" value={'$ ' + cart.reduce((s, i) => s + i.price * i.qty, 0).toLocaleString('es-AR')}/>
                <SummaryRow label="Descuentos" value={'− $ ' + (totals.productDiscount + totals.paymentDiscount + 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>
              <button onClick={() => setExpanded(false)} className="btn btn-ghost" style={{ width: '100%', marginTop: 12, padding: '10px', fontSize: 13 }}>
                Listo, ocultar
              </button>
            </>
          )}
        </div>
      )}
    </div>
  );
}

window.CheckoutV3 = CheckoutV3;