// checkout.jsx — Checkout modal + Success page (preview).

const { useState: useStateC, useEffect: useEffectC } = React;

function CheckoutModal({ items, onClose, onComplete }) {
  const { t, lang, currency, price } = React.useContext(window.LangContext);
  const [email, setEmail] = useStateC('');
  const [name, setName] = useStateC('');
  const [step, setStep] = useStateC('cart'); // cart | pay | done
  const [error, setError] = useStateC('');

  const list = items || [];
  const n = list.length;
  const unitStr = price.display;
  const totalStr = window.formatMoney((price.amount || 0) * n, currency);
  const formatLabel = n > 1
    ? (lang === 'en' ? `${n} maps` : `${n} mapas`)
    : (window.PRINT_SIZES.find(s => s.id === (list[0]?.size || '30x40'))?.name || '');

  // Load Stripe
  useEffectC(() => {
    if (!window.Stripe) {
      const script = document.createElement('script');
      script.src = 'https://js.stripe.com/v3/';
      script.onload = () => console.log('✅ Stripe.js loaded');
      document.head.appendChild(script);
    }
  }, []);

  async function pay(e) {
    e.preventDefault();
    setError('');

    if (!name.trim() || !email.trim()) {
      setError(t('checkout.fillFields'));
      return;
    }

    setStep('pay');

    try {
      // The server renders the poster from the design at high resolution.
      const response = await fetch('/api/stripe/create-checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ items: list, email, name, lang, currency })
      });

      if (!response.ok) throw new Error('Failed to create checkout session');

      const { checkoutUrl } = await response.json();
      if (checkoutUrl) window.location.href = checkoutUrl;
    } catch (err) {
      console.error('❌ Checkout error:', err);
      setError(t('checkout.payError'));
      setStep('cart');
    }
  }

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Close">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
            <path d="M18 6L6 18M6 6l12 12"/>
          </svg>
        </button>

        {/* LEFT — FINAL PROOF (same component/layout as the exported file) */}
        <aside className="modal-side">
          <h2 className="modal-title">{t('checkout.finalTitle')}</h2>
          <p className="modal-sub">{t('checkout.finalNote')}</p>

          <div>
            <div className="summary-row">
              <span>{n > 1 ? formatLabel : t('checkout.mapPersonal')}</span>
              <span>{n > 1 ? `${n} × ${unitStr}` : unitStr}</span>
            </div>
            <div className="summary-row">
              <span>{t('checkout.fileIncluded')}</span><span>{t('checkout.included')}</span>
            </div>
            <div className="summary-row total">
              <span>{t('checkout.total')}</span><span>{totalStr}</span>
            </div>
          </div>

          <div style={{ fontSize: 11, color: 'var(--muted)', lineHeight: 1.6 }}>
            {t('checkout.digitalNote')}
          </div>
        </aside>

        {/* RIGHT — format + delivery form */}
        <main className="modal-main">
          <div className="checkout-format-chip">
            <span>{n > 1 ? (lang === 'en' ? 'Order' : 'Pedido') : (lang === 'en' ? 'Format' : 'Formato')}</span>
            <b>{formatLabel}</b>
          </div>

          <form onSubmit={pay} style={{ marginTop: 8, display: 'flex', flexDirection: 'column', gap: 14 }}>
            <h3 style={{ fontFamily: 'var(--serif)', fontSize: 18, fontWeight: 500, margin: 0 }}>
              {t('checkout.fileSend')}
            </h3>

            <div className="field">
              <label className="field-label">{t('checkout.name')}</label>
              <input
                type="text" required
                className="input" placeholder={t('checkout.namePlaceholder')}
                value={name} onChange={e => setName(e.target.value)}
                disabled={step === 'pay'}
              />
            </div>

            <div className="field">
              <label className="field-label">{t('checkout.email')}</label>
              <input
                type="email" required
                className="input" placeholder={t('checkout.emailPlaceholder')}
                value={email} onChange={e => setEmail(e.target.value)}
                disabled={step === 'pay'}
              />
            </div>

            {error && (
              <div style={{ background: '#fee2e2', color: '#dc2626', padding: 12, borderRadius: 'var(--radius)', fontSize: 13 }}>
                {error}
              </div>
            )}

            <h3 style={{ fontFamily: 'var(--serif)', fontSize: 18, fontWeight: 500, margin: '8px 0 0' }}>
              {t('checkout.securePay')}
            </h3>

            <p style={{ fontSize: 13, color: 'var(--muted)', margin: 0 }}>
              {t('checkout.redirect')}
            </p>

            <button type="submit" className="btn-buy" style={{ marginTop: 8 }} disabled={step === 'pay'}>
              {step === 'pay' ? t('checkout.processing') : `${t('checkout.pay')} ${totalStr}`}
            </button>

            <div style={{ fontSize: 11, color: 'var(--muted)', textAlign: 'center', display: 'flex', gap: 10, justifyContent: 'center', marginTop: 4 }}>
              <span>🔒 Stripe</span>
              <span>•</span>
              <span>{t('checkout.guarantee')}</span>
              <span>•</span>
              <span>{t('checkout.noWatermark')}</span>
            </div>
          </form>
        </main>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────
// SUCCESS PAGE (in-app preview; real post-payment page is served by the server)
// ─────────────────────────────────────────────────────────────────────────

function SuccessPage({ design, order, onAgain }) {
  const { t } = React.useContext(window.LangContext);
  const sizeMeta = (window.PRINT_SIZES || []).find(s => s.id === (order?.size || '30x40')) || window.PRINT_SIZES[1];
  return (
    <div className="success">
      <header className="nav">
        <div className="nav-brand">WIS<i>maps</i></div>
        <button className="nav-cta" onClick={onAgain}>{t('success.createAnother')}</button>
      </header>

      <div className="success-hero">
        <div>
          <div className="success-check">
            <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><path d="M20 6L9 17l-5-5"/></svg>
          </div>
          <h1 className="success-title">
            {t('success.title1')}<em>{t('success.titleEm')}</em>{t('success.title2')}
          </h1>
          <p className="success-text">
            {t('success.text')} <b>{sizeMeta.name}</b>.
          </p>

          <div className="success-email">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/>
              <polyline points="22,6 12,13 2,6"/>
            </svg>
            <div>
              <div>{t('success.sentTo')}</div>
              <b>{order?.email || 'you@email.com'}</b>
            </div>
          </div>

          <div style={{ background: 'var(--paper-warm)', border: '1px solid var(--line)', padding: 20, borderRadius: 'var(--radius)', maxWidth: 460, marginTop: 24 }}>
            <h4 style={{ fontFamily: 'var(--serif)', fontSize: 16, margin: '0 0 10px', fontWeight: 500 }}>
              {t('success.howTitle')}
            </h4>
            <ol style={{ margin: 0, paddingLeft: 18, fontSize: 13, color: 'var(--muted)', lineHeight: 1.7 }}>
              <li>{t('success.how1')}</li>
              <li>{t('success.how2')}</li>
              <li>{t('success.how3')} {sizeMeta.name}</li>
              <li>{t('success.how4')}</li>
            </ol>
          </div>
        </div>

        <div className="success-preview">
          <EmailPreview design={design} order={order} sizeMeta={sizeMeta} />
        </div>
      </div>
    </div>
  );
}

// Preview of the actual email the customer receives
function EmailPreview({ design, order, sizeMeta }) {
  const { t } = React.useContext(window.LangContext);
  return (
    <div className="email-preview">
      <div className="email-header">
        <div className="em-from">WISMAPS &lt;hola@wismaps.com&gt;</div>
        <div className="em-to">{order?.email || 'you@email.com'}</div>
        <div className="em-subject">{t('success.emailSubject')}</div>
      </div>
      <div className="email-body">
        <div className="email-brand">WIS<i>maps</i></div>

        <div className="email-greeting">{t('success.title1')}{t('success.titleEm')}{t('success.title2')}</div>

        <div className="email-text">
          {t('checkout.digitalNote')}
        </div>

        <div className="email-preview-img">
          <Poster design={{ ...design }} width={180} frameId="none" withWatermark={false} interactive={false} draggable={false} />
        </div>

        <a href="#" className="email-btn">{t('success.how1')}</a>

        <div className="email-attachments">
          <div className="email-attach-row">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
              <polyline points="14 2 14 8 20 8"/>
            </svg>
            <span><b style={{ color: 'var(--ink)' }}>wismaps-{order?.size || '30x40'}.pdf</b> · {sizeMeta.px} px · PDF</span>
          </div>
        </div>

        <div className="email-foot">
          {order?.email ? 'hola@wismaps.com' : 'hola@wismaps.com'}
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────
// CART — lists the maps added, lets you remove / add more / go to checkout
// ─────────────────────────────────────────────────────────────────────────
function CartModal({ items, onClose, onRemove, onAddMore, onCheckout }) {
  const { t, lang, currency, price } = React.useContext(window.LangContext);
  const n = (items || []).length;
  const totalStr = window.formatMoney((price.amount || 0) * n, currency);
  const sizeName = id => (window.PRINT_SIZES.find(s => s.id === (id || '30x40'))?.name) || id;
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="cart-modal" onClick={e => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Close">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M18 6L6 18M6 6l12 12"/></svg>
        </button>
        <h2 className="modal-title">{lang === 'en' ? 'Your cart' : 'Tu carrito'} {n > 0 ? `(${n})` : ''}</h2>

        {n === 0 ? (
          <p style={{ color: 'var(--muted)', margin: '16px 0 24px' }}>{lang === 'en' ? 'Your cart is empty.' : 'Tu carrito está vacío.'}</p>
        ) : (
          <div className="cart-items">
            {items.map((d, i) => (
              <div className="cart-item" key={i}>
                <div className="cart-item-info">
                  <b>{d.headline || 'Mapa'}</b>
                  <span>{sizeName(d.size)}{d.location ? ' · ' + d.location : ''}</span>
                </div>
                <span className="cart-item-price">{price.display}</span>
                <button className="cart-item-remove" onClick={() => onRemove(i)} aria-label={lang === 'en' ? 'Remove' : 'Quitar'}>
                  <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6"/></svg>
                </button>
              </div>
            ))}
          </div>
        )}

        <div className="cart-total">
          <span>{lang === 'en' ? 'Total' : 'Total'}</span><b>{totalStr}</b>
        </div>

        <div className="cart-actions">
          <button className="btn-ghost" onClick={onAddMore}>{lang === 'en' ? 'Add another map' : 'Añadir otro mapa'}</button>
          <button className="btn-buy" onClick={onCheckout} disabled={n === 0} style={n === 0 ? { opacity: 0.5 } : {}}>
            {(lang === 'en' ? 'Checkout' : 'Ir a pagar')} · {totalStr}
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CheckoutModal, SuccessPage, CartModal });
