// Creart Checkout — shared modal that asks for customer info, saves the
// order to local storage, and then opens WhatsApp with the full order details.
// Exposes: window.openCheckout(payload) -> Promise<order|null>
(() => {
  const { useState, useEffect, useRef } = React;
  const WA_DEFAULT = '+50431969913';

  // Mount point
  let mountEl = document.getElementById('__checkout-root');
  if (!mountEl) {
    mountEl = document.createElement('div');
    mountEl.id = '__checkout-root';
    document.body.appendChild(mountEl);
  }

  // External hooks for imperative open
  let resolver = null;
  let openExt = null;

  const L = {
    es: {
      title: 'CONFIRMÁ TU PEDIDO',
      title_cart: 'CONFIRMÁ EL CARRITO',
      sub: 'Necesitamos tus datos y dirección para que te llegue la pieza.',
      sub_cart: 'Revisá tu pedido completo y coordinamos el envío por WhatsApp.',
      step_info: 'TUS DATOS',
      step_review: 'REVISÁ',
      cart_items: 'TUS PIEZAS',
      cart_total: 'TOTAL',
      cart_units: 'UNIDADES',
      name: 'Nombre completo',
      name_ph: 'Ej: María López',
      phone: 'Teléfono / WhatsApp',
      phone_ph: 'Ej: 9876 5432',
      addr: 'Dirección (calle, # casa, colonia)',
      addr_ph: 'Ej: Calle Las Rosas, casa 24, Col. Trejo',
      city: 'Ciudad / Depto.',
      city_ph: 'Ej: San Pedro Sula',
      notes: 'Notas (opcional)',
      notes_ph: 'Detalles, referencia, hora preferida...',
      cancel: 'CANCELAR',
      back: '← ATRÁS',
      next: 'SIGUIENTE →',
      send: 'CONFIRMAR Y MANDAR A WHATSAPP',
      req: 'Requerido',
      summary: 'RESUMEN',
      order_no: 'Pedido',
      product: 'Producto',
      price: 'Precio',
      ship_to: 'Enviar a',
      legal: 'Al confirmar, guardamos tu pedido y abrimos WhatsApp con todos los detalles para coordinar el envío.',
      remember: 'Recordar mis datos en este dispositivo',
    },
    en: {
      title: 'CONFIRM YOUR ORDER',
      title_cart: 'CONFIRM YOUR CART',
      sub: 'We need your info and address so the piece reaches you.',
      sub_cart: 'Review your full order and we coordinate shipping via WhatsApp.',
      step_info: 'YOUR INFO',
      step_review: 'REVIEW',
      cart_items: 'YOUR PIECES',
      cart_total: 'TOTAL',
      cart_units: 'UNITS',
      name: 'Full name',
      name_ph: 'e.g. Maria Lopez',
      phone: 'Phone / WhatsApp',
      phone_ph: 'e.g. 9876 5432',
      addr: 'Address (street, # house, neighborhood)',
      addr_ph: 'e.g. Calle Las Rosas, house 24, Col. Trejo',
      city: 'City / State',
      city_ph: 'e.g. San Pedro Sula',
      notes: 'Notes (optional)',
      notes_ph: 'Details, reference, preferred time...',
      cancel: 'CANCEL',
      back: '← BACK',
      next: 'NEXT →',
      send: 'CONFIRM AND SEND TO WHATSAPP',
      req: 'Required',
      summary: 'SUMMARY',
      order_no: 'Order',
      product: 'Product',
      price: 'Price',
      ship_to: 'Ship to',
      legal: 'Confirming will save your order and open WhatsApp with all the details to coordinate shipping.',
      remember: 'Remember my info on this device',
    },
  };

  const Field = ({ label, required, children, error }) => (
    <label style={{ display: 'block', marginBottom: 14 }}>
      <div style={{
        fontFamily: 'var(--fdisp2)', fontSize: 11, letterSpacing: '0.08em',
        marginBottom: 6, color: 'var(--ink)',
        display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
      }}>
        <span>{label.toUpperCase()}{required && <span style={{ color: 'var(--red)' }}> *</span>}</span>
        {error && <span style={{ color: 'var(--red)', fontFamily: 'var(--fmono)', fontSize: 10 }}>{error}</span>}
      </div>
      {children}
    </label>
  );

  const baseInput = {
    width: '100%',
    background: 'var(--bg)',
    color: 'var(--ink)',
    border: '2.5px solid var(--ink)',
    padding: '11px 12px',
    fontFamily: 'var(--fbody)',
    fontSize: 14,
    outline: 'none',
    boxShadow: '3px 3px 0 var(--ink)',
  };

  const CheckoutModal = () => {
    const [open, setOpen] = useState(false);
    const [payload, setPayload] = useState(null);
    const [step, setStep] = useState(1);
    const [name, setName] = useState('');
    const [phone, setPhone] = useState('');
    const [addr, setAddr] = useState('');
    const [city, setCity] = useState('San Pedro Sula');
    const [notes, setNotes] = useState('');
    const [remember, setRemember] = useState(true);
    const [touched, setTouched] = useState({});
    const [sending, setSending] = useState(false);

    // Expose imperative opener
    openExt = (p) => {
      const saved = window.CreartOrders.getClient();
      setName(saved.name || '');
      setPhone(saved.phone || '');
      setAddr(saved.addr || '');
      setCity(saved.city || 'San Pedro Sula');
      setNotes('');
      setTouched({});
      setStep(1);
      setPayload(p);
      setOpen(true);
    };

    useEffect(() => {
      const onKey = (e) => { if (e.key === 'Escape' && open) cancel(); };
      document.addEventListener('keydown', onKey);
      if (open) document.body.style.overflow = 'hidden';
      else document.body.style.overflow = '';
      return () => {
        document.removeEventListener('keydown', onKey);
        document.body.style.overflow = '';
      };
    }, [open]);

    if (!open || !payload) return null;

    const lang = payload.lang || 'es';
    const t = L[lang];

    const validInfo = name.trim().length >= 2 && phone.trim().length >= 6 && addr.trim().length >= 4;

    const close = (orderResult) => {
      if (resolver) { resolver(orderResult); resolver = null; }
      setOpen(false);
      setPayload(null);
    };
    const cancel = () => close(null);

    const onNext = () => {
      setTouched({ name: true, phone: true, addr: true });
      if (validInfo) setStep(2);
    };

    const submit = async () => {
      if (!validInfo) { setStep(1); setTouched({ name: true, phone: true, addr: true }); return; }
      if (remember) {
        window.CreartOrders.setClient({ name: name.trim(), phone: phone.trim(), addr: addr.trim(), city: city.trim() });
      }

      // ── Subir diseño a Supabase Storage si es base64 ─────────────────────
      setSending(true);
      let designImageUrl = payload.designImage || null;
      let designName     = payload.designName  || null;

      if (
        payload.designImage &&
        payload.designImage.startsWith('data:') &&
        window.supabase &&
        window.CREART_CONFIG?.SUPABASE_URL &&
        !window.CREART_CONFIG.SUPABASE_URL.includes('TU_PROYECTO')
      ) {
        try {
          const cfg = window.CREART_CONFIG;
          if (!window.CreartDB) window.CreartDB = window.supabase.createClient(cfg.SUPABASE_URL, cfg.SUPABASE_ANON_KEY);
          const sbUp = window.CreartDB;
          const ext  = payload.designImage.split(';')[0].split('/')[1] || 'png';
          const tempId   = `upload-${Date.now()}-${Math.floor(Math.random() * 9999)}`;
          const fileName = `${tempId}/diseno.${ext}`;

          // Convertir base64 → Blob
          const fetchRes = await fetch(payload.designImage);
          const blob     = await fetchRes.blob();

          const { error: uploadError } = await sbUp.storage
            .from('designs')
            .upload(fileName, blob, { contentType: blob.type, upsert: false });

          if (!uploadError) {
            const { data: urlData } = sbUp.storage.from('designs').getPublicUrl(fileName);
            designImageUrl = urlData.publicUrl;
            designName     = payload.designName || `diseno.${ext}`;
          } else {
            console.warn('[Checkout] upload error, pedido se guarda sin imagen:', uploadError);
            designImageUrl = null;
            designName     = payload.designName || null;
          }
        } catch (uploadErr) {
          console.warn('[Checkout] fallo al subir, pedido se guarda sin imagen:', uploadErr);
          designImageUrl = null;
          designName     = payload.designName || null;
        }
      } else if (payload.designImage?.startsWith('data:')) {
        // Sin Supabase configurado o supabase.js no cargado → no guardar base64 en DB
        designImageUrl = null;
      }

      // Guardar en Supabase (no bloquea el flujo si falla)
      let order = null;
      try {
        const savedProduct = isCartMode
          ? {
              name:  `CARRITO · ${cartUnits} ${lang === 'es' ? (cartUnits !== 1 ? 'piezas' : 'pieza') : (cartUnits !== 1 ? 'pieces' : 'piece')}`,
              sku:   null,
              price: cartFmt(cartTotal),
              img:   null,
            }
          : payload.product || null;
        const savedOptions = isCartMode
          ? { cart: payload.cart.map(it => ({
                name:    it.product?.name  || null,
                sku:     it.product?.sku   || null,
                qty:     it.qty  || 1,
                price:   it.priceNum || 0,
                options: it.options || null,
              })) }
          : payload.options || null;
        order = await window.CreartOrders.add({
          customer:    { name: name.trim(), phone: phone.trim(), addr: addr.trim(), city: city.trim() },
          notes:       notes.trim() || null,
          product:     savedProduct,
          options:     savedOptions,
          designImage: designImageUrl,
          designName:  designName,
          source:      payload.source || 'web',
          lang,
        });
      } catch (addErr) {
        console.warn('[Checkout] no se pudo guardar en DB, continuando con WA:', addErr);
        // Generar ID local para el mensaje de WA
        order = { id: `WA-${Date.now().toString(36).toUpperCase()}` };
      }
      setSending(false);
      // Build WA message
      const lines = [];
      lines.push(lang === 'es' ? '¡Yo! Quiero hacer este pedido:' : 'Yo! I want this order:');
      lines.push('');
      lines.push(`#${order.id}`);

      if (isCartMode && payload.cart?.length) {
        // Modo carrito: lista todos los ítems
        payload.cart.forEach((it, i) => {
          const qty = it.qty || 1;
          const lineTotal = cartFmt((it.priceNum || 0) * qty);
          lines.push(`${i + 1}. ${it.product?.name || 'Item'} × ${qty} → ${lineTotal}`);
          if (it.product?.sku) lines.push(`   SKU: ${it.product.sku}`);
          if (it.options) {
            Object.entries(it.options).filter(([_, v]) => v).forEach(([k, v]) => {
              lines.push(`   ${k}: ${v}`);
            });
          }
        });
        lines.push('');
        lines.push(`${lang === 'es' ? 'TOTAL' : 'TOTAL'}: ${cartFmt(cartTotal)}`);
      } else {
        // Modo producto único
        if (payload.product?.name) lines.push(`${lang === 'es' ? 'Producto' : 'Product'}: ${payload.product.name}`);
        if (payload.product?.sku) lines.push(`SKU: ${payload.product.sku}`);
        if (payload.product?.price) lines.push(`${lang === 'es' ? 'Precio' : 'Price'}: ${payload.product.price}`);
        if (payload.options) {
          Object.entries(payload.options).forEach(([k, v]) => {
            if (v) lines.push(`${k}: ${v}`);
          });
        }
      }

      lines.push('');
      lines.push(lang === 'es' ? '— Cliente —' : '— Customer —');
      lines.push(name.trim());
      lines.push(phone.trim());
      lines.push(`${addr.trim()}, ${city.trim()}`);
      if (notes.trim()) lines.push(`${lang === 'es' ? 'Notas' : 'Notes'}: ${notes.trim()}`);
      if (payload.designImage) {
        lines.push('');
        lines.push(lang === 'es'
          ? '(Te paso el diseño por acá enseguida ↓)'
          : '(Sending the design here right after ↓)');
      }
      const msg = lines.join('\n');
      const wa = (payload.wa || WA_DEFAULT).replace(/\D/g, '');
      const waUrl = `https://wa.me/${wa}?text=${encodeURIComponent(msg)}`;
      // Open WA
      window.open(waUrl, '_blank', 'noopener');
      if (isCartMode && window.CreartCart) window.CreartCart.clear();
      close(order);
    };

    const sticker = (text, color, rot) => (
      <span style={{
        display: 'inline-block', background: color, color: 'var(--ink)',
        fontFamily: 'var(--fdisp2)', fontSize: 11, padding: '3px 9px',
        transform: `rotate(${rot})`, border: '2px solid var(--ink)',
        boxShadow: '2px 2px 0 var(--ink)', letterSpacing: '0.06em',
      }}>{text}</span>
    );

    const isCartMode = !!(payload.cart && payload.cart.length);
    const cartFmt = window.CreartCart ? window.CreartCart.fmt : (n) => 'L. ' + n;
    const cartTotal = isCartMode
      ? payload.cart.reduce((s, x) => s + (x.priceNum || 0) * (x.qty || 1), 0)
      : 0;
    const cartUnits = isCartMode
      ? payload.cart.reduce((s, x) => s + (x.qty || 1), 0)
      : 0;

    const renderProductBlurb = () => {
      if (isCartMode) {
        return (
          <div style={{ marginBottom: 12 }}>
            <div style={{
              fontFamily: 'var(--fdisp2)', fontSize: 11, letterSpacing: '0.08em',
              color: 'var(--muted)', marginBottom: 8,
            }}>{t.cart_items} ({cartUnits})</div>
            {payload.cart.map((it, i) => (
              <div key={it.id || i} style={{
                display: 'flex', gap: 10, alignItems: 'center',
                background: 'var(--bg)', border: '2px solid var(--ink)',
                padding: '8px 10px', marginBottom: 6,
              }}>
                {it.product?.img && (
                  <div style={{ width: 40, height: 40, flexShrink: 0, overflow: 'hidden', border: '1.5px solid var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#fff' }}>
                    <img src={it.product.img} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', mixBlendMode: 'multiply' }}/>
                  </div>
                )}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontFamily: 'var(--fdisp)', fontSize: 15, lineHeight: 1, textTransform: 'uppercase' }}>{it.product?.name}</div>
                  {it.product?.sku && <div style={{ fontFamily: 'var(--fmono)', fontSize: 9, color: 'var(--muted)', letterSpacing: '0.05em' }}>{it.product.sku}</div>}
                </div>
                <div style={{ fontFamily: 'var(--fmono)', fontSize: 11, fontWeight: 700, whiteSpace: 'nowrap' }}>× {it.qty || 1}</div>
                <div style={{ background: 'var(--ink)', color: 'var(--yellow)', fontFamily: 'var(--fdisp2)', fontSize: 11, padding: '3px 7px', whiteSpace: 'nowrap' }}>
                  {cartFmt((it.priceNum || 0) * (it.qty || 1))}
                </div>
              </div>
            ))}
            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, alignItems: 'center', marginTop: 4 }}>
              <span style={{ fontFamily: 'var(--fmono)', fontSize: 10, color: 'var(--muted)', letterSpacing: '0.08em' }}>{t.cart_total}</span>
              <span style={{ fontFamily: 'var(--fbowl)', fontSize: 18, background: 'var(--ink)', color: 'var(--yellow)', padding: '3px 10px' }}>{cartFmt(cartTotal)}</span>
            </div>
          </div>
        );
      }
      if (!payload.product) return null;
      return (
        <div style={{
          display: 'flex', gap: 12, alignItems: 'center',
          background: 'var(--bg)', border: '2.5px solid var(--ink)',
          padding: 10, marginBottom: 12,
        }}>
          {(payload.product.img || payload.designImage) && (
            <div style={{
              width: 60, height: 60, background: '#fff',
              border: '2px solid var(--ink)', overflow: 'hidden', flexShrink: 0,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <img src={payload.designImage || payload.product.img} alt=""
                style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
            </div>
          )}
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{
              fontFamily: 'var(--fdisp)', fontSize: 18, lineHeight: 1,
              textTransform: 'uppercase', marginBottom: 2,
            }}>{payload.product.name}</div>
            <div style={{ fontFamily: 'var(--fmono)', fontSize: 10, color: 'var(--muted)', letterSpacing: '0.05em' }}>
              {payload.product.sku ? `${payload.product.sku} · ` : ''}{payload.product.price}
            </div>
            {payload.options && (
              <div style={{ fontFamily: 'var(--fmono)', fontSize: 10, color: 'var(--ink2)', marginTop: 3 }}>
                {Object.entries(payload.options).filter(([_, v]) => v).map(([k, v]) => `${k}: ${v}`).join(' · ')}
              </div>
            )}
          </div>
        </div>
      );
    };

    return (
      <div onClick={cancel} style={{
        position: 'fixed', inset: 0, zIndex: 1000,
        background: 'rgba(15,15,15,0.78)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 16, animation: 'fadeIn 0.18s ease both',
      }}>
        <style>{`@keyframes fadeIn{from{opacity:0}to{opacity:1}} @keyframes coIn{from{opacity:0;transform:scale(.94) rotate(-0.8deg)}to{opacity:1;transform:scale(1) rotate(0)}}`}</style>
        <div onClick={e => e.stopPropagation()} style={{
          background: 'var(--paper)', border: '4px solid var(--ink)',
          boxShadow: '10px 10px 0 var(--red)',
          maxWidth: 560, width: '100%', maxHeight: '92vh', overflowY: 'auto',
          position: 'relative', animation: 'coIn 0.22s ease both',
        }}>
          {/* Tape strips */}
          <div style={{
            position: 'absolute', top: -9, left: 48, width: 110, height: 18,
            background: 'var(--yellow)', transform: 'rotate(-7deg)',
            boxShadow: '1px 1px 0 rgba(0,0,0,0.15)',
          }}/>
          <div style={{
            position: 'absolute', top: -8, right: 70, width: 80, height: 18,
            background: 'var(--red)', transform: 'rotate(9deg)',
            boxShadow: '1px 1px 0 rgba(0,0,0,0.15)',
          }}/>
          <button onClick={cancel} aria-label="cerrar" style={{
            position: 'absolute', top: 12, right: 12, zIndex: 5,
            background: 'var(--ink)', color: 'var(--bg)',
            width: 36, height: 36, fontFamily: 'var(--fbowl)', fontSize: 16,
            border: '2px solid var(--ink)', boxShadow: '3px 3px 0 var(--red)',
            cursor: 'pointer',
          }}>×</button>

          <div style={{ padding: '32px 28px 24px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
              <div style={{
                fontFamily: 'var(--fmono)', fontSize: 10, fontWeight: 700,
                background: 'var(--ink)', color: 'var(--yellow)',
                padding: '3px 8px', letterSpacing: '0.12em',
              }}>{step}/2 · {step === 1 ? t.step_info : t.step_review}</div>
              {isCartMode
                ? sticker(`${cartUnits} ${lang==='es'?'PIEZAS':'PIECES'}`, 'var(--yellow)', '-4deg')
                : sticker(`#${(payload.product?.sku || 'CUSTOM')}`, 'var(--yellow)', '-4deg')}
            </div>
            <h2 style={{
              fontFamily: 'var(--fdisp)', fontSize: 'clamp(28px, 5vw, 40px)',
              lineHeight: 0.95, textTransform: 'uppercase', marginTop: 8, marginBottom: 6,
            }}>{isCartMode ? t.title_cart : t.title}</h2>
            <p style={{ fontSize: 13, color: 'var(--muted)', marginBottom: 22 }}>{isCartMode ? t.sub_cart : t.sub}</p>

            {renderProductBlurb()}

            {step === 1 && (
              <div>
                <Field label={t.name} required error={touched.name && name.trim().length < 2 ? t.req : null}>
                  <input value={name} onChange={e => setName(e.target.value)} onBlur={() => setTouched(s => ({ ...s, name: true }))}
                    placeholder={t.name_ph} style={baseInput} />
                </Field>
                <Field label={t.phone} required error={touched.phone && phone.trim().length < 6 ? t.req : null}>
                  <input value={phone} onChange={e => setPhone(e.target.value)} onBlur={() => setTouched(s => ({ ...s, phone: true }))}
                    placeholder={t.phone_ph} style={baseInput} type="tel" />
                </Field>
                <Field label={t.addr} required error={touched.addr && addr.trim().length < 4 ? t.req : null}>
                  <textarea value={addr} onChange={e => setAddr(e.target.value)} onBlur={() => setTouched(s => ({ ...s, addr: true }))}
                    placeholder={t.addr_ph} rows={2} style={{ ...baseInput, resize: 'vertical', minHeight: 60 }} />
                </Field>
                <Field label={t.city}>
                  <input value={city} onChange={e => setCity(e.target.value)} placeholder={t.city_ph} style={baseInput} />
                </Field>
                <Field label={t.notes}>
                  <textarea value={notes} onChange={e => setNotes(e.target.value)} placeholder={t.notes_ph} rows={2}
                    style={{ ...baseInput, resize: 'vertical', minHeight: 50 }} />
                </Field>
                <label style={{
                  display: 'flex', alignItems: 'center', gap: 8, marginTop: 4, marginBottom: 18,
                  fontSize: 12, color: 'var(--ink2)',
                }}>
                  <input type="checkbox" checked={remember} onChange={e => setRemember(e.target.checked)}
                    style={{ width: 16, height: 16, accentColor: '#0f0f0f' }} />
                  {t.remember}
                </label>
              </div>
            )}

            {step === 2 && (
              <div style={{
                background: 'var(--bg)', border: '3px solid var(--ink)',
                padding: 16, marginBottom: 18, boxShadow: '4px 4px 0 var(--ink)',
              }}>
                <div style={{
                  fontFamily: 'var(--fdisp)', fontSize: 22, textTransform: 'uppercase',
                  marginBottom: 12, color: 'var(--red)', letterSpacing: '0.02em',
                }}>{t.summary}</div>

                {payload.designImage && (
                  <div style={{
                    background: '#fff', border: '2px solid var(--ink)',
                    padding: 8, marginBottom: 12, display: 'flex',
                    justifyContent: 'center', alignItems: 'center',
                  }}>
                    <img src={payload.designImage} alt="design" style={{
                      maxHeight: 140, maxWidth: '100%', objectFit: 'contain',
                    }} />
                  </div>
                )}

                <dl style={{ display: 'grid', gridTemplateColumns: 'auto 1fr', gap: '8px 14px', fontSize: 13 }}>
                  {payload.product?.name && (<>
                    <dt style={{ fontFamily: 'var(--fmono)', fontSize: 10, fontWeight: 700, letterSpacing: '0.08em', color: 'var(--muted)' }}>{t.product.toUpperCase()}</dt>
                    <dd>{payload.product.name}{payload.product.sku && <span style={{ color: 'var(--muted)', fontFamily: 'var(--fmono)', fontSize: 11 }}> · {payload.product.sku}</span>}</dd>
                  </>)}
                  {payload.options && Object.entries(payload.options).filter(([_, v]) => v).map(([k, v]) => (
                    <React.Fragment key={k}>
                      <dt style={{ fontFamily: 'var(--fmono)', fontSize: 10, fontWeight: 700, letterSpacing: '0.08em', color: 'var(--muted)' }}>{k.toUpperCase()}</dt>
                      <dd>{v}</dd>
                    </React.Fragment>
                  ))}
                  {payload.product?.price && (<>
                    <dt style={{ fontFamily: 'var(--fmono)', fontSize: 10, fontWeight: 700, letterSpacing: '0.08em', color: 'var(--muted)' }}>{t.price.toUpperCase()}</dt>
                    <dd style={{ fontFamily: 'var(--fdisp2)', fontSize: 14 }}>{payload.product.price}</dd>
                  </>)}
                  <dt style={{ fontFamily: 'var(--fmono)', fontSize: 10, fontWeight: 700, letterSpacing: '0.08em', color: 'var(--muted)' }}>{t.ship_to.toUpperCase()}</dt>
                  <dd style={{ lineHeight: 1.5 }}>
                    <b>{name}</b><br />
                    {phone}<br />
                    {addr}, {city}
                  </dd>
                  {notes && (<>
                    <dt style={{ fontFamily: 'var(--fmono)', fontSize: 10, fontWeight: 700, letterSpacing: '0.08em', color: 'var(--muted)' }}>{t.notes.toUpperCase()}</dt>
                    <dd style={{ fontStyle: 'italic', color: 'var(--ink2)' }}>{notes}</dd>
                  </>)}
                </dl>
                <p style={{ fontSize: 11, color: 'var(--muted)', marginTop: 14, lineHeight: 1.5 }}>{t.legal}</p>
              </div>
            )}

            <div style={{ display: 'flex', gap: 10, marginTop: 6, flexWrap: 'wrap' }}>
              <button onClick={step === 1 ? cancel : () => setStep(1)} style={{
                background: 'transparent', color: 'var(--ink)',
                border: '2.5px solid var(--ink)', padding: '12px 18px',
                fontFamily: 'var(--fdisp2)', fontSize: 12, letterSpacing: '0.06em',
                cursor: 'pointer', flex: '0 0 auto',
              }}>{step === 1 ? t.cancel : t.back}</button>
              {step === 1 ? (
                <button onClick={onNext} disabled={!validInfo && Object.keys(touched).length > 0}
                  style={{
                    background: 'var(--ink)', color: 'var(--yellow)',
                    border: '2.5px solid var(--ink)', padding: '12px 20px',
                    fontFamily: 'var(--fdisp2)', fontSize: 12, letterSpacing: '0.06em',
                    cursor: 'pointer', flex: 1, boxShadow: '4px 4px 0 var(--red)',
                  }}>{t.next}</button>
              ) : (
                <button onClick={submit} disabled={sending} style={{
                  background: sending ? 'var(--muted)' : 'var(--red)', color: 'var(--bg)',
                  border: '2.5px solid var(--ink)', padding: '12px 20px',
                  fontFamily: 'var(--fdisp2)', fontSize: 13, letterSpacing: '0.06em',
                  cursor: sending ? 'not-allowed' : 'pointer', flex: 1,
                  boxShadow: sending ? 'none' : '4px 4px 0 var(--ink)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                  opacity: sending ? 0.7 : 1,
                }}>
                  {sending ? (
                    <>
                      <span style={{ display: 'inline-block', animation: 'spin 0.8s linear infinite' }}>⟳</span>
                      {payload.designImage?.startsWith('data:')
                        ? (lang === 'es' ? 'SUBIENDO DISEÑO...' : 'UPLOADING DESIGN...')
                        : (lang === 'es' ? 'PROCESANDO...'      : 'PROCESSING...')}
                      <style>{`@keyframes spin{to{transform:rotate(360deg)}}`}</style>
                    </>
                  ) : (
                    <>
                      <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347z" />
                        <path d="M12.05 2C6.495 2 2 6.495 2 12.05c0 1.87.515 3.619 1.409 5.117L2 22l4.933-1.383A10.004 10.004 0 0012.05 22c5.555 0 10.05-4.495 10.05-10.05C22.1 6.495 17.605 2 12.05 2zm0 18.364a8.288 8.288 0 01-4.217-1.15l-.303-.179-3.127.877.841-3.064-.197-.315A8.264 8.264 0 013.636 12.05c0-4.636 3.778-8.414 8.414-8.414 4.636 0 8.414 3.778 8.414 8.414 0 4.636-3.778 8.314-8.414 8.314z" />
                      </svg>
                      {t.send}
                    </>
                  )}
                </button>
              )}
            </div>
          </div>
        </div>
      </div>
    );
  };

  ReactDOM.createRoot(mountEl).render(<CheckoutModal />);

  window.openCheckout = (payload) => new Promise((resolve) => {
    resolver = resolve;
    const tryOpen = () => {
      if (openExt) openExt(payload || {});
      else setTimeout(tryOpen, 20);
    };
    tryOpen();
  });
})();
