/* AMBER & ZAFRAN — Multi-step Checkout */
function Field({ label, value, onChange, type = 'text', err, wide, ph, inputMode }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 7, gridColumn: wide ? '1 / -1' : 'auto' }}>
      <span style={{ fontFamily: 'var(--sans)', fontSize: 10, letterSpacing: '.16em', textTransform: 'uppercase', color: err ? 'var(--burgundy)' : 'var(--ink-soft)' }}>{label}</span>
      <input
        type={type} value={value} inputMode={inputMode} placeholder={ph}
        onChange={e => onChange(e.target.value)}
        style={{ border: 'none', borderBottom: `1.5px solid ${err ? 'var(--burgundy)' : 'var(--line)'}`, background: 'transparent', padding: '10px 2px', fontFamily: 'var(--serif)', fontSize: 17, outline: 'none', transition: 'border-color .3s var(--ease), box-shadow .3s var(--ease)' }}
        onFocus={e => { e.target.style.borderBottomColor = 'var(--ink)'; e.target.style.boxShadow = '0 1.5px 0 0 var(--ink)'; }}
        onBlur={e => { e.target.style.borderBottomColor = err ? 'var(--burgundy)' : 'var(--line)'; e.target.style.boxShadow = 'none'; }}
      />
    </label>
  );
}

function Stepper({ steps, idx, lang }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', padding: '4px 0 26px' }}>
      {steps.map((s, i) => (
        <React.Fragment key={i}>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
            <div style={{ width: 30, height: 30, borderRadius: '50%', display: 'grid', placeItems: 'center', fontFamily: 'var(--serif)', fontSize: 14, transition: 'all .4s var(--ease)', background: i <= idx ? 'var(--burgundy)' : 'transparent', color: i <= idx ? 'var(--white)' : 'var(--ink-soft)', border: i <= idx ? 'none' : '1px solid var(--line)' }}>
              {i < idx ? <Icon.check /> : i + 1}
            </div>
            <span style={{ fontFamily: lang === 'ar' ? 'var(--arabic)' : 'var(--sans)', fontSize: 9.5, letterSpacing: lang === 'ar' ? 0 : '.14em', textTransform: 'uppercase', color: i <= idx ? 'var(--ink)' : 'var(--ink-soft)', whiteSpace: 'nowrap' }}>{s}</span>
          </div>
          {i < steps.length - 1 && <div style={{ flex: 1, height: 1, margin: '0 8px', marginBottom: 22, background: i < idx ? 'var(--burgundy)' : 'var(--line)', transition: 'background .4s var(--ease)' }}></div>}
        </React.Fragment>
      ))}
    </div>
  );
}

function SummaryRow({ label, value, strong, muted }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: strong ? '14px 0 0' : '6px 0' }}>
      <span style={{ fontFamily: 'var(--sans)', fontSize: strong ? 12 : 12, letterSpacing: '.1em', textTransform: 'uppercase', color: muted ? 'var(--ink-soft)' : 'var(--ink)' }}>{label}</span>
      <span style={{ fontFamily: strong ? 'var(--serif)' : 'var(--sans)', fontSize: strong ? 24 : 13, color: muted ? 'var(--ink-soft)' : 'var(--ink)' }}>{value}</span>
    </div>
  );
}

function Checkout({ t, lang, go, cart, promo: appliedPromo, discountAmount, applyPromoCode, removePromoCode, onOrderPlaced }) {
  const c = t.co;
  const [step, setStep] = useState(0);
  // Phase 3B: the real, server-generated order — replaces the old
  // Math.random() placeholder number. null until an order is actually placed.
  const [order, setOrder] = useState(null);
  const [placing, setPlacing] = useState(false);
  const [orderError, setOrderError] = useState('');
  const [f, setF] = useState({ fName: '', lName: '', email: '', phone: '', address: '', address2: '', city: '', country: 'Jordan', postal: '' });
  const [delivery, setDelivery] = useState(0);
  const [isGift, setIsGift] = useState(false);
  const [giftMsg, setGiftMsg] = useState('');
  const [pay, setPay] = useState('card');
  const [errs, setErrs] = useState({});
  // promo input box: pre-fills with whatever code is already applied to
  // the cart (so it survives a refresh, same as the cart itself does).
  const [promo, setPromo] = useState(appliedPromo && appliedPromo.valid ? appliedPromo.code : '');
  const [promoMsg, setPromoMsg] = useState('');
  const set = (k) => (v) => setF(s => ({ ...s, [k]: v }));
  const scrollRef = useRef(null);

  const subtotal = cart.reduce((s, it) => s + it.price * it.qty, 0);
  const count = cart.reduce((s, it) => s + it.qty, 0);
  const shipCost = c.delivery[delivery][2];
  const giftCost = 0;
  const appliedDiscount = appliedPromo && appliedPromo.valid ? (discountAmount || 0) : 0;
  const total = subtotal + shipCost + giftCost - appliedDiscount;
  const tax = Math.round(total * 0.16);

  const topReset = () => { if (scrollRef.current) scrollRef.current.scrollTop = 0; };

  const validateDetails = () => {
    const e = {};
    ['fName', 'lName', 'email', 'phone', 'address', 'city'].forEach(k => { if (!f[k].trim()) e[k] = true; });
    if (f.email && !/^\S+@\S+\.\S+$/.test(f.email)) e.email = true;
    setErrs(e); return Object.keys(e).length === 0;
  };
  // Phase 3C-A: card/Apple Pay no longer collect anything here at all
  // — the customer enters card details on Network's own hosted page,
  // never ours (that's the entire point of "hosted" checkout: this
  // project never sees or stores a raw card number). So there's
  // nothing left to validate before redirecting.
  const validatePay = () => true;

  const PAY_METHOD_MAP = { card: 'card', apple: 'apple_pay', cod: 'cod' };
  const DELIVERY_METHOD_MAP = ['express', 'standard', 'concierge'];

  const placeOrder = async () => {
    setPlacing(true);
    setOrderError('');
    try {
      const result = await window.AZOrder.placeOrder({
        contact: { first_name: f.fName, last_name: f.lName, email: f.email, phone: f.phone, preferred_lang: lang },
        address: { address_line1: f.address, address_line2: f.address2, city: f.city, postal_code: f.postal, country: f.country },
        delivery_method: DELIVERY_METHOD_MAP[delivery],
        is_gift: isGift,
        gift_message: giftMsg,
        gift_wrap_style: 'burgundy_silk_gold_seal',
        payment_method: PAY_METHOD_MAP[pay],
        promo_code: appliedPromo && appliedPromo.valid ? appliedPromo.code : null,
      });
      setOrder(result);
      if (onOrderPlaced) onOrderPlaced();

      if (pay === 'cod') {
        // No gateway involved at all for Cash on Delivery — the order
        // is already "confirmed" (see lib/orderService.js), so this
        // goes straight to the same confirmation screen as before.
        setStep(3); topReset();
        return;
      }

      // card / apple_pay: the order exists but is still "pending" —
      // it only becomes "confirmed" once Network's server-to-server
      // callback says the payment succeeded (see
      // docs/phase3c-a-payment-integration.md). This redirects the
      // browser away from the app entirely, to Network's own page.
      const session = await window.AZPayment.createSession(result.order_id);
      window.location.href = session.redirect_url;
    } catch (err) {
      setOrderError(
        err.code === 'OUT_OF_STOCK'
          ? (lang === 'ar' ? 'أحد العناصر في حقيبتك لم يعد متوفراً بهذه الكمية.' : 'One of the items in your bag is no longer available in that quantity.')
          : (lang === 'ar' ? 'تعذّر إتمام الطلب. يرجى المحاولة مرة أخرى.' : 'Couldn’t place your order. Please try again.')
      );
    } finally {
      setPlacing(false);
    }
  };

  const next = () => {
    if (step === 0 && !validateDetails()) return;
    if (step === 2 && !validatePay()) { return; }
    if (step === 2) { placeOrder(); return; }
    setStep(s => s + 1); topReset();
  };
  const back = () => { if (step === 0) { go('shop'); } else { setStep(s => s - 1); topReset(); } };

  // EMPTY
  if (cart.length === 0 && step < 3) {
    return (
      <div style={{ minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
        <CheckoutBar t={t} c={c} onBack={() => go('shop')} />
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 22, padding: 40, textAlign: 'center' }}>
          <img src="assets/mark-black.png" alt="" style={{ width: 76, opacity: .45 }} />
          <h2 className="sec-title h-md">{c.emptyTitle}</h2>
          <button className="btn btn-fill" onClick={() => go('shop')}>{c.emptyBtn}</button>
        </div>
      </div>
    );
  }

  // CONFIRMATION
  if (step === 3 && order) {
    const orderNo = order.order_number;
    return (
      <div ref={scrollRef} style={{ minHeight: '100%', background: 'radial-gradient(120% 70% at 50% 0%, #2a1116, #160a0d)', color: 'var(--white)', display: 'flex', flexDirection: 'column' }}>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '70px 30px', textAlign: 'center' }}>
          <div style={{ position: 'relative', marginBottom: 8 }}>
            <div style={{ position: 'absolute', inset: -30, background: 'radial-gradient(circle, rgba(220,177,107,.3), transparent 65%)', filter: 'blur(10px)' }}></div>
            <img src="assets/mark-gold.png" alt="" style={{ width: 110, position: 'relative', animation: 'rise 1s var(--ease) both' }} />
          </div>
          <div className="kicker solo center" style={{ justifyContent: 'center', color: 'var(--gold)', marginTop: 18, animation: 'rise 1s var(--ease) .1s both' }}>{c.confSub}</div>
          <h1 className="sec-title" style={{ fontSize: 'clamp(50px,16vw,72px)', color: 'var(--white)', marginTop: 14, animation: 'rise 1s var(--ease) .15s both' }}>{c.confTitle}</h1>
          <p className="body" style={{ color: 'rgba(253,253,253,.8)', maxWidth: 300, marginTop: 14, animation: 'rise 1s var(--ease) .25s both' }}>{c.confBody}</p>

          <div style={{ width: '100%', maxWidth: 320, marginTop: 34, padding: '22px 24px', background: 'rgba(255,255,255,.05)', border: '1px solid rgba(220,177,107,.25)', animation: 'rise 1s var(--ease) .35s both' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingBottom: 14, borderBottom: '1px solid rgba(255,255,255,.12)' }}>
              <span style={{ fontFamily: 'var(--sans)', fontSize: 10, letterSpacing: '.18em', textTransform: 'uppercase', color: 'var(--rose)' }}>{c.orderNo}</span>
              <span style={{ fontFamily: 'var(--serif)', fontSize: 18, color: 'var(--gold)' }}>{orderNo}</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: 14 }}>
              <span style={{ fontFamily: lang === 'ar' ? 'var(--arabic)' : 'var(--sans)', fontSize: 10, letterSpacing: lang === 'ar' ? 0 : '.18em', textTransform: 'uppercase', color: 'var(--rose)' }}>{c.est}</span>
              <span style={{ fontFamily: lang === 'ar' ? 'var(--arabic)' : 'var(--serif)', fontSize: 13, textAlign: lang === 'ar' ? 'left' : 'right' }}>{c.estVal}</span>
            </div>
          </div>
          <p style={{ fontFamily: lang === 'ar' ? 'var(--arabic)' : 'var(--sans)', fontSize: 11, letterSpacing: lang === 'ar' ? 0 : '.08em', color: 'rgba(253,253,253,.5)', marginTop: 18, animation: 'rise 1s var(--ease) .4s both' }}>{c.trackNote}</p>
          <button className="btn btn-gold" style={{ marginTop: 30, animation: 'rise 1s var(--ease) .45s both' }} onClick={() => go('home')}>{c.keepShopping}</button>
        </div>
      </div>
    );
  }

  return (
    <div ref={scrollRef} style={{ minHeight: '100%', display: 'flex', flexDirection: 'column', background: 'var(--paper)' }}>
      <CheckoutBar t={t} c={c} onBack={back} />

      <div style={{ padding: '20px 24px 0' }}>
        <Stepper steps={c.steps} idx={step} lang={lang} />
      </div>

      <div style={{ flex: 1, padding: '0 24px 30px' }}>
        {/* STEP 0 — DETAILS */}
        {step === 0 && (
          <div style={{ animation: 'fade .4s var(--ease)' }}>
            <SectionLabel n="01" title={c.contactK} lang={lang} />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px 16px', marginBottom: 36 }}>
              <Field label={c.fName} value={f.fName} onChange={set('fName')} err={errs.fName} />
              <Field label={c.lName} value={f.lName} onChange={set('lName')} err={errs.lName} />
              <Field label={c.email} value={f.email} onChange={set('email')} err={errs.email} type="email" inputMode="email" wide />
              <Field label={c.phone} value={f.phone} onChange={set('phone')} err={errs.phone} type="tel" inputMode="tel" wide />
            </div>
            <SectionLabel n="02" title={c.shipK} lang={lang} />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px 16px' }}>
              <Field label={c.address} value={f.address} onChange={set('address')} err={errs.address} wide />
              <Field label={c.address2} value={f.address2} onChange={set('address2')} wide />
              <Field label={c.city} value={f.city} onChange={set('city')} err={errs.city} />
              <Field label={c.postal} value={f.postal} onChange={set('postal')} />
              <Field label={c.country} value={f.country} onChange={set('country')} wide />
            </div>
          </div>
        )}

        {/* STEP 1 — DELIVERY + GIFTING */}
        {step === 1 && (
          <div style={{ animation: 'fade .4s var(--ease)' }}>
            <SectionLabel n="01" title={c.deliveryK} lang={lang} />
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 38 }}>
              {c.delivery.map((d, i) => (
                <button key={i} onClick={() => setDelivery(i)} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '18px 18px', textAlign: 'start', border: delivery === i ? '1.5px solid var(--ink)' : '1px solid var(--line)', background: delivery === i ? 'var(--cream)' : 'transparent', transition: 'all .3s var(--ease)' }}>
                  <span style={{ width: 18, height: 18, borderRadius: '50%', border: '1.5px solid', borderColor: delivery === i ? 'var(--burgundy)' : 'var(--line)', display: 'grid', placeItems: 'center', flex: 'none' }}>
                    {delivery === i && <span style={{ width: 9, height: 9, borderRadius: '50%', background: 'var(--burgundy)' }}></span>}
                  </span>
                  <span style={{ flex: 1 }}>
                    <span style={{ display: 'block', fontFamily: lang === 'ar' ? 'var(--arabic-display)' : 'var(--serif)', fontSize: 17 }}>{d[0]}</span>
                    <span style={{ display: 'block', fontFamily: lang === 'ar' ? 'var(--arabic)' : 'var(--sans)', fontSize: 11, letterSpacing: lang === 'ar' ? 0 : '.06em', color: 'var(--ink-soft)', marginTop: 3 }}>{d[1]}</span>
                  </span>
                  <span style={{ fontFamily: d[2] === 0 ? 'var(--sans)' : 'var(--serif)', fontSize: d[2] === 0 ? 10 : 16, letterSpacing: d[2] === 0 ? '.14em' : 0, textTransform: 'uppercase', color: d[2] === 0 ? 'var(--gold-deep-on-light)' : 'var(--ink)' }}>{d[2] === 0 ? d[3] : `${t.currency} ${d[2]}`}</span>
                </button>
              ))}
            </div>

            <SectionLabel n="02" title={c.giftK} lang={lang} />
            <button onClick={() => setIsGift(g => !g)} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 14, padding: '18px', border: '1px solid var(--line)', background: isGift ? 'var(--cream)' : 'transparent', transition: 'all .3s var(--ease)' }}>
              <span style={{ width: 44, height: 26, borderRadius: 14, background: isGift ? 'var(--burgundy)' : 'var(--line)', position: 'relative', transition: 'background .3s var(--ease)', flex: 'none' }}>
                <span style={{ position: 'absolute', top: 3, insetInlineStart: isGift ? 21 : 3, width: 20, height: 20, borderRadius: '50%', background: '#fff', transition: 'inset-inline-start .3s var(--ease)', boxShadow: '0 1px 3px rgba(0,0,0,.3)' }}></span>
              </span>
              <span style={{ flex: 1, textAlign: 'start' }}>
                <span style={{ display: 'block', fontFamily: lang === 'ar' ? 'var(--arabic-display)' : 'var(--serif)', fontSize: 17 }}>{c.giftToggle}</span>
                <span style={{ display: 'block', fontFamily: lang === 'ar' ? 'var(--arabic)' : 'var(--sans)', fontSize: 11, color: 'var(--gold-deep-on-light)', letterSpacing: lang === 'ar' ? 0 : '.06em', marginTop: 3 }}>{c.giftWrapNote}</span>
              </span>
            </button>
            {isGift && (
              <div style={{ marginTop: 14, animation: 'fade .4s var(--ease)' }}>
                <div style={{ display: 'flex', gap: 14, alignItems: 'center', padding: '16px', background: 'linear-gradient(150deg,#762538,#3a0e18)', color: 'var(--white)' }}>
                  <div style={{ width: 44, height: 44, position: 'relative', flex: 'none' }}>
                    <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(150deg,#1d0c10,#2c1116)' }}></div>
                    <div style={{ position: 'absolute', left: '50%', top: 0, bottom: 0, width: 6, transform: 'translateX(-50%)', background: 'linear-gradient(var(--gold-deep),var(--gold))' }}></div>
                    <div style={{ position: 'absolute', top: '50%', left: 0, right: 0, height: 6, transform: 'translateY(-50%)', background: 'linear-gradient(90deg,var(--gold-deep),var(--gold))' }}></div>
                  </div>
                  <span style={{ fontFamily: lang === 'ar' ? 'var(--arabic)' : 'var(--serif-it)', fontStyle: lang === 'ar' ? 'normal' : 'italic', fontSize: 15 }}>{c.giftWrap}</span>
                </div>
                <textarea value={giftMsg} onChange={e => setGiftMsg(e.target.value)} placeholder={c.giftMsgPh} rows={3} style={{ width: '100%', marginTop: 12, border: '1px solid var(--line)', background: 'transparent', padding: '14px', fontFamily: lang === 'ar' ? 'var(--arabic)' : 'var(--serif-it)', fontStyle: lang === 'ar' ? 'normal' : 'italic', fontSize: 15, outline: 'none', resize: 'none' }}></textarea>
              </div>
            )}
          </div>
        )}

        {/* STEP 2 — PAYMENT */}
        {step === 2 && (
          <div style={{ animation: 'fade .4s var(--ease)' }}>
            <SectionLabel n="01" title={c.payK} lang={lang} />
            <div style={{ display: 'flex', gap: 10, marginBottom: 26 }}>
              {[['card', c.payCard], ['apple', c.payApple], ['cod', c.payCod]].map(([k, lbl]) => (
                <button key={k} onClick={() => setPay(k)} style={{ flex: 1, padding: '14px 6px', fontFamily: lang === 'ar' ? 'var(--arabic)' : 'var(--sans)', fontSize: 11, letterSpacing: lang === 'ar' ? 0 : '.08em', textTransform: 'uppercase', border: pay === k ? '1.5px solid var(--ink)' : '1px solid var(--line)', background: pay === k ? 'var(--ink)' : 'transparent', color: pay === k ? 'var(--white)' : 'var(--ink)', transition: 'all .3s var(--ease)' }}>{lbl}</button>
              ))}
            </div>
            {(pay === 'card' || pay === 'apple') && (
              <div style={{ padding: '30px', textAlign: 'center', border: '1px solid var(--line)' }}>
                {pay === 'apple' && <div style={{ fontFamily: 'var(--serif-it)', fontStyle: 'italic', fontSize: 16, color: 'var(--ink-soft)', marginBottom: 10 }}>Apple Pay</div>}
                <p className="body">
                  {lang === 'ar'
                    ? 'سننقلك إلى صفحة الدفع الآمنة لشبكة Network لإدخال بيانات بطاقتك.'
                    : 'You’ll be redirected to Network’s secure payment page to enter your card details.'}
                </p>
              </div>
            )}
            {pay === 'cod' && <p className="body">{lang === 'ar' ? 'تدفع نقداً عند استلام طلبك.' : 'You will pay in cash when your order is delivered.'}</p>}
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 24, fontFamily: lang === 'ar' ? 'var(--arabic)' : 'var(--sans)', fontSize: 11, letterSpacing: lang === 'ar' ? 0 : '.08em', color: 'var(--ink-soft)' }}>
              <Icon.lock /> {c.secureNote}
            </div>
          </div>
        )}

        {/* ORDER SUMMARY (all steps) */}
        <div style={{ marginTop: 38, paddingTop: 28, borderTop: '1px solid var(--line)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
            <SectionLabel n="" title={c.summaryK} lang={lang} noNum />
            <button onClick={() => go('shop')} style={{ fontFamily: lang === 'ar' ? 'var(--arabic)' : 'var(--sans)', fontSize: 10, letterSpacing: lang === 'ar' ? 0 : '.14em', textTransform: 'uppercase', color: 'var(--ink-soft)', borderBottom: '1px solid var(--line)' }}>{c.editBag}</button>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginBottom: 18 }}>
            {cart.map((it, i) => (
              <div key={i} style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
                <div style={{ width: 50, height: 62, background: 'linear-gradient(160deg,#efe6da,#e2d4c4)', flex: 'none', position: 'relative' }}>
                  <div style={{ position: 'absolute', inset: 0, overflow: 'hidden' }}>
                    <div style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%)' }}><Flacon p={it.p} scale={0.34} showLabel={false} /></div>
                  </div>
                  <span style={{ position: 'absolute', top: -7, insetInlineEnd: -7, width: 20, height: 20, borderRadius: '50%', background: 'var(--burgundy)', color: '#fff', fontFamily: 'var(--sans)', fontSize: 10, display: 'grid', placeItems: 'center' }}>{it.qty}</span>
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: lang === 'ar' ? 'var(--arabic)' : 'var(--serif)', fontSize: 15 }}>{lang === 'ar' ? it.p.ar : it.p.name}</div>
                  <div style={{ fontFamily: 'var(--sans)', fontSize: 10, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--ink-soft)', marginTop: 2 }}>{it.size}</div>
                </div>
                <span style={{ fontFamily: 'var(--sans)', fontSize: 13 }}>{t.currency} {it.price * it.qty}</span>
              </div>
            ))}
          </div>

          {/* promo */}
          <div style={{ display: 'flex', border: '1px solid var(--line)', marginBottom: 8 }}>
            <input value={promo} onChange={e => setPromo(e.target.value)} placeholder={c.promoPh} style={{ flex: 1, border: 'none', background: 'transparent', padding: '13px 16px', fontFamily: lang === 'ar' ? 'var(--arabic)' : 'var(--sans)', fontSize: 12, letterSpacing: lang === 'ar' ? 0 : '.06em', outline: 'none', textTransform: 'uppercase' }} />
            <button
              onClick={() => {
                if (appliedDiscount > 0 && promo.trim() === '') { removePromoCode(); setPromoMsg(''); return; }
                applyPromoCode(promo).then((result) => {
                  setPromoMsg(result && result.valid
                    ? (lang === 'ar' ? `طُبِّق: خصم ${t.currency} ${result.discount_amount}` : `Applied: ${t.currency} ${result.discount_amount} off`)
                    : (lang === 'ar' ? 'رمز الخصم غير صالح.' : 'That promo code isn’t valid.'));
                });
              }}
              style={{ padding: '0 22px', fontFamily: lang === 'ar' ? 'var(--arabic)' : 'var(--sans)', fontSize: 11, letterSpacing: lang === 'ar' ? 0 : '.16em', textTransform: 'uppercase', borderInlineStart: '1px solid var(--line)' }}
            >{c.apply}</button>
          </div>
          {promoMsg && <div style={{ fontFamily: 'var(--sans)', fontSize: 11, color: appliedDiscount > 0 ? 'var(--burgundy)' : 'var(--ink-soft)', marginBottom: 14 }}>{promoMsg}</div>}

          <SummaryRow label={c.subtotal || t.subtotal} value={`${t.currency} ${subtotal}`} />
          <SummaryRow label={c.shipping} value={shipCost === 0 ? c.delivery[delivery][3] || '—' : `${t.currency} ${shipCost}`} muted />
          {isGift && <SummaryRow label={c.gift} value={c.giftWrapNote} muted />}
          {appliedDiscount > 0 && <SummaryRow label={lang === 'ar' ? 'الخصم' : 'Discount'} value={`-${t.currency} ${appliedDiscount}`} muted />}
          <SummaryRow label={c.tax} value={`${t.currency} ${tax}`} muted />
          <SummaryRow label={c.total} value={`${t.currency} ${total}`} strong />
        </div>
      </div>

      {/* sticky CTA */}
      <div style={{ position: 'sticky', bottom: 0, padding: '16px 24px 26px', background: 'linear-gradient(transparent, var(--paper) 22%)', backdropFilter: 'blur(4px)' }}>
        {orderError && <p className="body" style={{ color: 'var(--burgundy)', marginBottom: 10, textAlign: 'center' }}>{orderError}</p>}
        <button className="btn btn-burg btn-block" onClick={next} disabled={placing} style={{ opacity: placing ? 0.6 : 1 }}>
          {placing
            ? (lang === 'ar' ? 'جارٍ إرسال الطلب…' : 'Placing your order…')
            : (step === 2 ? (pay === 'cod' ? c.placeBtn : `${c.payBtn} · ${t.currency} ${total}`) : c.continueBtn)}
          <Icon.arrow className="arr" />
        </button>
      </div>
    </div>
  );
}

function CheckoutBar({ t, c, onBack }) {
  return (
    <div style={{ position: 'sticky', top: 0, zIndex: 30, background: 'rgba(251,248,243,.92)', backdropFilter: 'blur(16px)', borderBottom: '1px solid var(--line-2)' }}>
      <StatusBar dark={false} />
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '4px 18px 14px' }}>
        <button className="iconbtn" onClick={onBack} aria-label={t.dir === 'rtl' ? 'رجوع' : 'Back'} style={{ width: 42, height: 42, display: 'grid', placeItems: 'center' }}>
          <Icon.chevron style={{ transform: t.dir === 'rtl' ? 'none' : 'rotate(180deg)' }} />
        </button>
        <span style={{ fontFamily: t.dir === 'rtl' ? 'var(--arabic-display)' : 'var(--serif)', fontSize: 20, letterSpacing: t.dir === 'rtl' ? 0 : '.06em' }}>{c.title}</span>
        <div style={{ width: 42 }}></div>
      </div>
    </div>
  );
}

function SectionLabel({ n, title, lang, noNum }) {
  return (
    <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 20 }}>
      {!noNum && <span style={{ fontFamily: 'var(--serif)', fontSize: 13, color: 'var(--gold-deep-on-light)' }}>{n}</span>}
      <span style={{ fontFamily: lang === 'ar' ? 'var(--arabic-display)' : 'var(--serif)', fontSize: 21 }}>{title}</span>
    </div>
  );
}

/* AMBER & ZAFRAN — Payment return screen (Phase 3C-A).
   Where the browser lands after Network's hosted page, for card/Apple
   Pay. Deliberately NEUTRAL about success — the customer's browser
   redirect is never the authoritative source of the outcome (it can be
   skipped entirely if they close the tab, or arrive before Network's
   own server-to-server callback has even reached us yet — see
   docs/phase3c-a-payment-integration.md). It only ever asserts what's
   actually known for certain: "cancelled" (they tapped cancel on
   Network's page, unambiguous) vs. "we're confirming" (genuinely
   unknown from here, resolved separately, behind the scenes). */
function PaymentReturn({ t, lang, go, outcome, orderNumber }) {
  const cancelled = outcome === 'cancelled';
  return (
    <div style={{ minHeight: '100%', background: 'radial-gradient(120% 70% at 50% 0%, #2a1116, #160a0d)', color: 'var(--white)', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '70px 30px', textAlign: 'center' }}>
      <img src="assets/mark-gold.png" alt="" style={{ width: 90, marginBottom: 18 }} />
      <h1 className="sec-title" style={{ fontSize: 'clamp(36px,12vw,52px)', color: 'var(--white)' }}>
        {cancelled
          ? (lang === 'ar' ? 'لم تكتمل العملية' : 'Payment Not Completed')
          : (lang === 'ar' ? 'جارٍ تأكيد الدفع' : 'Confirming Your Payment')}
      </h1>
      <p className="body" style={{ color: 'rgba(253,253,253,.8)', maxWidth: 320, marginTop: 14 }}>
        {cancelled
          ? (lang === 'ar'
              ? 'تم إلغاء الدفع ولم يُخصم أي مبلغ. طلبك لم يُؤكَّد بعد — يمكنك المحاولة مرة أخرى من المتجر.'
              : 'The payment was cancelled and nothing was charged. Your order has not been confirmed — you’re welcome to try again from the Boutique.')
          : (lang === 'ar'
              ? 'نحن نتحقق من نتيجة الدفع الآن. سيتم تحديث حالة طلبك بمجرد تأكيدها من شبكة الدفع.'
              : 'We’re verifying the result with the payment network now. Your order’s status will update as soon as that’s confirmed.')}
      </p>
      {orderNumber && (
        <div style={{ marginTop: 24, padding: '14px 22px', border: '1px solid rgba(220,177,107,.25)' }}>
          <span style={{ fontFamily: 'var(--sans)', fontSize: 10, letterSpacing: '.18em', textTransform: 'uppercase', color: 'var(--rose)' }}>{t.co.orderNo}</span>
          <span style={{ fontFamily: 'var(--serif)', fontSize: 18, color: 'var(--gold)', marginInlineStart: 14 }}>{orderNumber}</span>
        </div>
      )}
      <button className="btn btn-gold" style={{ marginTop: 30 }} onClick={() => go('shop')}>{t.co.keepShopping}</button>
    </div>
  );
}

Object.assign(window, { Checkout, PaymentReturn });
