/* global React, firebase */
function CheckoutPage({ ea, go, onComplete, user }) {
  if (!ea) ea = window.EA_LIST[0];
  const [method, setMethod] = React.useState('usdt_trc20');
  const [step, setStep] = React.useState(1);
  const [processing, setProcessing] = React.useState(false);
  const [mt5Account, setMt5Account] = React.useState('');
  const [mt5Broker, setMt5Broker] = React.useState('');
  const [mt5Error, setMt5Error] = React.useState('');

  const licenseKey = React.useMemo(
    () => `EFF-${ea.id.toUpperCase()}-${Math.random().toString(36).slice(2, 6).toUpperCase()}-${Math.random().toString(36).slice(2, 6).toUpperCase()}-${Math.random().toString(36).slice(2, 6).toUpperCase()}-${Math.random().toString(36).slice(2, 6).toUpperCase()}`,
    [ea.id]
  );
  const orderId = React.useMemo(
    () => `ord_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`,
    [ea.id]
  );

  // ── Brand SVG icons ──────────────────────────────────────────────
  const ICONS = {
    usdt: (
      <svg viewBox="0 0 32 32" width="22" height="22"><circle cx="16" cy="16" r="16" fill="#26A17B"/><path fill="#fff" d="M17.9 17.5v-2h4.6v-3H9.5v3h4.6v2c-3.7.2-6.5 1-6.5 1.9 0 1 2.8 1.7 6.5 1.9v6.4h3.8v-6.4c3.7-.2 6.5-1 6.5-1.9 0-1-2.8-1.7-6.5-1.9zm0 3.2v0c-.1 0-1 .1-2 .1-.8 0-1.4 0-1.7-.1v0c-3.3-.1-5.7-.7-5.7-1.4s2.5-1.3 5.7-1.4v2.2c.3 0 .9.1 1.7.1 1 0 1.8 0 2-.1V18c3.2.1 5.7.7 5.7 1.4 0 .6-2.5 1.2-5.7 1.3z"/></svg>
    ),
    usdtBsc: (
      <svg viewBox="0 0 32 32" width="22" height="22"><circle cx="16" cy="16" r="16" fill="#F0B90B"/><path fill="#fff" d="M17.9 17.5v-2h4.6v-3H9.5v3h4.6v2c-3.7.2-6.5 1-6.5 1.9 0 1 2.8 1.7 6.5 1.9v6.4h3.8v-6.4c3.7-.2 6.5-1 6.5-1.9 0-1-2.8-1.7-6.5-1.9zm0 3.2v0c-.1 0-1 .1-2 .1-.8 0-1.4 0-1.7-.1v0c-3.3-.1-5.7-.7-5.7-1.4s2.5-1.3 5.7-1.4v2.2c.3 0 .9.1 1.7.1 1 0 1.8 0 2-.1V18c3.2.1 5.7.7 5.7 1.4 0 .6-2.5 1.2-5.7 1.3z"/></svg>
    ),
    btc: (
      <svg viewBox="0 0 32 32" width="22" height="22"><circle cx="16" cy="16" r="16" fill="#F7931A"/><path fill="#fff" d="M22.4 14.5c.3-2-1.2-3.1-3.3-3.8l.7-2.7-1.7-.4-.7 2.6c-.4-.1-.9-.2-1.3-.3l.7-2.7-1.7-.4-.7 2.7-1.1-.2v0L10.9 9l-.5 1.8s1.3.3 1.3.3c.7.2.8.7.8 1l-.8 3.1c.1 0 .1 0 .2.1l-.2-.1-1.1 4.4c-.1.2-.3.5-.8.4 0 0-1.3-.3-1.3-.3l-.9 1.9 2.3.6c.4.1.8.2 1.3.3l-.7 2.7 1.7.4.7-2.7 1.3.4-.7 2.7 1.7.4.7-2.7c2.9.6 5.2.4 6.1-2.3.8-2.2-.1-3.5-1.7-4.3 1.2-.3 2-1.1 2.2-2.6zm-3.8 5.7c-.5 2.2-4.3 1-5.5.7l.9-3.6c1.2.3 5.2.9 4.6 2.9zm.5-5.7c-.5 2-3.6.9-4.6.7l.8-3.3c1 .3 4.3.8 3.8 2.6z"/></svg>
    ),
    eth: (
      <svg viewBox="0 0 32 32" width="22" height="22"><circle cx="16" cy="16" r="16" fill="#627EEA"/><path fill="#fff" fillOpacity=".6" d="M16.5 4v8.9l7.5 3.4z"/><path fill="#fff" d="M16.5 4 9 16.3l7.5-3.4z"/><path fill="#fff" fillOpacity=".6" d="M16.5 21.97v6.03L24 17.7z"/><path fill="#fff" d="M16.5 28v-6.03L9 17.7z"/><path fill="#fff" fillOpacity=".2" d="m16.5 20.57 7.5-4.27-7.5-3.4z"/><path fill="#fff" fillOpacity=".6" d="m9 16.3 7.5 4.27v-7.67z"/></svg>
    ),
    bnb: (
      <svg viewBox="0 0 32 32" width="22" height="22"><circle cx="16" cy="16" r="16" fill="#F0B90B"/><path fill="#fff" d="M12.1 13.9 16 10l3.9 3.9 2.3-2.3L16 5.4l-6.2 6.2 2.3 2.3zM5.4 16l2.3-2.3L10 16l-2.3 2.3L5.4 16zm6.7 2.1L16 22l3.9-3.9 2.3 2.3L16 26.6l-6.2-6.2v-.1l2.3-2.2zM22 16l2.3-2.3 2.3 2.3-2.3 2.3L22 16zm-3.7 0L16 13.7 14.3 15.4l-.2.2-.4.4L16 18.3 18.3 16z"/></svg>
    ),
    card: (
      <svg viewBox="0 0 32 32" width="22" height="22" fill="none" stroke="#7C5CFF" strokeWidth="2"><rect x="3" y="7" width="26" height="18" rx="3"/><path d="M3 12h26" strokeWidth="2.5"/><path d="M7 19h4" strokeLinecap="round"/></svg>
    ),
    binance: (
      <svg viewBox="0 0 32 32" width="22" height="22"><rect width="32" height="32" rx="6" fill="#F0B90B"/><path fill="#000" d="M12.1 13.9 16 10l3.9 3.9 2.3-2.3L16 5.4l-6.2 6.2 2.3 2.3zM5.4 16l2.3-2.3L10 16l-2.3 2.3L5.4 16zm6.7 2.1L16 22l3.9-3.9 2.3 2.3L16 26.6l-6.2-6.2 2.3-2.3zM22 16l2.3-2.3 2.3 2.3-2.3 2.3L22 16zm-3.7 0L16 13.7l-2.3 2.3 2.3 2.3L18.3 16z"/></svg>
    ),
  };

  // Available payment methods.
  // Crypto methods route through NOWPayments.
  // Card / Apple Pay / Google Pay route through Lemon Squeezy.
  // Binance Pay is a separate flow (hosted by Binance — not implemented yet).
  const methods = [
    // ── Crypto (NOWPayments) ─────────────────────────────────────────
    { id: 'usdt_trc20', name: 'USDT (TRC-20)', desc: 'Tether on Tron · low fees, fast', icon: ICONS.usdt,    color: '#26A17B', kind: 'crypto', payCurrency: 'usdttrc20' },
    { id: 'usdt_bsc',   name: 'USDT (BEP-20)', desc: 'Tether on BNB Smart Chain',       icon: ICONS.usdtBsc, color: '#F0B90B', kind: 'crypto', payCurrency: 'usdtbsc' },
    { id: 'btc',        name: 'Bitcoin',       desc: 'BTC on-chain · ~10 min confirm',  icon: ICONS.btc,     color: '#F7931A', kind: 'crypto', payCurrency: 'btc' },
    { id: 'eth',        name: 'Ethereum',      desc: 'ETH on ERC-20',                   icon: ICONS.eth,     color: '#627EEA', kind: 'crypto', payCurrency: 'eth' },
    { id: 'bnb_bsc',    name: 'BNB',           desc: 'BNB on BNB Smart Chain',          icon: ICONS.bnb,     color: '#F0B90B', kind: 'crypto', payCurrency: 'bnbbsc' },

    // ── Card / Wallet (Lemon Squeezy hosts Apple Pay + Google Pay) ──
    { id: 'card',       name: 'Card · Apple Pay · Google Pay', desc: 'Visa / Mastercard / Apple Pay / Google Pay', icon: ICONS.card,    color: '#7C5CFF', kind: 'card' },

    // ── Binance Pay (hosted) ────────────────────────────────────────
    { id: 'binance',    name: 'Binance Pay',   desc: 'Pay from your Binance wallet (0% fee)', icon: ICONS.binance, color: '#F0B90B', kind: 'binance' },
  ];

  const subtotal = ea.price;
  const total = subtotal;

  const selectedMethod = methods.find(m => m.id === method);
  const methodName = selectedMethod?.name || method;

  async function pay() {
    setMt5Error('');
    const acctTrim = mt5Account.trim();
    if (!acctTrim) { setMt5Error('Please enter your MT5 account number first.'); return; }
    if (!/^[0-9]{4,15}$/.test(acctTrim)) { setMt5Error('MT5 account number must be 4–15 digits.'); return; }

    setProcessing(true);

    // ── Crypto → NOWPayments hosted invoice ──────────────────────────
    if (selectedMethod?.kind === 'crypto') {
      try {
        const res = await fetch('/api/nowpayments-create', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            price: total,
            currency: 'usd',
            payCurrency: selectedMethod.payCurrency,
            orderId,
            description: `${ea.name} — Lifetime License (MT5: ${acctTrim})`,
            customerEmail: user?.email,
          }),
        });
        const data = await res.json();
        if (data.invoiceUrl) {
          if (user && window.fb) {
            await window.fb.db.collection('orders').doc(orderId).set({
              userId: user.uid, userName: user.name, userEmail: user.email,
              eaId: ea.id, eaName: ea.name,
              mt5Account: acctTrim, mt5Broker: mt5Broker.trim() || null,
              amount: total, method: methodName, licenseKey,
              licenseTerm: ea.selectedLicense?.label || null,
              status: 'pending', invoiceId: data.invoiceId,
              expertFiles: [],
              createdAt: firebase.firestore.FieldValue.serverTimestamp(),
            }).catch(() => {});
          }
          if (window.Mailer) {
            window.Mailer.sendAdminPurchaseNotice({
              customerName: user?.name, customerEmail: user?.email,
              eaName: ea.name, price: total, method: methodName,
              mt5Account: acctTrim, mt5Broker: mt5Broker.trim(),
              licenseKey, orderId, status: 'pending',
            }).catch(() => {});
            if (user?.email) {
              window.Mailer.sendOrderReceived({
                email: user.email, name: user?.name,
                eaName: ea.name, price: total, method: methodName,
                orderId, licenseTerm: ea.selectedLicense?.label || null,
              }).catch(() => {});
            }
          }
          window.location.href = data.invoiceUrl;
        } else {
          alert('Payment error: ' + (data.error || 'Unknown'));
          setProcessing(false);
        }
      } catch (e) {
        alert('Network error: ' + e.message);
        setProcessing(false);
      }
      return;
    }

    // ── Card / Apple Pay / Google Pay → Lemon Squeezy ────────────────
    if (selectedMethod?.kind === 'card') {
      try {
        const res = await fetch('/api/lemonsqueezy-create', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            variantId: ea.lemonVariantId || null, // Admin sets this per EA
            customerEmail: user?.email,
            customerName: user?.name,
            orderId,
            eaName: ea.name,
          }),
        });
        const data = await res.json();
        if (data.checkoutUrl) {
          if (user && window.fb) {
            await window.fb.db.collection('orders').doc(orderId).set({
              userId: user.uid, userName: user.name, userEmail: user.email,
              eaId: ea.id, eaName: ea.name,
              mt5Account: acctTrim, mt5Broker: mt5Broker.trim() || null,
              amount: total, method: methodName, licenseKey,
              licenseTerm: ea.selectedLicense?.label || null,
              status: 'pending', invoiceId: data.checkoutId,
              expertFiles: [],
              createdAt: firebase.firestore.FieldValue.serverTimestamp(),
            }).catch(() => {});
          }
          if (window.Mailer) {
            window.Mailer.sendAdminPurchaseNotice({
              customerName: user?.name, customerEmail: user?.email,
              eaName: ea.name, price: total, method: methodName,
              mt5Account: acctTrim, mt5Broker: mt5Broker.trim(),
              licenseKey, orderId, status: 'pending',
            }).catch(() => {});
            if (user?.email) {
              window.Mailer.sendOrderReceived({
                email: user.email, name: user?.name,
                eaName: ea.name, price: total, method: methodName,
                orderId, licenseTerm: ea.selectedLicense?.label || null,
              }).catch(() => {});
            }
          }
          window.location.href = data.checkoutUrl;
        } else {
          alert('Payment error: ' + (data.error || 'No variant ID set for this EA. Admin must configure it in Lemon Squeezy.'));
          setProcessing(false);
        }
      } catch (e) {
        alert('Network error: ' + e.message);
        setProcessing(false);
      }
      return;
    }

    // ── Binance Pay (placeholder — set up merchant first) ────────────
    if (selectedMethod?.kind === 'binance') {
      alert('Binance Pay merchant approval pending. Please use another method for now.');
      setProcessing(false);
      return;
    }
  }

  return (
    <div>
      <section style={{ padding: '48px 0' }}>
        <div className="container">
          <span className="eyebrow">CHECKOUT · STEP {step} / 3</span>
          <h1 className="mt-4" style={{ fontSize: 48 }}>Secure <span className="gradient-text">deployment</span></h1>

          {/* Progress */}
          <div className="flex gap-2 mt-8 mb-8">
            {[1, 2, 3].map(s => (
              <div key={s} style={{ flex: 1, height: 4, borderRadius: 2, background: s <= step ? 'var(--cyan)' : 'rgba(255,255,255,0.08)', boxShadow: s <= step ? '0 0 8px var(--cyan)' : 'none', transition: 'all 0.4s' }}/>
            ))}
          </div>

          <div className="grid" style={{ gridTemplateColumns: '1.4fr 1fr', gap: 32 }}>
            <div>
              {step === 1 && (
                <div className="panel panel-padded-lg">
                  <h2 style={{ fontSize: 24 }}>Select payment method</h2>
                  <p className="text-muted text-sm mt-2">All payments are end-to-end encrypted. License key issues automatically.</p>

                  <div className="font-mono text-xs text-muted mt-6 mb-2" style={{ letterSpacing: '0.15em' }}>CRYPTO</div>
                  <div className="grid grid-2" style={{ gap: 12 }}>
                    {methods.filter(m => m.kind === 'crypto').map(m => (
                      <PaymentOption key={m.id} m={m} selected={method === m.id} onSelect={() => setMethod(m.id)}/>
                    ))}
                  </div>

                  <div className="font-mono text-xs text-muted mt-6 mb-2" style={{ letterSpacing: '0.15em' }}>CARDS & WALLETS</div>
                  <div className="grid grid-2" style={{ gap: 12 }}>
                    {methods.filter(m => m.kind === 'card' || m.kind === 'binance').map(m => (
                      <PaymentOption key={m.id} m={m} selected={method === m.id} onSelect={() => setMethod(m.id)}/>
                    ))}
                  </div>

                  <button className="btn btn-primary btn-lg btn-block btn-sheen mt-6" onClick={() => setStep(2)}>Continue →</button>
                </div>
              )}

              {step === 2 && (
                <div className="panel panel-padded-lg">
                  <h2 style={{ fontSize: 24 }}>Confirm & pay</h2>
                  <p className="text-muted text-sm mt-2">Paying with <span className="text-cyan">{methodName}</span></p>

                  {/* MT5 Account input */}
                  <div className="panel mt-6" style={{ padding: 20, background: 'rgba(255,45,170,0.04)', borderColor: 'rgba(255,45,170,0.25)' }}>
                    <span className="eyebrow" style={{ color: 'var(--magenta)' }}>MT5 ACCOUNT · REQUIRED</span>
                    <p className="text-xs text-muted mt-2">Enter the MT5 account number the EA will be licensed to. We need this to bind your license and prepare the files.</p>
                    <div className="field mt-3">
                      <label>MT5 Account Number *</label>
                      <input
                        className="input font-mono"
                        type="text"
                        inputMode="numeric"
                        placeholder="e.g. 1234567890"
                        value={mt5Account}
                        onChange={(e) => { setMt5Account(e.target.value.replace(/[^0-9]/g, '')); setMt5Error(''); }}
                        autoComplete="off"
                      />
                    </div>
                    <div className="field mt-3">
                      <label>Broker (optional)</label>
                      <input
                        className="input"
                        type="text"
                        placeholder="e.g. Exness, IC Markets, Pepperstone..."
                        value={mt5Broker}
                        onChange={(e) => setMt5Broker(e.target.value)}
                      />
                    </div>
                    {mt5Error && (
                      <div className="panel mt-3" style={{ padding: 10, background: 'rgba(255,59,92,0.08)', borderColor: 'rgba(255,59,92,0.3)' }}>
                        <span className="text-red font-mono text-xs">⚠ {mt5Error}</span>
                      </div>
                    )}
                  </div>

                  <div className="panel mt-4" style={{ padding: 20, background: 'rgba(0,229,255,0.04)' }}>
                    <div className="flex-between mb-2">
                      <span className="text-muted text-sm">Amount</span>
                      <span className="display" style={{ fontSize: 24, color: 'var(--cyan)' }}>${total}.00</span>
                    </div>
                    <div className="flex-between text-sm">
                      <span className="text-muted">Method</span>
                      <span className="font-mono">{methodName}</span>
                    </div>
                  </div>

                  <p className="text-muted text-sm mt-6">
                    {selectedMethod?.kind === 'crypto' && 'You\'ll be redirected to a secure invoice page with the wallet address and QR code. After your payment confirms, your EA will be uploaded to your dashboard.'}
                    {selectedMethod?.kind === 'card' && 'You\'ll be redirected to our secure checkout (Lemon Squeezy). Cards, Apple Pay, and Google Pay are all supported.'}
                    {selectedMethod?.kind === 'binance' && 'Binance Pay support is being approved by Binance. We\'ll enable it as soon as it\'s active.'}
                  </p>

                  <button className="btn btn-primary btn-lg btn-block btn-sheen mt-6" onClick={pay} disabled={processing}>
                    {processing ? <span className="typing"><span/><span/><span/></span> : `Pay $${total}.00 →`}
                  </button>
                  <button className="btn btn-ghost btn-sm btn-block mt-2" onClick={() => setStep(1)}>← Back</button>
                </div>
              )}

              {step === 3 && (
                <div className="panel panel-padded-lg text-center" style={{ padding: 48 }}>
                  <div style={{ width: 80, height: 80, margin: '0 auto', borderRadius: '50%', background: 'rgba(0,255,148,0.1)', border: '2px solid var(--green)', display: 'grid', placeItems: 'center', boxShadow: '0 0 32px rgba(0,255,148,0.4)' }}>
                    <svg width="40" height="40" viewBox="0 0 24 24" fill="none"><path d="M5 13l4 4L19 7" stroke="var(--green)" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  </div>
                  <h2 className="mt-6" style={{ fontSize: 32 }}>Payment confirmed</h2>
                  <p className="text-muted mt-4">License key sent to your email. EA ready for deployment.</p>
                  <div className="panel mt-6" style={{ padding: 16, background: 'rgba(0,0,0,0.4)' }}>
                    <div className="text-xs text-muted">License Key</div>
                    <div className="font-mono text-cyan mt-2" style={{ fontSize: 14, wordBreak: 'break-all' }}>{licenseKey}</div>
                  </div>
                  <button className="btn btn-primary btn-lg mt-6 btn-sheen" onClick={() => go('dashboard')}>Open Dashboard →</button>
                </div>
              )}
            </div>

            {/* Order summary */}
            <div className="panel panel-glow panel-padded-lg" style={{ position: 'sticky', top: 96, height: 'fit-content' }}>
              <span className="eyebrow">ORDER SUMMARY</span>
              <div className="mt-6">
                <div className="flex gap-3" style={{ alignItems: 'flex-start' }}>
                  <div style={{ width: 56, height: 56, borderRadius: 8, background: 'var(--grad-1)', display: 'grid', placeItems: 'center', fontFamily: 'var(--font-mono)', fontWeight: 700, color: '#000', fontSize: 18 }}>{ea.name[0]}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 600 }}>{ea.name}</div>
                    <div className="text-xs text-muted mt-1">{ea.strategy} · {ea.selectedLicense ? ea.selectedLicense.label + ' license' : 'Lifetime License'}</div>
                  </div>
                  <div className="font-mono">${ea.price}</div>
                </div>
              </div>
              <div className="divider"/>
              <div className="flex-between text-sm mb-2">
                <span className="text-muted">Lifetime updates</span>
                <span className="font-mono text-green">INCLUDED</span>
              </div>
              <div className="flex-between text-sm mb-2">
                <span className="text-muted">.set files (all pairs)</span>
                <span className="font-mono text-green">INCLUDED</span>
              </div>
              <div className="flex-between text-sm mb-2">
                <span className="text-muted">AI Agent access</span>
                <span className="font-mono text-green">INCLUDED</span>
              </div>
              <div className="flex-between text-sm mb-2">
                <span className="text-muted">Full backtest report</span>
                <span className="font-mono text-green">INCLUDED</span>
              </div>
              <div className="divider"/>
              <div className="flex-between">
                <span style={{ fontWeight: 600 }}>Total</span>
                <span className="display" style={{ fontSize: 28, color: 'var(--cyan)' }}>${total}</span>
              </div>
              <div className="text-xs text-muted mt-2 font-mono">USD · one-time</div>

              <div className="divider"/>
              <span className="eyebrow">BACKTEST SUMMARY</span>
              <div className="grid grid-2 mt-4">
                <div><div className="stat-label" style={{ fontSize: 9 }}>Win</div><div className="font-mono text-cyan">{ea.winRate}%</div></div>
                <div><div className="stat-label" style={{ fontSize: 9 }}>PF</div><div className="font-mono text-green">{ea.pf}</div></div>
                <div><div className="stat-label" style={{ fontSize: 9 }}>DD</div><div className="font-mono text-red">{ea.dd}%</div></div>
                <div><div className="stat-label" style={{ fontSize: 9 }}>Risk</div><div className="font-mono" style={{ color: ea.risk < 5 ? 'var(--green)' : 'var(--amber)' }}>{ea.risk}/10</div></div>
              </div>
              <div style={{ height: 80, marginTop: 12 }}><EquityCurve data={ea.curve} height={80} animated={false}/></div>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

function PaymentOption({ m, selected, onSelect }) {
  return (
    <div onClick={onSelect} className="panel" style={{
      padding: 16, cursor: 'pointer',
      borderColor: selected ? 'var(--cyan)' : 'var(--line)',
      boxShadow: selected ? '0 0 0 1px var(--cyan), 0 0 16px rgba(0,229,255,0.2)' : 'none',
      transition: 'all 0.2s',
    }}>
      <div className="flex gap-3" style={{ alignItems: 'center' }}>
        <div style={{ width: 36, height: 36, borderRadius: 8, display: 'grid', placeItems: 'center', flexShrink: 0 }}>{m.icon}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 600, fontSize: 13 }}>{m.name}</div>
          <div className="text-xs text-muted mt-1" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{m.desc}</div>
        </div>
        <div style={{ width: 14, height: 14, borderRadius: '50%', border: '1.5px solid var(--line-strong)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
          {selected && <div style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--cyan)', boxShadow: '0 0 6px var(--cyan)' }}/>}
        </div>
      </div>
    </div>
  );
}

window.CheckoutPage = CheckoutPage;
