/* ───────────────────────────────────────────────────────────────────────
   Checkout — shared primitives, inputs, summary, trust, cross-sell.
   Used by V1 (one-page), V2 (multi-step), V3 (accordion).
   ─────────────────────────────────────────────────────────────────────── */

// ── Mini header common to all 3 variants ─────────────────────────────────
function CheckoutHeader({ onNavigate }) {
  const go = (e) => { e.preventDefault(); onNavigate && onNavigate('/'); };
  return (
    <div style={{ background: 'var(--surface)', borderBottom: '1px solid var(--line)' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 28px' }}>
        <a href="/" onClick={go} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <img src="public/logo.png" alt="RC Powerclean" style={{ height: 30 }}/>
        </a>
        <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: 'var(--ink-3)', fontSize: 12, fontWeight: 600 }}>
            <Icon name="shield" size={14}/> COMPRA 100% SEGURA
          </div>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: 'var(--ink-3)', fontSize: 12 }}>
            <Icon name="phone" size={13}/> 11-2518-1264
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Form Input ───────────────────────────────────────────────────────────
function Field({ label, hint, error, required, children, span = 12 }) {
  return (
    <div style={{ gridColumn: `span ${span}`, display: 'flex', flexDirection: 'column', gap: 6 }}>
      <label style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-2)', letterSpacing: '-0.005em' }}>
        {label}{required && <span style={{ color: '#a00e0c', marginLeft: 4 }}>*</span>}
      </label>
      {children}
      {hint && !error && <span style={{ fontSize: 11, color: 'var(--ink-4)' }}>{hint}</span>}
      {error && <span style={{ fontSize: 11, color: '#a00e0c' }}>{error}</span>}
    </div>
  );
}

function Input({ placeholder, value, defaultValue, type = 'text', icon, suffix, readOnly }) {
  return (
    <div style={{ position: 'relative', display: 'flex', alignItems: 'center' }}>
      {icon && <div style={{ position: 'absolute', left: 12, color: 'var(--ink-4)', display: 'flex' }}>
        <Icon name={icon} size={15}/>
      </div>}
      <input
        type={type}
        placeholder={placeholder}
        defaultValue={defaultValue}
        value={value}
        readOnly={readOnly}
        style={{
          width: '100%',
          padding: icon ? '12px 14px 12px 36px' : '12px 14px',
          fontSize: 14, fontFamily: 'inherit',
          background: 'var(--surface)',
          border: '1px solid var(--line-2)',
          borderRadius: 8,
          color: 'var(--ink)',
          outline: 'none',
        }}
        onFocus={(e) => e.target.style.borderColor = 'var(--ink)'}
        onBlur={(e) => e.target.style.borderColor = 'var(--line-2)'}
      />
      {suffix && <div style={{ position: 'absolute', right: 12, fontSize: 12, fontWeight: 600, color: 'var(--ink-4)' }}>{suffix}</div>}
    </div>
  );
}

// ── Section Card ─────────────────────────────────────────────────────────
function CkCard({ children, style = {}, padded = true }) {
  return (
    <div style={{
      background: 'var(--surface)',
      border: '1px solid var(--line)',
      borderRadius: 'var(--r-lg)',
      padding: padded ? '24px 26px' : 0,
      ...style,
    }}>
      {children}
    </div>
  );
}

function SectionTitle({ n, title, subtitle, done, icon }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14, marginBottom: subtitle ? 16 : 18 }}>
      {n && (
        <div style={{
          width: 30, height: 30, borderRadius: 15,
          background: done ? '#0f8a5b' : 'var(--ink)',
          color: '#fff', fontSize: 13, fontWeight: 700,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
        }}>{done ? <Icon name="check" size={15}/> : n}</div>
      )}
      {icon && !n && (
        <div style={{
          width: 30, height: 30, borderRadius: 8,
          background: 'var(--bg-2)', color: 'var(--ink)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
        }}><Icon name={icon} size={16}/></div>
      )}
      <div style={{ flex: 1, paddingTop: 2 }}>
        <h2 style={{ fontSize: 17, fontWeight: 700, letterSpacing: '-0.01em', margin: 0 }}>{title}</h2>
        {subtitle && <p style={{ fontSize: 13, color: 'var(--ink-3)', margin: '4px 0 0' }}>{subtitle}</p>}
      </div>
    </div>
  );
}

// ── Radio option (envío + pago) ──────────────────────────────────────────
function RadioOption({ checked, onClick, title, subtitle, price, badge, accent, right, locked }) {
  return (
    <button
      type="button"
      onClick={locked ? null : onClick}
      style={{
        width: '100%', textAlign: 'left',
        background: checked ? '#FFF5F4' : 'var(--surface)',
        border: '1.5px solid ' + (checked ? '#a00e0c' : 'var(--line)'),
        borderRadius: 10,
        padding: '14px 16px',
        cursor: locked ? 'not-allowed' : 'pointer',
        opacity: locked ? 0.55 : 1,
        display: 'flex', alignItems: 'center', gap: 14,
        transition: 'border-color .15s, background .15s',
      }}
    >
      <div style={{
        width: 18, height: 18, borderRadius: 9,
        border: '2px solid ' + (checked ? '#a00e0c' : 'var(--line-2)'),
        background: checked ? '#a00e0c' : '#fff',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>
        {checked && <div style={{ width: 7, height: 7, borderRadius: 4, background: '#fff' }}/>}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
          <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>{title}</span>
          {badge && <span style={{
            fontSize: 10, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase',
            padding: '3px 7px', borderRadius: 4,
            background: accent === 'green' ? '#0f8a5b' : '#a00e0c', color: '#fff',
          }}>{badge}</span>}
        </div>
        {subtitle && <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 3 }}>{subtitle}</div>}
      </div>
      {right ? right : (price !== undefined && (
        <div style={{ fontSize: 14, fontWeight: 700, color: price === 0 ? '#0f8a5b' : 'var(--ink)' }}>
          {price === 0 ? 'GRATIS' : price === null ? 'A cotizar' : '$ ' + price.toLocaleString('es-AR')}
        </div>
      ))}
    </button>
  );
}

// ── Order summary line ───────────────────────────────────────────────────
function SummaryRow({ label, value, strong, mono, color }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12 }}>
      <span style={{ fontSize: strong ? 15 : 13, color: color || 'var(--ink-3)', fontWeight: strong ? 600 : 400 }}>{label}</span>
      <span className={mono ? 'mono' : ''} style={{
        fontSize: strong ? 22 : 13, fontWeight: strong ? 800 : 600,
        color: color || 'var(--ink)',
        letterSpacing: strong ? '-0.02em' : 0,
      }}>{value}</span>
    </div>
  );
}

// ── Cart item row used in summary ────────────────────────────────────────
function SummaryItem({ name, brand, qty, price, img, image, onChangeQty, onRemove, compact }) {
  const imgSrc = img || image;
  const lineTotal = price * qty;
  return (
    <div style={{ display: 'flex', gap: 12, padding: compact ? '10px 0' : '14px 0', borderBottom: '1px solid var(--line)' }}>
      <div style={{
        width: compact ? 52 : 64, height: compact ? 52 : 64,
        background: '#fff', border: '1px solid var(--line)', borderRadius: 8,
        display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, position: 'relative',
        overflow: 'hidden',
      }}>
        {imgSrc ? <img src={imgSrc} alt="" style={{ width: '100%', height: '100%', objectFit: 'contain', padding: 4 }}/>
             : <Icon name="package" size={20}/>}
        <span style={{
          position: 'absolute', top: -6, right: -6, minWidth: 20, height: 20,
          padding: '0 5px', borderRadius: 10, background: 'var(--ink)', color: '#fff',
          fontSize: 11, fontWeight: 700,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>{qty}</span>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        {brand && <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-4)' }}>{brand}</div>}
        <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', lineHeight: 1.3, marginTop: 2,
          overflow: 'hidden', textOverflow: 'ellipsis', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
        }}>{name}</div>
        {!compact && onChangeQty && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 6 }}>
            <div style={{ display: 'inline-flex', alignItems: 'center', border: '1px solid var(--line-2)', borderRadius: 6 }}>
              <button onClick={() => onChangeQty(-1)} disabled={qty <= 1}
                style={{ padding: '2px 10px', fontSize: 14, color: qty <= 1 ? 'var(--ink-4)' : 'var(--ink-2)', cursor: qty <= 1 ? 'not-allowed' : 'pointer' }}>−</button>
              <span style={{ padding: '0 10px', fontSize: 12, fontWeight: 600, minWidth: 18, textAlign: 'center' }}>{qty}</span>
              <button onClick={() => onChangeQty(1)}
                style={{ padding: '2px 10px', fontSize: 14, color: 'var(--ink-2)', cursor: 'pointer' }}>+</button>
            </div>
            <button onClick={onRemove} style={{ fontSize: 11, color: 'var(--ink-4)', textDecoration: 'underline', textUnderlineOffset: 2, cursor: 'pointer' }}>Quitar</button>
          </div>
        )}
      </div>
      <div style={{ textAlign: 'right', flexShrink: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ink)' }}>$ {lineTotal.toLocaleString('es-AR')}</div>
        {qty > 1 && <div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 2 }}>$ {price.toLocaleString('es-AR')} c/u</div>}
      </div>
    </div>
  );
}

// ── Trust badges row ─────────────────────────────────────────────────────
function TrustBadges({ compact }) {
  const items = [
    { icon: 'shield',     t: 'Compra protegida',  d: 'Devolución 10 días'  },
    { icon: 'truck',      t: 'Envío gratis',      d: 'CABA y GBA en 48 hs' },
    { icon: 'rotate',     t: 'Garantía oficial',  d: '12 meses todos'      },
    { icon: 'whatsapp',   t: 'Asesoramiento',     d: 'Service propio Haedo'},
  ];
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: compact ? 'repeat(2, 1fr)' : 'repeat(4, 1fr)', gap: 10,
    }}>
      {items.map((it) => (
        <div key={it.t} style={{
          display: 'flex', alignItems: 'flex-start', gap: 10,
          padding: '12px 14px',
          background: 'var(--bg-2)', borderRadius: 8,
        }}>
          <div style={{ color: '#a00e0c', flexShrink: 0, paddingTop: 1 }}><Icon name={it.icon} size={18}/></div>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink)' }}>{it.t}</div>
            <div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 1 }}>{it.d}</div>
          </div>
        </div>
      ))}
    </div>
  );
}

// ── Coupon input ─────────────────────────────────────────────────────────
function CouponBox({ applied, onApply, onRemove }) {
  const [open, setOpen] = React.useState(!!applied);
  const [code, setCode] = React.useState(applied || '');
  if (applied) {
    return (
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12,
        padding: '12px 14px', background: '#E9F6EF',
        border: '1px solid #B8E0CA', borderRadius: 8,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <Icon name="check" size={16} className="" />
          <div>
            <div style={{ fontSize: 13, fontWeight: 700, color: '#0f6940' }}>Cupón <span className="mono">{applied}</span> aplicado</div>
            <div style={{ fontSize: 11, color: '#0f8a5b' }}>−5% adicional en este pedido</div>
          </div>
        </div>
        <button onClick={onRemove} style={{ fontSize: 12, color: 'var(--ink-3)', textDecoration: 'underline', textUnderlineOffset: 2 }}>Quitar</button>
      </div>
    );
  }
  if (!open) {
    return (
      <button onClick={() => setOpen(true)} style={{
        display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13, color: 'var(--ink-2)',
        fontWeight: 600, textDecoration: 'underline', textUnderlineOffset: 3,
      }}>
        <Icon name="tag" size={14}/> ¿Tenés un código de descuento?
      </button>
    );
  }
  return (
    <div style={{ display: 'flex', gap: 8 }}>
      <input
        value={code} onChange={(e) => setCode(e.target.value.toUpperCase())}
        placeholder="CÓDIGO"
        style={{
          flex: 1, padding: '11px 13px', fontSize: 13, fontFamily: 'monospace', letterSpacing: '0.05em',
          border: '1px solid var(--line-2)', borderRadius: 8, background: '#fff', textTransform: 'uppercase',
        }}
      />
      <button onClick={() => onApply(code || 'WELCOME5')} className="btn btn-dark" style={{ padding: '10px 18px', fontSize: 13 }}>
        Aplicar
      </button>
    </div>
  );
}

// ── Cross-sell strip ─────────────────────────────────────────────────────
function CrossSell({ items, onAdd }) {
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 10 }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--ink)' }}>Agregá a tu pedido</div>
        <div className="mono" style={{ fontSize: 10, color: 'var(--ink-4)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>Compran junto</div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
        {items.map((it) => (
          <div key={it.name} style={{
            display: 'flex', flexDirection: 'column', gap: 6,
            padding: 10, border: '1px solid var(--line)', borderRadius: 8, background: 'var(--surface)',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <div style={{ width: 38, height: 38, background: '#fff', border: '1px solid var(--line)', borderRadius: 6, flexShrink: 0,
                display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon name="package" size={16}/>
              </div>
              <div style={{ minWidth: 0, flex: 1 }}>
                <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink)', lineHeight: 1.3,
                  overflow: 'hidden', textOverflow: 'ellipsis', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
                }}>{it.name}</div>
              </div>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink)' }}>$ {it.price.toLocaleString('es-AR')}</div>
              <button onClick={() => onAdd && onAdd(it)} style={{
                fontSize: 11, fontWeight: 700, color: '#a00e0c',
                border: '1px solid #a00e0c', padding: '3px 9px', borderRadius: 5,
              }}>＋ Sumar</button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Mock data ────────────────────────────────────────────────────────────
const MOCK_CART = [
  {
    name: 'Hidrolavadora Powerclean LT590',
    brand: 'POWERCLEAN',
    qty: 1,
    price: 450840,
    listPrice: 530400,
    img: null,
  },
  {
    name: 'Manguera de alta presión 8m trenzada',
    brand: 'POWERCLEAN',
    qty: 2,
    price: 16900,
    img: null,
  },
];

const MOCK_CROSS_SELL = [
  { name: 'Detergente concentrado 5L', price: 12480 },
  { name: 'Boquilla turbo profesional', price: 18900 },
  { name: 'Adaptador hembra ¼"', price: 4350 },
];

const MOCK_PAYMENT_METHODS = [
  { id: 'transfer', icon: 'bank',       title: 'Transferencia bancaria', subtitle: 'CBU o alias · Confirmación en 24 hs hábiles', badge: '−15% OFF', accent: 'red' },
  { id: 'mp',       icon: 'wallet',     title: 'Mercado Pago',            subtitle: 'Dinero en cuenta, débito o crédito',         badge: null,  accent: null },
  { id: 'credit',   icon: 'credit',     title: 'Tarjeta de crédito',     subtitle: 'Visa, Master, Amex, Naranja · Hasta 12 cuotas sin interés', badge: '12 SIN INTERÉS', accent: 'green' },
  { id: 'debit',    icon: 'credit',     title: 'Tarjeta de débito',      subtitle: 'Débito inmediato Visa o Master',              badge: null,  accent: null },
];

const MOCK_SHIPPING = [
  { id: 'free',   icon: 'truck',  title: 'Envío gratis CABA / GBA',       subtitle: 'Llega entre el martes 26 y jueves 28', price: 0,    badge: 'EN 48 HS', accent: 'green' },
  { id: 'pickup', icon: 'store',  title: 'Retiro en sucursal Haedo',      subtitle: 'Tres Arroyos 456 · Lun a Vie 9 a 18 hs', price: 0,    badge: 'GRATIS',   accent: 'green' },
  { id: 'quote',  icon: 'box',    title: 'Transporte por volumen',         subtitle: 'Cotizamos con tu dirección — para envíos al interior', price: null, badge: null,  accent: null },
];

const MOCK_TOTALS = (cartSubtotal, shipping, paymentDiscountPct = 0, couponPct = 0) => {
  const productDiscount = 79560;
  const subtotal = cartSubtotal;
  const ship = shipping === null ? 0 : (shipping || 0);
  const paymentDiscount = Math.round((subtotal - productDiscount) * paymentDiscountPct / 100);
  const couponDiscount = Math.round((subtotal - productDiscount) * couponPct / 100);
  const total = subtotal - productDiscount - paymentDiscount - couponDiscount + ship;
  return { productDiscount, paymentDiscount, couponDiscount, ship, total };
};

// Expose to other Babel scripts
Object.assign(window, {
  CheckoutHeader, Field, Input, CkCard, SectionTitle, RadioOption,
  SummaryRow, SummaryItem, TrustBadges, CouponBox, CrossSell,
  MOCK_CART, MOCK_CROSS_SELL, MOCK_PAYMENT_METHODS, MOCK_SHIPPING, MOCK_TOTALS,
});
