// Saraya Events — Checkout, Payment UI, and Order Confirmation.
//
// ⚠️ DEV NOTE — PAYMENT GATEWAY INTEGRATION
// This is a complete front-end payment FLOW only. No real charge is made.
// To go live, connect a UAE payment gateway where marked `=== GATEWAY ===`
// below (recommended: Stripe, Tap Payments, Telr, PayTabs, or Network
// International). Typically you would: create a payment intent / session on
// your backend, redirect or mount the gateway's hosted fields here, and on
// the success webhook mark the order `payment.status = 'paid'`. For now we
// simulate success for card/Apple Pay/Google Pay and mark transfer / COD /
// pay-on-confirmation as 'awaiting'.

const { useState: useStateCo } = React;

const PAYMENT_METHODS = [
  { id: 'card',     icon: 'credit-card',  label: { en: 'Credit / Debit Card', ar: 'بطاقة ائتمان / خصم' }, instant: true },
  { id: 'applepay', icon: 'apple',        label: { en: 'Apple Pay', ar: 'Apple Pay' }, instant: true },
  { id: 'googlepay',icon: 'smartphone',   label: { en: 'Google Pay', ar: 'Google Pay' }, instant: true },
  { id: 'transfer', icon: 'building-2',   label: { en: 'Bank Transfer', ar: 'تحويل بنكي' }, instant: false },
  { id: 'confirm',  icon: 'handshake',    label: { en: 'Pay on Confirmation', ar: 'الدفع عند التأكيد' }, instant: false },
  { id: 'cod',      icon: 'banknote',     label: { en: 'Cash on Delivery', ar: 'الدفع عند الاستلام' }, instant: false, physicalOnly: true },
];

function CheckoutPage() {
  const { t, lang } = useLang();
  const { go } = useNav();
  const cart = useCart();
  const ar = lang === 'ar';
  const T = cart.totals;
  const allDigital = T.allDigital;
  const hasPhysical = T.hasPhysical;
  const subItem = cart.items.find((x) => x.isSubscription);
  const subMeta = (subItem && subItem.meta) || {};

  const [f, setF] = useStateCo({ name: subMeta.owner || '', phone: subMeta.phone || '', email: subMeta.email || '', address: '', emirate: '', deliveryDate: '', deliveryTime: '', eventDate: '', eventTime: '', notes: '', giftMessage: '', recipientName: '', recipientPhone: '' });
  const [method, setMethod] = useStateCo('card');
  const [card, setCard] = useStateCo({ num: '', exp: '', cvc: '', name: '' });
  const [code, setCode] = useStateCo(cart.code || '');
  const [codeMsg, setCodeMsg] = useStateCo('');
  const [processing, setProcessing] = useStateCo(false);
  const [errors, setErrors] = useStateCo({});
  const set = (k, v) => setF((p) => Object.assign({}, p, { [k]: v }));

  if (cart.items.length === 0) {
    return <main style={{ paddingTop: 130, minHeight: '60vh' }}><Container narrow style={{ textAlign: 'center' }}>
      <Icon name="shopping-bag" size={44} stroke={1} style={{ color: 'var(--fg-muted)' }} />
      <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 30, fontWeight: 500, marginTop: 14 }}>{ar ? 'سلتك فارغة' : 'Your cart is empty'}</h1>
      <Button variant="primary" style={{ marginTop: 18 }} onClick={() => go('store')}>{ar ? 'تصفح السوق' : 'Browse Marketplace'}</Button>
    </Container></main>;
  }

  const applyCode = () => { const r = cart.applyCode(code); setCodeMsg(r.msg); };
  const methods = PAYMENT_METHODS.filter((m) => !(m.physicalOnly && !hasPhysical));

  const validate = () => {
    const e = {};
    if (!f.name.trim()) e.name = 1;
    if (!f.phone.trim()) e.phone = 1;
    if (!f.email.trim() || !/^[^@]+@[^@]+\.[^@]+$/.test(f.email)) e.email = 1;
    if (hasPhysical) { if (!f.address.trim()) e.address = 1; if (!f.emirate) e.emirate = 1; }
    if (method === 'card') { if (card.num.replace(/\s/g, '').length < 12) e.cardnum = 1; if (!card.exp) e.exp = 1; if (!card.cvc) e.cvc = 1; }
    setErrors(e); return Object.keys(e).length === 0;
  };

  const placeOrder = async () => {
    if (!validate()) { window.scrollTo({ top: 0, behavior: 'smooth' }); return; }
    setProcessing(true);
    const mObj = PAYMENT_METHODS.find((m) => m.id === method);

    // Stripe: card / Apple Pay / Google Pay redirect to Stripe Checkout when
    // a publishable key + backend are configured (admin → Payments). The order
    // is then created server-side by the webhook. If Stripe isn't configured,
    // we fall through to the built-in simulation so the demo still completes.
    if (mObj.instant && window.stripeConfigured && window.stripeConfigured()) {
      try {
        const res = await window.stripeCheckout({
          mode: subItem ? 'subscription' : 'payment',
          lineItems: window.buildStripeLineItems(cart.items),
          customer: { name: f.name, email: f.email, phone: f.phone },
          metadata: {
            email: f.email, name: f.name, phone: f.phone,
            allDigital: String(T.allDigital), hasSubscription: String(!!subItem),
            address: hasPhysical ? f.address : '', emirate: hasPhysical ? f.emirate : '',
          },
          successPath: 'store', cancelPath: 'checkout',
        });
        if (res && res.redirected) return;   // Stripe hosted page takes over
      } catch (e) {
        setProcessing(false);
        setErrors({ stripe: 1 });
        window.scrollTo({ top: 0, behavior: 'smooth' });
        return;
      }
    }

    // Simulated success (no Stripe yet) or non-instant methods (transfer / COD / pay-on-confirmation).
    setTimeout(() => {
      // Subscription: on successful payment, create it + generate access credentials.
      let access = null, subscriptionId = null;
      if (subItem) {
        const m = subItem.meta || {};
        const handle = (f.email.split('@')[0] || 'member').replace(/[^a-z0-9]/gi, '').toLowerCase();
        access = { username: handle + '-' + Math.random().toString(36).slice(2, 5), password: Math.random().toString(36).slice(2, 9) };
        try {
          const sub = window.SubsAPI.create({ owner: m.owner || f.name, business: m.business || f.name, phone: f.phone, email: f.email, category: m.category || '', desc: m.desc || '', status: 'active', payment: mObj.instant ? 'paid' : 'pending', access });
          subscriptionId = sub.id;
        } catch (e2) {}
        try { localStorage.setItem('saraya_member', JSON.stringify({ business: m.business || f.name, email: f.email, since: Date.now() })); } catch (e3) {}
      }
      const order = window.OrdersAPI.create({
        customer: { name: f.name, phone: f.phone, email: f.email },
        address: hasPhysical ? f.address : '', emirate: hasPhysical ? f.emirate : '',
        items: cart.items.map((it) => ({ id: it.id, name: it.name, price: it.price, qty: it.qty, digital: it.digital, isSubscription: it.isSubscription, meta: it.meta || null })),
        totals: { subtotal: T.subtotal, discount: T.discount, delivery: T.delivery, vat: T.vat, total: T.total, allDigital: T.allDigital },
        fulfilment: {
          deliveryDate: f.deliveryDate, deliveryTime: f.deliveryTime, eventDate: f.eventDate, eventTime: f.eventTime,
          giftMessage: f.giftMessage, recipientName: f.recipientName, recipientPhone: f.recipientPhone,
        },
        notes: f.notes,
        payment: { method, methodLabel: mObj.label.en, status: mObj.instant ? 'paid' : 'awaiting' },
        discountCode: cart.code || '',
        access, subscriptionId,
      });
      cart.clear();
      go('confirmation/' + order.id);
      setProcessing(false);
    }, 1400);
  };

  return (
    <main style={{ paddingTop: 96, background: 'var(--bg-canvas)' }}>
      <Section bg="canvas">
        <Container wide>
          <button onClick={() => go('store')} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--fg-secondary)', fontSize: 13.5, marginBottom: 14 }}><Icon name="arrow-left" size={16} />{ar ? 'متابعة التسوّق' : 'Continue shopping'}</button>
          <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(30px,4vw,44px)', fontWeight: 500 }}>{ar ? 'إتمام الشراء' : 'Checkout'}</h1>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginTop: 6, fontSize: 13, color: 'var(--fg-muted)' }}><Icon name="lock" size={14} style={{ color: 'var(--success)' }} />{ar ? 'دفع آمن ومشفّر' : 'Secure, encrypted checkout'}</div>

          <div className="saraya-checkout-grid" style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 32, marginTop: 28, alignItems: 'start' }}>
            {/* LEFT: forms */}
            <div style={{ display: 'grid', gap: 20 }}>
              <Panel title={ar ? 'بياناتك' : 'Your details'} icon="user">
                <div className="saraya-split" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                  <Field label={ar ? 'الاسم الكامل' : 'Full name'} error={errors.name}><TextInput value={f.name} onChange={(e) => set('name', e.target.value)} /></Field>
                  <Field label={ar ? 'رقم الجوال' : 'Mobile number'} error={errors.phone}><TextInput value={f.phone} onChange={(e) => set('phone', e.target.value)} placeholder="+971…" /></Field>
                </div>
                <Field label={ar ? 'البريد الإلكتروني' : 'Email'} error={errors.email}><TextInput type="email" value={f.email} onChange={(e) => set('email', e.target.value)} /></Field>
              </Panel>

              {hasPhysical && (
                <Panel title={ar ? 'التوصيل' : 'Delivery'} icon="truck">
                  <Field label={ar ? 'العنوان' : 'Delivery / setup address'} error={errors.address}><Textarea rows={2} value={f.address} onChange={(e) => set('address', e.target.value)} /></Field>
                  <div className="saraya-split" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                    <Field label={ar ? 'الإمارة' : 'Emirate / city'} error={errors.emirate}><Select value={f.emirate} onChange={(e) => set('emirate', e.target.value)}><option value="">{ar ? 'اختر' : 'Select'}</option>{window.SARAYA.STORE_CONFIG.emirates.map((c) => <option key={c} value={c}>{c}</option>)}</Select></Field>
                    <Field label={ar ? 'تاريخ التوصيل' : 'Delivery date'}><TextInput type="date" value={f.deliveryDate} onChange={(e) => set('deliveryDate', e.target.value)} /></Field>
                  </div>
                  <div className="saraya-split" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                    <Field label={ar ? 'وقت التوصيل' : 'Delivery time'}><Select value={f.deliveryTime} onChange={(e) => set('deliveryTime', e.target.value)}><option value="">{ar ? 'اختر' : 'Select'}</option>{window.SARAYA.STORE_CONFIG.timeSlots.map((s) => <option key={s} value={s}>{s}</option>)}</Select></Field>
                    <Field label={ar ? 'تاريخ الفعالية (إن وُجد)' : 'Event date (if any)'}><TextInput type="date" value={f.eventDate} onChange={(e) => set('eventDate', e.target.value)} /></Field>
                  </div>
                  <Field label={ar ? 'رسالة إهداء (اختياري)' : 'Gift message (optional)'}><Textarea rows={2} value={f.giftMessage} onChange={(e) => set('giftMessage', e.target.value)} /></Field>
                  <div className="saraya-split" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                    <Field label={ar ? 'اسم المستلِم (اختياري)' : 'Recipient name (optional)'}><TextInput value={f.recipientName} onChange={(e) => set('recipientName', e.target.value)} /></Field>
                    <Field label={ar ? 'جوال المستلِم (اختياري)' : 'Recipient mobile (optional)'}><TextInput value={f.recipientPhone} onChange={(e) => set('recipientPhone', e.target.value)} /></Field>
                  </div>
                </Panel>
              )}
              {subItem && (
                <Panel title={ar ? 'اشتراك المعرض الرقمي' : 'Virtual Showroom subscription'} icon="store">
                  <p style={{ fontSize: 13.5, color: 'var(--fg-secondary)', display: 'flex', alignItems: 'flex-start', gap: 8 }}><Icon name="info" size={15} style={{ color: 'var(--gold-deep)', flexShrink: 0, marginTop: 2 }} />{ar ? 'بعد الدفع، نُفعّل وصولك فورًا ونرسل بيانات الدخول إلى بريدك — وتحصل على وصول إلى متجر سرايا لإدارة معرضك.' : 'After payment we activate your access instantly and email your login — and you’ll get access to the Saraya store to manage your showroom.'}</p>
                  <div style={{ fontSize: 12.5, color: 'var(--fg-muted)', display: 'flex', alignItems: 'center', gap: 7 }}><Icon name="repeat" size={13} />{ar ? 'يتجدّد شهريًا بـ AED 99 ما لم يتم الإلغاء.' : 'Renews monthly at AED 99 unless cancelled.'}</div>
                </Panel>
              )}
              {allDigital && !subItem && (
                <Panel title={ar ? 'منتجات رقمية' : 'Digital delivery'} icon="download">
                  <p style={{ fontSize: 13.5, color: 'var(--fg-secondary)', display: 'flex', alignItems: 'center', gap: 8 }}><Icon name="info" size={15} style={{ color: 'var(--gold-deep)' }} />{ar ? 'لا يلزم عنوان. ستصلك روابط التحميل على بريدك فورًا بعد الدفع.' : 'No address needed. Download links are sent to your email instantly after payment.'}</p>
                </Panel>
              )}

              <Panel title={ar ? 'طريقة الدفع' : 'Payment method'} icon="credit-card">
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(min(150px,100%),1fr))', gap: 10 }}>
                  {methods.map((m) => (
                    <button key={m.id} onClick={() => setMethod(m.id)} style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '13px 14px', borderRadius: 12, cursor: 'pointer', textAlign: 'start', background: method === m.id ? 'var(--gold-tint)' : 'var(--white)', border: '1.5px solid ' + (method === m.id ? 'var(--gold)' : 'var(--line-strong)'), fontFamily: 'var(--font-body)', fontSize: 13.5, fontWeight: 500, color: 'var(--fg-primary)' }}>
                      <Icon name={m.icon} size={18} style={{ color: 'var(--gold-deep)' }} />{m.label[lang]}
                    </button>
                  ))}
                </div>
                {method === 'card' && (
                  <div style={{ marginTop: 16, display: 'grid', gap: 14 }}>
                    <Field label={ar ? 'رقم البطاقة' : 'Card number'} error={errors.cardnum}><TextInput value={card.num} onChange={(e) => setCard({ ...card, num: e.target.value })} placeholder="4242 4242 4242 4242" /></Field>
                    <div className="saraya-split saraya-card-3col" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 14 }}>
                      <Field label={ar ? 'الانتهاء' : 'Expiry'} error={errors.exp}><TextInput value={card.exp} onChange={(e) => setCard({ ...card, exp: e.target.value })} placeholder="MM/YY" /></Field>
                      <Field label="CVC" error={errors.cvc}><TextInput value={card.cvc} onChange={(e) => setCard({ ...card, cvc: e.target.value })} placeholder="123" /></Field>
                      <Field label={ar ? 'على البطاقة' : 'Name on card'}><TextInput value={card.name} onChange={(e) => setCard({ ...card, name: e.target.value })} /></Field>
                    </div>
                    <div style={{ fontSize: 11.5, color: 'var(--fg-muted)', display: 'flex', alignItems: 'center', gap: 6 }}><Icon name="lock" size={12} />{ar ? 'بيانات تجريبية — لن يتم أي خصم فعلي.' : 'Demo only — no real charge is made. Connect a gateway to go live.'}</div>
                  </div>
                )}
                {(method === 'applepay' || method === 'googlepay') && (
                  <div style={{ marginTop: 16, padding: '16px', borderRadius: 12, background: 'var(--espresso)', color: 'var(--ivory)', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, fontSize: 14.5, fontWeight: 600 }}>
                    <Icon name={method === 'applepay' ? 'apple' : 'smartphone'} size={20} />{ar ? 'ستظهر نافذة الدفع عند الطلب' : 'You’ll confirm in the ' + (method === 'applepay' ? 'Apple Pay' : 'Google Pay') + ' sheet'}
                  </div>
                )}
                {method === 'transfer' && <Note>{ar ? 'سنرسل تفاصيل الحساب البنكي بعد الطلب لإتمام التحويل.' : 'We’ll send our bank details after you place the order to complete the transfer.'}</Note>}
                {method === 'confirm' && <Note>{ar ? 'سيتواصل فريقنا لتأكيد الطلب وترتيب الدفع.' : 'Our team will contact you to confirm the order and arrange payment.'}</Note>}
                {method === 'cod' && <Note>{ar ? 'ادفع نقدًا عند استلام طلبك.' : 'Pay in cash when your order is delivered.'}</Note>}
              </Panel>
            </div>

            {/* RIGHT: summary */}
            <div style={{ position: 'sticky', top: 92 }}>
              <Panel title={ar ? 'ملخص الطلب' : 'Order summary'} icon="receipt">
                <div style={{ display: 'grid', gap: 10, marginBottom: 14 }}>
                  {cart.items.map((it) => (
                    <div key={it.id} style={{ display: 'flex', gap: 11, alignItems: 'center' }}>
                      <Img tone={it.tone} icon={it.digital ? 'download' : 'shopping-bag'} src={it.src} slot={'store:' + it.id} ratio="1/1" radius={9} plain style={{ width: 46, flexShrink: 0 }} />
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 13.5, fontWeight: 500, lineHeight: 1.25 }}>{it.name[lang] || it.name.en}</div>
                        <div style={{ fontSize: 12, color: 'var(--fg-muted)' }}>× {it.qty}{it.digital ? ' · ' + (ar ? 'رقمي' : 'digital') : ''}</div>
                      </div>
                      <div style={{ fontSize: 13.5, fontWeight: 600 }}>{money(it.price * it.qty)}</div>
                    </div>
                  ))}
                </div>
                {/* discount code */}
                <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
                  <TextInput value={code} onChange={(e) => setCode(e.target.value)} placeholder={ar ? 'رمز الخصم' : 'Discount code'} style={{ flex: 1 }} />
                  <Button variant="secondary" size="sm" onClick={applyCode}>{ar ? 'تطبيق' : 'Apply'}</Button>
                </div>
                {codeMsg && <div style={{ fontSize: 12, marginBottom: 10, color: cart.code ? 'var(--success)' : 'var(--error)' }}>{codeMsg}</div>}

                <Line label={ar ? 'المجموع الفرعي' : 'Subtotal'} value={money(T.subtotal)} />
                {T.discount > 0 && <Line label={ar ? 'الخصم' : 'Discount'} value={'− ' + money(T.discount)} accent />}
                {hasPhysical && <Line label={ar ? 'التوصيل' : 'Delivery'} value={T.delivery === 0 ? (ar ? 'مجاني' : 'Free') : money(T.delivery)} />}
                <Line label={ar ? 'ضريبة القيمة المضافة (٥٪)' : 'VAT (5%)'} value={money(T.vat)} />
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 10, paddingTop: 12, borderTop: '1px solid var(--line)' }}>
                  <span style={{ fontWeight: 600 }}>{ar ? 'الإجمالي' : 'Total'}</span>
                  <span style={{ fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 600 }}>{money(T.total)}</span>
                </div>

                {errors.stripe && <div style={{ background: 'var(--error-bg)', color: 'var(--error)', padding: '10px 14px', borderRadius: 10, fontSize: 12.5, marginTop: 12 }}>{ar ? 'تعذّر بدء الدفع عبر Stripe. تحقق من الإعدادات أو حاول مجددًا.' : 'Could not start Stripe payment. Check settings or try again.'}</div>}
                <Button variant="primary" full icon={processing ? null : 'lock'} onClick={placeOrder} disabled={processing} style={{ marginTop: 16 }}>
                  {processing ? (ar ? 'جارٍ المعالجة…' : 'Processing…') : (ar ? 'ادفع الآن · ' : 'Pay Now · ') + money(T.total)}
                </Button>
                <Button variant="whatsapp" size="sm" full icon="message-circle" href={window.SARAYA.waLink('Hello Saraya Events, I need help with my checkout.')} target="_blank" style={{ marginTop: 8 }}>{ar ? 'دعم عبر واتساب' : 'WhatsApp Support'}</Button>
                <div style={{ marginTop: 12, display: 'flex', gap: 10, justifyContent: 'center', alignItems: 'center', color: 'var(--fg-muted)' }}>
                  {['shield-check', 'credit-card', 'lock'].map((ic) => <Icon key={ic} name={ic} size={16} />)}
                  <span style={{ fontSize: 11 }}>{window.stripeConfigured && window.stripeConfigured() ? (ar ? 'دفع آمن عبر Stripe' : 'Secured by Stripe') : (ar ? 'دفع آمن' : 'Secured payment')}</span>
                </div>
              </Panel>
              <div style={{ textAlign: 'center', marginTop: 12, fontSize: 11.5, color: 'var(--fg-muted)' }}>
                <PolicyLinks />
              </div>
            </div>
          </div>
        </Container>
      </Section>
    </main>
  );
}

/* ---------------- Confirmation ---------------- */
function ConfirmationPage({ orderId }) {
  const { t, lang } = useLang();
  const { go } = useNav();
  const ar = lang === 'ar';
  const order = window.OrdersAPI.get(orderId);
  if (!order) return <main style={{ paddingTop: 130, minHeight: '50vh' }}><Container narrow style={{ textAlign: 'center' }}><p style={{ color: 'var(--fg-muted)' }}>{ar ? 'لم يتم العثور على الطلب.' : 'Order not found.'}</p><Button variant="primary" style={{ marginTop: 14 }} onClick={() => go('store')}>{ar ? 'المتجر' : 'Store'}</Button></Container></main>;
  const digitalItems = (order.items || []).filter((i) => i.digital && !i.isSubscription);
  const paid = order.payment && order.payment.status === 'paid';

  return (
    <main style={{ paddingTop: 110, background: 'var(--bg-canvas)' }}>
      <Section bg="canvas">
        <Container narrow>
          <div style={{ textAlign: 'center' }}>
            <span style={{ display: 'inline-flex', width: 72, height: 72, borderRadius: 999, alignItems: 'center', justifyContent: 'center', background: 'var(--success-bg)', color: 'var(--success)' }}><Icon name="check" size={38} /></span>
            <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(28px,4vw,40px)', fontWeight: 500, marginTop: 18 }}>{ar ? 'تم استلام طلبك' : 'Your order is confirmed'}</h1>
            <p style={{ fontSize: 15.5, color: 'var(--fg-secondary)', marginTop: 10, maxWidth: 520, marginInline: 'auto', lineHeight: 1.6 }}>{ar ? 'شكرًا لاختيارك سرايا للفعاليات. سيتواصل فريقنا معك قريبًا لتأكيد طلبك.' : 'Thank you for choosing Saraya Events. Our team will contact you shortly to confirm your order.'}</p>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 10, marginTop: 16, padding: '10px 18px', borderRadius: 999, background: 'var(--white)', border: '1px solid var(--line)' }}>
              <span style={{ fontSize: 13, color: 'var(--fg-muted)' }}>{ar ? 'رقم الطلب' : 'Order number'}</span>
              <span style={{ fontFamily: 'var(--font-display)', fontSize: 19, fontWeight: 600 }}>{order.number}</span>
              <StatusPill status={order.status} small />
            </div>
          </div>

          {order.access && (
            <Panel title={ar ? 'وصولك إلى المعرض الرقمي' : 'Your Virtual Showroom access'} icon="key-round" style={{ marginTop: 28 }}>
              <p style={{ fontSize: 13.5, color: 'var(--fg-secondary)', marginBottom: 14 }}>{ar ? 'تم تفعيل اشتراكك. استخدم بيانات الدخول التالية لإدارة معرضك والوصول إلى متجر سرايا. أرسلنا نسخة إلى بريدك.' : 'Your subscription is active. Use the login below to manage your showroom and access the Saraya store. A copy has been emailed to you.'}</p>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <div style={{ padding: '12px 14px', background: 'var(--bg-tint)', borderRadius: 10 }}>
                  <div style={{ fontSize: 11, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>{ar ? 'اسم المستخدم' : 'Username'}</div>
                  <div style={{ fontFamily: 'var(--font-body)', fontSize: 15, fontWeight: 600, marginTop: 3, wordBreak: 'break-all' }}>{order.access.username}</div>
                </div>
                <div style={{ padding: '12px 14px', background: 'var(--bg-tint)', borderRadius: 10 }}>
                  <div style={{ fontSize: 11, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>{ar ? 'كلمة المرور' : 'Temporary password'}</div>
                  <div style={{ fontFamily: 'var(--font-body)', fontSize: 15, fontWeight: 600, marginTop: 3 }}>{order.access.password}</div>
                </div>
              </div>
              <Button variant="gold" full icon="store" style={{ marginTop: 16 }} onClick={() => go('store')}>{ar ? 'ادخل إلى متجر سرايا' : 'Access the Saraya Store'}</Button>
              <p style={{ fontSize: 11.5, color: 'var(--fg-muted)', marginTop: 10, display: 'flex', alignItems: 'center', gap: 6 }}><Icon name="shield-check" size={12} />{ar ? 'يُنصح بتغيير كلمة المرور بعد أول دخول.' : 'For your security, change this password after your first sign-in.'}</p>
            </Panel>
          )}

          {digitalItems.length > 0 && (
            <Panel title={ar ? 'منتجاتك الرقمية' : 'Your digital products'} icon="download" style={{ marginTop: 28 }}>
              <p style={{ fontSize: 13, color: 'var(--fg-muted)', marginBottom: 12 }}>{ar ? 'متاحة للتحميل فورًا، ويمكنك العودة لهذه الصفحة في أي وقت.' : 'Available to download now — you can return to this page anytime.'}</p>
              <div style={{ display: 'grid', gap: 10 }}>
                {digitalItems.map((it) => <DigitalDownloadRow key={it.id} item={it} lang={lang} ar={ar} />)}
              </div>
            </Panel>
          )}

          <Panel title={ar ? 'تفاصيل الطلب' : 'Order details'} icon="receipt" style={{ marginTop: 20 }}>
            <KV k={ar ? 'الاسم' : 'Name'} v={order.customer.name} />
            <KV k={ar ? 'الجوال' : 'Mobile'} v={order.customer.phone} />
            <KV k={ar ? 'البريد' : 'Email'} v={order.customer.email} />
            {order.emirate && <KV k={ar ? 'الإمارة' : 'Emirate'} v={order.emirate} />}
            {order.address && <KV k={ar ? 'العنوان' : 'Address'} v={order.address} />}
            {order.fulfilment && order.fulfilment.deliveryDate && <KV k={ar ? 'التوصيل' : 'Delivery'} v={order.fulfilment.deliveryDate + ' · ' + (order.fulfilment.deliveryTime || '')} />}
            <KV k={ar ? 'طريقة الدفع' : 'Payment method'} v={order.payment.methodLabel} />
            <KV k={ar ? 'حالة الدفع' : 'Payment status'} v={paid ? (ar ? 'مدفوع' : 'Paid') : (ar ? 'بانتظار التأكيد' : 'Awaiting confirmation')} />
            <div style={{ marginTop: 12, paddingTop: 12, borderTop: '1px solid var(--line)' }}>
              {(order.items || []).map((it) => (
                <div key={it.id} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5, padding: '5px 0' }}><span>{(it.name[lang] || it.name.en)} × {it.qty}</span><span style={{ fontWeight: 600 }}>{money(it.price * it.qty)}</span></div>
              ))}
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, paddingTop: 8, borderTop: '1px solid var(--line)', fontWeight: 700, fontSize: 16 }}><span>{ar ? 'الإجمالي' : 'Total'}</span><span>{money(order.totals.total)}</span></div>
            </div>
          </Panel>

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(160px,1fr))', gap: 10, marginTop: 22 }}>
            <Button variant="secondary" icon="file-text" onClick={() => printInvoice(order, lang)}>{ar ? 'تحميل الفاتورة' : 'Download Invoice'}</Button>
            <Button variant="whatsapp" icon="message-circle" href={window.SARAYA.waLink('Hello Saraya Events, regarding my order ' + order.number + '…')} target="_blank">{ar ? 'تواصل عبر واتساب' : 'WhatsApp Contact'}</Button>
            <Button variant="primary" icon="store" onClick={() => go('store')}>{ar ? 'العودة للمتجر' : 'Back to Store'}</Button>
          </div>
        </Container>
      </Section>
    </main>
  );
}

function DigitalDownloadRow({ item, lang, ar }) {
  const [busy, setBusy] = useStateCo(false);
  const dl = async () => {
    setBusy(true);
    const ok = await window.downloadDigitalFile(item.id, (item.name.en || 'download'));
    setBusy(false);
    if (!ok) window.open(window.SARAYA.waLink('Hello Saraya Events, please send my download for ' + (item.name.en) + '.'), '_blank');
  };
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', background: 'var(--white)', border: '1px solid var(--line)', borderRadius: 12 }}>
      <Icon name="file-down" size={20} style={{ color: 'var(--gold-deep)' }} />
      <div style={{ flex: 1 }}><div style={{ fontSize: 14, fontWeight: 500 }}>{item.name[lang] || item.name.en}</div><div style={{ fontSize: 11.5, color: 'var(--fg-muted)' }}>{ar ? 'تحميل فوري' : 'Instant download'}</div></div>
      <Button variant="primary" size="sm" icon="download" onClick={dl} disabled={busy}>{busy ? '…' : (ar ? 'تحميل' : 'Download')}</Button>
    </div>
  );
}

/* invoice — opens a printable window (Save as PDF) */
function printInvoice(order, lang) {
  const C = window.SARAYA.CONTACT;
  const rows = (order.items || []).map((it) => `<tr><td style="padding:8px 0;border-bottom:1px solid #eee">${it.name.en} × ${it.qty}</td><td style="padding:8px 0;border-bottom:1px solid #eee;text-align:right">${window.money(it.price * it.qty)}</td></tr>`).join('');
  const T = order.totals;
  const html = `<!doctype html><html><head><meta charset="utf-8"><title>Invoice ${order.number}</title>
  <style>body{font-family:Georgia,serif;color:#2A1F1A;max-width:640px;margin:40px auto;padding:0 24px}h1{font-size:28px;margin:0}small{color:#8a7d70}table{width:100%;border-collapse:collapse;margin-top:20px}.tot{display:flex;justify-content:space-between;padding:4px 0}.tot.b{font-weight:700;font-size:18px;border-top:2px solid #2A1F1A;margin-top:8px;padding-top:8px}</style></head>
  <body><div style="display:flex;justify-content:space-between;align-items:flex-start"><div><h1>Saraya Events</h1><small>سرايا للفعاليات · ${C.city}</small></div><div style="text-align:right"><div style="font-size:20px;font-weight:700">INVOICE</div><small>${order.number}<br>${new Date(order.createdAt).toLocaleDateString()}</small></div></div>
  <div style="margin-top:24px"><strong>Bill to</strong><br>${order.customer.name}<br>${order.customer.phone} · ${order.customer.email}${order.address ? '<br>' + order.address + ', ' + order.emirate : ''}</div>
  <table><tbody>${rows}</tbody></table>
  <div style="margin-top:16px"><div class="tot"><span>Subtotal</span><span>${window.money(T.subtotal)}</span></div>${T.discount > 0 ? `<div class="tot"><span>Discount</span><span>− ${window.money(T.discount)}</span></div>` : ''}${T.delivery ? `<div class="tot"><span>Delivery</span><span>${window.money(T.delivery)}</span></div>` : ''}<div class="tot"><span>VAT (5%)</span><span>${window.money(T.vat)}</span></div><div class="tot b"><span>Total</span><span>${window.money(T.total)}</span></div></div>
  <p style="margin-top:28px;color:#8a7d70;font-size:13px">Payment: ${order.payment.methodLabel} — ${order.payment.status === 'paid' ? 'Paid' : 'Awaiting confirmation'}</p>
  <p style="color:#8a7d70;font-size:13px">Thank you for choosing Saraya Events.</p>
  <script>window.onload=function(){window.print()}<\/script></body></html>`;
  const w = window.open('', '_blank'); if (w) { w.document.write(html); w.document.close(); }
}

/* ---------------- shared bits ---------------- */
function Panel({ title, icon, children, style }) {
  return (
    <div style={{ background: 'var(--white)', border: '1px solid var(--line)', borderRadius: 16, padding: '20px 22px', boxShadow: 'var(--shadow-soft)', ...style }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 16 }}>
        {icon && <Icon name={icon} size={18} style={{ color: 'var(--gold-deep)' }} />}
        <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 500 }}>{title}</h3>
      </div>
      <div style={{ display: 'grid', gap: 14 }}>{children}</div>
    </div>
  );
}
function Line({ label, value, accent }) {
  return <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5, padding: '3px 0', color: accent ? 'var(--success)' : 'var(--fg-secondary)' }}><span>{label}</span><span style={{ fontWeight: 500 }}>{value}</span></div>;
}
function Note({ children }) {
  return <div style={{ marginTop: 14, padding: '12px 14px', borderRadius: 10, background: 'var(--bg-tint)', fontSize: 13, color: 'var(--fg-secondary)', display: 'flex', gap: 8 }}><Icon name="info" size={15} style={{ color: 'var(--gold-deep)', flexShrink: 0, marginTop: 1 }} />{children}</div>;
}
function PolicyLinks() {
  const { lang } = useLang(); const ar = lang === 'ar';
  const items = ar ? ['سياسة الاسترجاع', 'الشروط والأحكام', 'الخصوصية'] : ['Refund policy', 'Terms', 'Privacy'];
  return <span>{items.map((x, i) => <React.Fragment key={i}>{i > 0 && ' · '}<a href={window.SARAYA.waLink('Hello Saraya Events, I have a question about your ' + x + '.')} target="_blank" rel="noopener" style={{ color: 'var(--fg-muted)', textDecoration: 'underline' }}>{x}</a></React.Fragment>)}</span>;
}

Object.assign(window, { CheckoutPage, ConfirmationPage, PolicyLinks });
