/* global React, SFIcons */
const { X, Trash, Truck: TruckC } = SFIcons;
const { Button: BtnC, QuantityStepper: QS, StockStatus: SS } = window.MADECIDesignSystem_419fb1;
const clp = (n) => '$' + Number(n).toLocaleString('es-CL');

function CartLine({ item, onQty, onRemove }) {
  return (
    <div style={{ display: 'flex', gap: 12, padding: '16px 0', borderBottom: '1px solid var(--border-subtle)' }}>
      <div style={{ width: 56, height: 56, flex: 'none', background: 'var(--neutral-50)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-sm)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="var(--neutral-300)" strokeWidth="1.4"><path d="M6 4h12l-1.2 15.2A2 2 0 0 1 14.8 21H9.2a2 2 0 0 1-2-1.8L6 4Z" /><path d="M6.4 9h11.2" /></svg>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14.5, color: 'var(--text-strong)', lineHeight: 1.15 }}>{item.name}</div>
        <div style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--text-muted)' }}>{item.brand} · {item.pack}</div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 8 }}>
          <QS value={item.qty} min={1} size="sm" onChange={(q) => onQty(item.id, q)} />
          <span style={{ fontFamily: 'var(--font-data)', fontWeight: 700, fontSize: 16, color: 'var(--text-strong)' }}>{clp(item.price * item.qty)}</span>
        </div>
      </div>
      <button onClick={() => onRemove(item.id)} aria-label="Quitar" style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-subtle)', padding: 0, height: 'fit-content' }}><Trash size={16} /></button>
    </div>
  );
}

function CartDrawer({ open, items, onClose, onQty, onRemove, onCheckout, onClear }) {
  const subtotal = items.reduce((s, i) => s + i.price * i.qty, 0);
  const min = 30000;
  const ok = subtotal >= min;
  const [confirmarVaciar, setConfirmarVaciar] = React.useState(false);
  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(17,19,21,.5)', opacity: open ? 1 : 0, pointerEvents: open ? 'auto' : 'none', transition: 'opacity .25s', zIndex: 50 }} />
      <div style={{ position: 'fixed', top: 0, right: 0, bottom: 0, width: 420, maxWidth: '92vw', background: 'var(--surface-card)', boxShadow: 'var(--shadow-lg)', zIndex: 51, transform: open ? 'none' : 'translateX(100%)', transition: 'transform .3s var(--ease-out)', display: 'flex', flexDirection: 'column' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '20px 22px', borderBottom: '1px solid var(--border-subtle)' }}>
          <h3 style={{ fontSize: 20, fontWeight: 700 }}>Tu pedido <span style={{ color: 'var(--text-muted)', fontWeight: 600 }}>({items.length})</span></h3>
          <button onClick={onClose} aria-label="Cerrar" style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-muted)' }}><X size={22} /></button>
        </div>
        <div style={{ flex: 1, overflowY: 'auto', padding: '0 22px' }}>
          {items.length === 0
            ? <div style={{ textAlign: 'center', padding: '64px 0', color: 'var(--text-muted)', fontFamily: 'var(--font-body)' }}>Tu carrito está vacío.</div>
            : (
              <React.Fragment>
                <div style={{ display: 'flex', justifyContent: 'flex-end', paddingTop: 12 }}>
                  {confirmarVaciar ? (
                    <span style={{ display: 'flex', alignItems: 'center', gap: 8, fontFamily: 'var(--font-body)', fontSize: 13 }}>
                      <span style={{ color: 'var(--text-muted)' }}>¿Vaciar todo?</span>
                      <button onClick={() => { onClear(); setConfirmarVaciar(false); }} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--madeci-red)', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 13 }}>Sí, vaciar</button>
                      <button onClick={() => setConfirmarVaciar(false)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-muted)', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 13 }}>No</button>
                    </span>
                  ) : (
                    <button onClick={() => setConfirmarVaciar(true)} style={{ display: 'flex', alignItems: 'center', gap: 6, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-muted)', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 12.5 }}>
                      <Trash size={14} /> Vaciar carrito
                    </button>
                  )}
                </div>
                {items.map((i) => <CartLine key={i.id} item={i} onQty={onQty} onRemove={onRemove} />)}
              </React.Fragment>
            )}
        </div>
        <div style={{ borderTop: '1px solid var(--border-subtle)', padding: 22, background: 'var(--neutral-25)' }}>
          {!ok && items.length > 0 && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, background: 'var(--status-warning-50)', color: 'var(--status-warning)', padding: '9px 12px', borderRadius: 'var(--radius-sm)', fontFamily: 'var(--font-body)', fontSize: 13, marginBottom: 14 }}>
              <TruckC size={16} /> Te faltan {clp(min - subtotal)} para el pedido mínimo.
            </div>
          )}
          <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'var(--font-display)', marginBottom: 4 }}>
            <span style={{ color: 'var(--text-muted)' }}>Subtotal</span>
            <span style={{ fontFamily: 'var(--font-data)', fontWeight: 700, fontSize: 22, color: 'var(--text-strong)' }}>{clp(subtotal)}</span>
          </div>
          <p style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--text-subtle)', margin: '0 0 14px' }}>IVA incluido · despacho calculado en el checkout</p>
          <BtnC block size="lg" disabled={!ok || items.length === 0} onClick={onCheckout}>Continuar al checkout</BtnC>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { CartDrawer });
