/**
 * Checkout + Confirm screens — Stripe Payment Element flow.
 *
 * Step 1 = address, Step 2 = pay (Stripe Elements). Server creates a
 * PaymentIntent up front (price recomputed from live DB) and the client
 * confirms it via stripe.confirmPayment(). On success the order is flipped
 * to 'paid' via /api/checkout/confirm and we navigate to the confirm screen.
 */

window.CheckoutScreen = function CheckoutScreen({ lang, cart, onNav, channel, user, onPlaced }) {
  const [step, setStep]       = React.useState(1);
  const prefillName = (user?.name || '').trim().split(/\s+/);
  const [form, setForm] = React.useState({
    email: user?.email || 'customer@yy.shop',
    phone: user?.phone || '+62 812 3456 7890',
    first: prefillName[0] || 'Anya',
    last:  prefillName.slice(1).join(' ') || 'Wong',
    address1: 'Jalan Sudirman Kav. 12',
    address2: '',
    city: 'Jakarta',
    postal: '10220',
    country: 'Indonesia',
    shipping_method: 'YY Express · 5–7 days',
  });

  // If user logs in mid-checkout, backfill email/phone/name.
  React.useEffect(() => {
    if (!user) return;
    const pn = (user.name || '').trim().split(/\s+/);
    setForm(f => ({
      ...f,
      email: user.email || f.email,
      phone: user.phone || f.phone,
      first: pn[0] || f.first,
      last:  pn.slice(1).join(' ') || f.last,
    }));
  }, [user?.id]); // eslint-disable-line

  const subtotal = cart.reduce((s, i) => s + Number(i.price) * (i.qty || 1), 0);
  const shipping = subtotal > 80 ? 0 : 12;
  const tax = Math.round(subtotal * 0.08 * 100) / 100;
  const total = subtotal + shipping + tax;

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  // -------- Stripe state --------
  const [stripeJsReady, setStripeJsReady] = React.useState(!!window.Stripe);
  const [checkoutCfg,   setCheckoutCfg]   = React.useState(null); // { publishable_key, currency, enabled }
  const [intent,        setIntent]        = React.useState(null); // { clientSecret, orderId, ... }
  const [stripeInst,    setStripeInst]    = React.useState(null);
  const [stripeElements,setStripeElements]= React.useState(null);
  const [paying,        setPaying]        = React.useState(false);
  const [payError,      setPayError]      = React.useState('');
  const [intentError,   setIntentError]   = React.useState('');
  const peMountRef = React.useRef(null);

  // Pull /checkout/config to know if Stripe is enabled and which pk_ to use.
  React.useEffect(() => {
    window.YY_API.get('/checkout/config').then(setCheckoutCfg).catch(() => setCheckoutCfg({ enabled: false }));
  }, []);

  // Inject https://js.stripe.com/v3/ once.
  React.useEffect(() => {
    if (window.Stripe) { setStripeJsReady(true); return; }
    const id = 'stripe-js-v3';
    if (document.getElementById(id)) return;
    const s = document.createElement('script');
    s.id = id;
    s.src = 'https://js.stripe.com/v3/';
    s.onload = () => setStripeJsReady(true);
    s.onerror = () => setPayError('Failed to load Stripe.js');
    document.head.appendChild(s);
  }, []);

  // Step 2 mount: create a PaymentIntent on the server, then mount the Element.
  React.useEffect(() => {
    if (step !== 2) return;
    if (!stripeJsReady) return;
    if (!checkoutCfg?.enabled || !checkoutCfg?.publishable_key) {
      setIntentError(
        lang === 'zh'
          ? '请先在后台 → 系统设置 → Stripe 支付 中填好 Publishable / Secret Key,并保存。'
          : 'Please configure Stripe keys under Admin → Settings → Stripe Payments first.'
      );
      return;
    }
    if (intent) return;

    (async () => {
      try {
        const r = await window.YY_API.post('/checkout/create-intent', {
          items: cart.map(i => ({ id: i.id, qty: i.qty || 1 })),
          customer: {
            email: form.email,
            phone: form.phone,
            name: [form.first, form.last].filter(Boolean).join(' '),
            address1: form.address1, address2: form.address2,
            city: form.city, postal: form.postal, country: form.country,
          },
          shipping, tax,
          shipping_method: form.shipping_method,
          channel_id: channel, lang,
        });
        setIntent(r);
        const stripe = window.Stripe(r.publishableKey || checkoutCfg.publishable_key);
        setStripeInst(stripe);
        const elements = stripe.elements({
          clientSecret: r.clientSecret,
          appearance: { theme: 'stripe' },
        });
        const pe = elements.create('payment', { layout: 'tabs' });
        // Defer mount until the ref is available (next tick after re-render).
        requestAnimationFrame(() => {
          if (peMountRef.current) pe.mount(peMountRef.current);
        });
        setStripeElements(elements);
      } catch (e) {
        setIntentError(e.message);
      }
    })();
  }, [step, stripeJsReady, checkoutCfg]); // eslint-disable-line

  // Trigger the actual charge.
  async function payNow() {
    if (!stripeInst || !stripeElements || !intent) return;
    setPayError(''); setPaying(true);
    try {
      const ret = await stripeInst.confirmPayment({
        elements: stripeElements,
        redirect: 'if_required',
        confirmParams: {
          return_url: window.location.origin + '/#/confirm',
          receipt_email: form.email,
        },
      });
      if (ret.error) { setPayError(ret.error.message || 'payment_failed'); setPaying(false); return; }
      const piId = ret.paymentIntent?.id || intent.clientSecret.split('_secret_')[0];
      const conf = await window.YY_API.post('/checkout/confirm', {
        orderId: intent.orderId, paymentIntentId: piId,
      });
      if (conf.orderStatus === 'paid' || conf.status === 'succeeded') {
        onPlaced && onPlaced({
          order_no: intent.orderNo, email: form.email,
          subtotal, shipping, tax, total, currency: 'USD',
          city: form.city, country: form.country, postal: form.postal,
        });
        onNav('confirm');
      } else {
        setPayError('Payment not yet succeeded — status: ' + (conf.status || 'unknown'));
      }
    } catch (e) {
      setPayError(e.message || 'payment_failed');
    } finally {
      setPaying(false);
    }
  }

  return (
    <div className="screen-body">
      <div className="checkout-layout">
        <div className="checkout-main">
          <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 38, letterSpacing: '-0.02em', marginBottom: 28 }}>
            {t('checkout.title', lang)}
          </h1>

          <div className="steps">
            <div className={'step ' + (step >= 1 ? 'on' : '')}><span className="step-num">{step > 1 ? '✓' : '1'}</span>{t('checkout.step1', lang)}</div>
            <div className={'step ' + (step >= 2 ? 'on' : '')}><span className="step-num">2</span>{t('checkout.step2', lang)}</div>
          </div>

          {step === 1 && (
            <div className="checkout-section">
              <h3>{t('checkout.step1', lang)}</h3>
              <div className="form-grid">
                <div className="form-field"><label>Email</label><input value={form.email} onChange={e => set('email', e.target.value)}/></div>
                <div className="form-field"><label>Phone</label><input value={form.phone} onChange={e => set('phone', e.target.value)}/></div>
                <div className="form-field"><label>First name</label><input value={form.first} onChange={e => set('first', e.target.value)}/></div>
                <div className="form-field"><label>Last name</label><input value={form.last} onChange={e => set('last', e.target.value)}/></div>
                <div className="form-field full"><label>Address line 1</label><input value={form.address1} onChange={e => set('address1', e.target.value)}/></div>
                <div className="form-field full"><label>Address line 2</label><input placeholder="Apt, unit (optional)" value={form.address2} onChange={e => set('address2', e.target.value)}/></div>
                <div className="form-field"><label>City</label><input value={form.city} onChange={e => set('city', e.target.value)}/></div>
                <div className="form-field"><label>Postal code</label><input value={form.postal} onChange={e => set('postal', e.target.value)}/></div>
                <div className="form-field"><label>Country / region</label><input value={form.country} onChange={e => set('country', e.target.value)}/></div>
                <div className="form-field"><label>Shipping method</label><input value={form.shipping_method} onChange={e => set('shipping_method', e.target.value)}/></div>
              </div>
              <button className="btn-primary" style={{ marginTop: 24 }} onClick={() => setStep(2)}>{t('common.continue', lang)} →</button>
            </div>
          )}

          {step === 2 && (
            <div className="checkout-section">
              <h3>{t('checkout.step2', lang)}</h3>

              {intentError && (
                <div style={{
                  padding: '12px 14px', background: '#fff7ed', border: '1px solid #fdba74',
                  color: '#9a3412', borderRadius: 8, fontSize: 13, marginBottom: 16,
                }}>{intentError}</div>
              )}

              {!intentError && !intent && (
                <div style={{ padding:'18px 0', color:'var(--fg-muted)', fontSize:13 }}>
                  {lang === 'zh' ? '正在创建支付意图…' : 'Creating payment intent…'}
                </div>
              )}

              <div ref={peMountRef} style={{ minHeight: intent ? 180 : 0 }}/>

              {payError && (
                <div style={{
                  padding: '10px 12px', background: '#fef2f2', border: '1px solid #fca5a5',
                  color: '#991b1b', borderRadius: 8, fontSize: 13, marginTop: 12,
                }}>{payError}</div>
              )}

              <div style={{ display: 'flex', gap: 12, marginTop: 20 }}>
                <button className="btn-ghost" onClick={() => { setStep(1); setIntent(null); setStripeElements(null); setStripeInst(null); setIntentError(''); }}>← Back</button>
                <button className="btn-primary" style={{ flex: 1 }}
                        disabled={paying || !intent || !!intentError}
                        onClick={payNow}>
                  {paying
                    ? (lang === 'zh' ? '处理中…' : 'Processing…')
                    : `${t('checkout.place', lang)} · $${total.toFixed(2)}`}
                </button>
              </div>
            </div>
          )}
        </div>

        <aside className="checkout-side">
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 22, marginBottom: 24 }}>Your bag</h3>
          <div className="cart-items">
            {cart.map((item, i) => (
              <div key={i} className="cart-item">
                <div className="cart-item-img"><div style={{ width: '85%', height: '85%' }}><ProductVisual product={item}/></div></div>
                <div>
                  <div className="cart-item-name">{item.name[lang] || item.name.en}</div>
                  <div className="cart-item-meta">Qty {item.qty || 1} · Size M</div>
                </div>
                <div className="cart-item-price">${(Number(item.price) * (item.qty || 1)).toFixed(2)}</div>
              </div>
            ))}
          </div>

          <div style={{ marginTop: 24, paddingTop: 16, borderTop: '1px solid var(--border)' }}>
            <div className="summary-row"><span>{t('common.subtotal', lang)}</span><span>${subtotal.toFixed(2)}</span></div>
            <div className="summary-row"><span>{t('common.shipping', lang)}</span><span>{shipping === 0 ? 'Free' : `$${shipping}`}</span></div>
            <div className="summary-row"><span>{t('common.tax', lang)}</span><span>${tax.toFixed(2)}</span></div>
            <div className="summary-row total"><span>{t('common.total', lang)}</span><span>${total.toFixed(2)}</span></div>
          </div>

          <div style={{ marginTop: 20, padding: 14, background: 'var(--surface)', borderRadius: 'var(--radius)', fontSize: 12, color: 'var(--fg-muted)', display: 'flex', gap: 10, alignItems: 'flex-start' }}>
            <span style={{ fontSize: 14 }}>◆</span>
            <span>Free shipping on orders over $80 · Powered by Stripe</span>
          </div>
        </aside>
      </div>
    </div>
  );
};

window.ConfirmScreen = function ConfirmScreen({ lang, cart, onNav, order }) {
  const orderNo  = order?.order_no || 'YY-' + Math.floor(100000 + Math.random() * 900000);
  const subtotal = order ? Number(order.subtotal) : cart.reduce((s, i) => s + Number(i.price) * (i.qty || 1), 0);
  const shipping = order ? Number(order.shipping) : (subtotal > 80 ? 0 : 12);
  const tax      = order ? Number(order.tax)      : subtotal * 0.08;
  const total    = order ? Number(order.total)    : subtotal + shipping + tax;
  const email    = order?.email || 'customer@yy.shop';
  const shipTo   = order ? `${order.city || ''}, ${order.country || ''} ${order.postal || ''}`.trim().replace(/^,\s*/, '') : 'Jakarta, Indonesia 10220';

  return (
    <div className="screen-body">
      <div className="confirm">
        <div className="confirm-icon">
          <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M5 12l5 5L20 7"/></svg>
        </div>
        <h1>{t('order.success', lang)}</h1>
        <div className="confirm-sub">{t('order.thanks', lang)}. A receipt has been sent to <strong style={{ color: 'var(--fg)' }}>{email}</strong></div>

        <div className="confirm-card">
          <div className="confirm-row"><span className="l">{t('order.number', lang)}</span><span style={{ fontFamily: 'var(--font-mono)' }}>{orderNo}</span></div>
          <div className="confirm-row"><span className="l">{t('order.eta', lang)}</span><span>{(() => {
            const fmt = (d) => d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
            const a = new Date(Date.now() + 3 * 864e5);
            const b = new Date(Date.now() + 8 * 864e5);
            return `${fmt(a)} – ${fmt(b)}, ${b.getFullYear()}`;
          })()}</span></div>
          <div className="confirm-row"><span className="l">Shipping to</span><span>{shipTo}</span></div>
          <div className="confirm-row"><span className="l">Payment</span><span>Stripe</span></div>
          <div className="confirm-row" style={{ paddingTop: 18 }}><span className="l">{t('common.total', lang)}</span><span style={{ fontWeight: 600, fontSize: 18 }}>${total.toFixed(2)} USD</span></div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 32 }}>
          {cart.slice(0, 4).map((item, i) => (
            <div key={i} style={{ aspectRatio: 1, background: 'var(--surface)', borderRadius: 'var(--radius)', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden' }}>
              <div style={{ width: '75%' }}><ProductVisual product={item}/></div>
            </div>
          ))}
        </div>

        <div style={{ display: 'flex', gap: 12, justifyContent: 'center' }}>
          <button className="btn-primary" onClick={() => onNav('home')}>Continue shopping →</button>
          <button className="btn-ghost">Track order</button>
        </div>
      </div>
    </div>
  );
};
