// 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;

// Only methods with active !== false are shown at checkout. Card runs through
// Stripe Checkout, which itself offers Apple Pay / Google Pay to eligible devices
// (so separate buttons are redundant). Tabby/Tamara are NOT integrated — they must
// never be selectable, as they would create an UNPAID order. Flip active to true
// only once a method is genuinely wired end-to-end.
const PAYMENT_METHODS = [
  { id: 'card',     icon: 'credit-card',  label: { en: 'Credit / Debit Card', ar: 'بطاقة ائتمان / خصم' }, instant: true,  active: true },
  { id: 'applepay', icon: 'apple',        label: { en: 'Apple Pay', ar: 'Apple Pay' }, instant: true,  active: false },
  { id: 'googlepay',icon: 'smartphone',   label: { en: 'Google Pay', ar: 'Google Pay' }, instant: true,  active: false },
  { id: 'tabby',    icon: 'calendar',     label: { en: 'Tabby — Pay in 4', ar: 'تابي — ادفع على 4 دفعات' }, instant: false, active: false },
  { id: 'tamara',   icon: 'layers',       label: { en: 'Tamara — Split in 3', ar: 'تمارا — قسّم على 3 دفعات' }, instant: false, active: false },
];

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 hasRental = cart.items.some((x) => x.meta && x.meta.rental);
  const hasService = cart.items.some((x) => x.meta && x.meta.serviceBooking);

  const [f, setF] = useStateCo({ name: subMeta.owner || '', phone: subMeta.phone || '', email: subMeta.email || '', address: '', emirate: '', deliveryDate: '', deliveryTime: '', eventDate: '', eventTime: '', rentalStart: '', rentalEnd: '', svcEventDate: '', svcEventTime: '', svcGuests: '', svcVenue: '', 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 }));

  React.useEffect(() => {
    try {
      if (!cart.items || cart.items.length === 0) return;
      window.sarayaTrack && window.sarayaTrack('begin_checkout', {
        currency: 'AED', value: T.total,
        items: cart.items.map((it) => ({ item_id: it.id, item_name: (it.name && (it.name.en || it.name)) || '', price: Number(it.price) || 0, quantity: it.qty })),
      });
    } catch (e) {}
  }, []);

  // Prefill service/rental dates chosen on the listing page.
  React.useEffect(() => {
    const svc = cart.items.find((x) => x.meta && x.meta.serviceBooking && x.meta.eventDate);
    if (svc && svc.meta) {
      setF((p) => Object.assign({}, p, {
        svcEventDate: p.svcEventDate || svc.meta.eventDate || '',
        svcEventTime: p.svcEventTime || svc.meta.eventTime || '',
        svcGuests: p.svcGuests || (svc.meta.guests != null && svc.meta.guests !== '' ? String(svc.meta.guests) : ''),
        svcVenue: p.svcVenue || svc.meta.venue || '',
      }));
    }
    const rnt = cart.items.find((x) => x.meta && x.meta.rental && x.meta.rentalStart);
    if (rnt && rnt.meta) {
      setF((p) => Object.assign({}, p, {
        rentalStart: p.rentalStart || rnt.meta.rentalStart || '',
        rentalEnd: p.rentalEnd || rnt.meta.rentalEnd || '',
      }));
    }
  }, []);

  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.active !== false && !(m.physicalOnly && !hasPhysical));

  const validate = () => {
    const e = {};
    if (!f.name.trim()) e.name = 1;
    if (f.phone.replace(/\D/g, '').length < 7) 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 (!f.deliveryDate) e.deliveryDate = 1; if (!f.deliveryTime) e.deliveryTime = 1; }
    if (hasRental) { if (!f.rentalStart) e.rentalStart = 1; if (!f.rentalEnd) e.rentalEnd = 1; if (f.rentalStart && f.rentalEnd && f.rentalEnd < f.rentalStart) e.rentalEnd = 1;
      const badRental = cart.items.some((it) => it.meta && it.meta.rental && (!(Number(it.meta.perDay) > 0) || !(Number(it.meta.appliedDays) >= 1) || !(Number(it.qty) >= (Number(it.meta.minQty) || 1))));
      if (badRental) e.rentalItem = 1; }
    if (hasService) { if (!f.svcEventDate) e.svcEventDate = 1; if (!String(f.svcEventTime).trim()) e.svcEventTime = 1; if (!String(f.svcGuests).trim() || Number(f.svcGuests) < 1) e.svcGuests = 1; if (!String(f.svcVenue).trim()) e.svcVenue = 1; }
    // On-site card fields only exist in demo mode; with live Stripe the card is
    // entered on Stripe's page, so don't require them here.
    if (method === 'card' && !(window.stripeConfigured && window.stripeConfigured())) { 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);

    // Guard: re-check the chosen service date is still bookable (blocks lead-time,
    // blocked dates, non-working days and capacity — prevents a double-booking
    // between opening the page and paying).
    if (hasService && window.SarayaService && window.SarayaService.availability) {
      const svc = cart.items.find((x) => x.meta && x.meta.serviceBooking);
      const vid = svc && svc.meta && svc.meta.vendorId;
      const lead = (svc && svc.meta && Number(svc.meta.leadDays)) || 0;
      if (vid && f.svcEventDate) {
        const ok = await window.SarayaService.availability.isBookable(vid, f.svcEventDate, lead);
        if (!ok) {
          setProcessing(false);
          setErrors({ svcEventDate: 1, svcUnavailable: 1 });
          window.scrollTo({ top: 0, behavior: 'smooth' });
          return;
        }
      }
    }

    // Guard: re-check every rental line's date range is still available for its qty.
    if (hasRental && window.SarayaService && window.SarayaService.rentals && window.SarayaService.rentals.rangeAvailable && f.rentalStart && f.rentalEnd) {
      for (const it of cart.items) {
        if (it.meta && it.meta.rental && it.meta.rentalId) {
          const ok = await window.SarayaService.rentals.rangeAvailable(it.meta.rentalId, f.rentalStart, f.rentalEnd, Number(it.qty) || 1);
          if (!ok) {
            setProcessing(false);
            setErrors({ rentalStart: 1, rentalEnd: 1, rentalUnavailable: 1 });
            window.scrollTo({ top: 0, behavior: 'smooth' });
            return;
          }
        }
      }
    }

    const mObj = PAYMENT_METHODS.find((m) => m.id === method);

    // Vendor package subscription (dashboard "add to cart" flow): charge the real
    // recurring Stripe subscription. Scoped to sub items that carry a packageLevel
    // — the showroom lead flow (no packageLevel) and every product / rental /
    // service checkout are left completely untouched.
    if (subItem && subMeta.packageLevel && mObj.instant && window.stripeConfigured && window.stripeConfigured()) {
      try {
        const res = await window.stripeSubscribe({
          packageLevel: subMeta.packageLevel,
          billingInterval: subMeta.interval === 'annual' ? 'year' : 'month',
          successPath: 'vendor-dashboard',
          cancelPath: 'checkout',
        });
        if (res && res.redirected) { try { cart.clear(); } catch (_) {} return; }
        // simulated (Stripe not configured) → fall through to the request-recording flow
      } catch (e) {
        setProcessing(false);
        setErrors({ stripe: 1 });
        window.scrollTo({ top: 0, behavior: 'smooth' });
        return;
      }
    }

    // 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.
    // Real card payment via Stripe Checkout (products / rentals / services).
    // The Supabase edge function creates the order (+ items) with exact totals
    // and the Stripe session; the stripe-webhook records the payment and marks
    // the order paid. Subscriptions are NOT charged here (they record a
    // request); vendor subscriptions have their own Stripe flow.
    if (mObj.instant && !subItem && window.stripeConfigured && window.stripeConfigured()) {
      try {
        const _typeOf = (it) => (it.meta && it.meta.rental) ? 'rental' : (it.meta && it.meta.serviceBooking) ? 'service' : 'product';
        const _types = Array.from(new Set(cart.items.map(_typeOf)));
        const res = await window.stripeCheckout({
          lineItems: window.buildStripeLineItems(cart.items),   // raw product lines (fils)
          customer: { name: f.name, email: f.email, phone: f.phone },
          totals: { subtotal: T.subtotal, delivery: T.delivery, vat: T.vat, discount: T.discount, total: T.total },
          metadata: {
            name: f.name, email: f.email, phone: f.phone,
            address: hasPhysical ? f.address : '', emirate: hasPhysical ? f.emirate : '',
            discountCode: cart.code || '',
            order_type: _types.length === 1 ? _types[0] : 'product',
            rental_start: hasRental ? f.rentalStart : '', rental_end: hasRental ? f.rentalEnd : '',
            service_event_date: hasService ? f.svcEventDate : '', service_event_time: hasService ? f.svcEventTime : '', guest_count: hasService ? f.svcGuests : '', venue: hasService ? f.svcVenue : '',
            notes: [f.notes || '', cart.items.filter((it) => it.meta && it.meta.serviceBooking).map((it) => { const full = Number(it.meta.fullPrice) || 0; const paid = Number(it.price) || 0; const nm = (it.meta.serviceName && (it.meta.serviceName.en || it.meta.serviceName)) || 'Service'; return nm + ': ' + (it.meta.depositPct || 10) + '% deposit AED ' + paid.toFixed(2) + ' paid; full AED ' + full.toFixed(2) + '; balance AED ' + Math.max(0, full - paid).toFixed(2) + ' due.'; }).join(' ')].filter(Boolean).join(' — '),
          },
        });
        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(async () => {
      // 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) {}

        // Persist the subscription signup so Saraya actually receives it — it
        // was localStorage-only before. subscriptions.INSERT is admin-only by
        // design (admins provision after payment), so we record it as a request
        // in `leads` rather than minting an unpaid "active" subscription.
        if (window.SarayaDB && window.saveLead) {
          let subRes = { ok: false };
          try {
            subRes = await window.saveLead({
              leadType: 'vendor_application', source: 'showroom_subscription',
              name: (m.business || f.name), phone: f.phone, email: f.email,
              message: 'Virtual Showroom subscription request: ' + ((subItem.name && (subItem.name.en || subItem.name)) || 'plan') + ' — AED ' + subItem.price + '/mo. Payment not collected yet; please provision after payment.',
            });
          } catch (e5) { subRes = { ok: false, error: e5 }; }
          if (!subRes.ok && !subRes.fallback) {
            setProcessing(false);
            setErrors({ order: 1 });
            window.scrollTo({ top: 0, behavior: 'smooth' });
            return;   // real failure → don't claim success; the signup wasn't received
          }
        }
      }

      // Persist the order to Supabase so Saraya actually receives it (source of
      // truth for Staff Operations) — checkout previously wrote only localStorage.
      // Nothing is charged in simulated mode, so the payment stays PENDING; a real
      // Stripe webhook is the only thing that may later mark it paid. Subscriptions
      // use their own flow above and are not double-persisted here.
      let dbRef = null;
      if (!subItem && window.SarayaDB) {
        // Type the order + each item by what's actually in the cart so rentals
        // and service bookings aren't miscategorised as products in Staff Ops.
        const itemTypeOf = (it) => (it.meta && it.meta.rental) ? 'rental' : (it.meta && it.meta.serviceBooking) ? 'service' : 'product';
        const _types = Array.from(new Set(cart.items.map(itemTypeOf)));
        // orders.type allows product|rental|service (no "mixed"); for a mixed
        // cart use the first item's type — each item still carries its own type.
        const orderPayload = {
          type: _types.length === 1 ? _types[0] : itemTypeOf(cart.items[0]),
          subtotal: T.subtotal, discount_amount: T.discount, delivery_fee: T.delivery,
          vat_amount: T.vat, total_amount: T.total,
          delivery_address: hasPhysical ? { emirate: f.emirate, street: f.address } : null,
          notes: f.notes || '',
          guest_name: f.name, guest_email: f.email, guest_phone: f.phone,
          payment_method: method,
          items: cart.items.map((it) => {
            // Route the real UUID to the matching column so the order attributes
            // to the right vendor (drives commission + payout in create_guest_order).
            const _t = itemTypeOf(it);
            const _ref = (it.meta && it.meta.serviceId) || (it.meta && it.meta.rentalId) || it.id;
            const _uuid = (typeof _ref === 'string' && _ref.length === 36) ? _ref : null;
            return {
              item_type: _t,
              product_id: _t === 'product' ? _uuid : null,
              rental_id: _t === 'rental' ? _uuid : null,
              service_id: _t === 'service' ? _uuid : null,
              name_en: (it.name && (it.name.en || it.name)) || 'Item',
              unit_price: it.price, quantity: it.qty, line_total: it.price * it.qty,
            };
          }),
        };
        try {
          const { data: created, error } = await window.SarayaDB.rpc('create_guest_order', { p: orderPayload });
          if (error || !created) {
            setProcessing(false);
            setErrors({ order: 1 });
            window.scrollTo({ top: 0, behavior: 'smooth' });
            return;   // real failure → keep the form open, do NOT show a false success
          }
          const rec = Array.isArray(created) ? created[0] : created;
          dbRef = rec && rec.reference;
        } catch (e4) {
          setProcessing(false);
          setErrors({ order: 1 });
          window.scrollTo({ top: 0, behavior: 'smooth' });
          return;
        }
      }

      const orderInput = {
        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,
        // Honest: never "paid" in simulated mode — only a real charge may set paid.
        payment: { method, methodLabel: mObj.label.en, status: 'awaiting' },
        discountCode: cart.code || '',
        access, subscriptionId,
      };
      if (dbRef) orderInput.number = dbRef;   // keep the customer's ref == the DB reference
      const order = window.OrdersAPI.create(orderInput);
      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'} required error={errors.name}><TextInput value={f.name} onChange={(e) => set('name', e.target.value)} /></Field>
                  <Field label={ar ? 'رقم الجوال' : 'Mobile number'} required error={errors.phone}><TextInput value={f.phone} onChange={(e) => set('phone', e.target.value)} placeholder="+971…" /></Field>
                </div>
                <Field label={ar ? 'البريد الإلكتروني' : 'Email'} required 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'} required 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'} required 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'} required error={errors.deliveryDate}><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'} required error={errors.deliveryTime}><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>
              )}
              {(hasRental || hasService) && (
                <Panel title={ar ? 'تواريخ الحجز' : 'Booking dates'} icon="calendar">
                  {hasRental && (
                    <div style={{ display: 'grid', gap: 10 }}>
                      {errors.rentalUnavailable ? (
                        <div style={{ padding: '10px 12px', borderRadius: 10, background: '#FEF2F2', border: '1px solid #FCA5A5', color: '#B91C1C', fontSize: 13, display: 'flex', alignItems: 'center', gap: 8 }}>
                          <Icon name="alert-circle" size={15} />{ar ? 'تواريخ الإيجار لم تعد متاحة بالكامل. يرجى تعديلها.' : 'Those rental dates are no longer fully available. Please adjust them.'}
                        </div>
                      ) : null}
                      <div className="saraya-split" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                        <Field label={ar ? 'بداية الإيجار' : 'Rental start'} required error={errors.rentalStart}><TextInput type="date" value={f.rentalStart} onChange={(e) => set('rentalStart', e.target.value)} /></Field>
                        <Field label={ar ? 'نهاية الإيجار' : 'Rental end'} required error={errors.rentalEnd}><TextInput type="date" value={f.rentalEnd} onChange={(e) => set('rentalEnd', e.target.value)} /></Field>
                      </div>
                    </div>
                  )}
                  {hasService && (
                    <div style={{ display: 'grid', gap: 14, marginTop: hasRental ? 14 : 0 }}>
                      {errors.svcUnavailable ? (
                        <div style={{ padding: '10px 12px', borderRadius: 10, background: '#FEF2F2', border: '1px solid #FCA5A5', color: '#B91C1C', fontSize: 13, display: 'flex', alignItems: 'center', gap: 8 }}>
                          <Icon name="alert-circle" size={15} />{ar ? 'التاريخ المختار لم يعد متاحاً لدى المورّد. يرجى اختيار تاريخ آخر.' : 'That date is no longer available with the vendor. Please choose another date.'}
                        </div>
                      ) : null}
                      <div className="saraya-split" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                        <Field label={ar ? 'تاريخ الفعالية' : 'Event date'} required error={errors.svcEventDate}><TextInput type="date" value={f.svcEventDate} onChange={(e) => set('svcEventDate', e.target.value)} /></Field>
                        <Field label={ar ? 'وقت الفعالية' : 'Event time'} required error={errors.svcEventTime}><TextInput value={f.svcEventTime} onChange={(e) => set('svcEventTime', e.target.value)} placeholder={ar ? 'مثال: 7 مساءً' : 'e.g. 7 PM'} /></Field>
                      </div>
                      <div className="saraya-split" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                        <Field label={ar ? 'عدد الضيوف' : 'Guest count'} required error={errors.svcGuests}><TextInput type="number" min="1" value={f.svcGuests} onChange={(e) => set('svcGuests', e.target.value)} /></Field>
                        <Field label={ar ? 'المكان' : 'Venue'} required error={errors.svcVenue}><TextInput value={f.svcVenue} onChange={(e) => set('svcVenue', e.target.value)} /></Field>
                      </div>
                    </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} />{(() => {
                    const isY = subMeta.interval === 'annual';
                    const amt = Number(subItem.price) || 0;
                    return ar
                      ? ('يتجدّد ' + (isY ? 'سنويًا' : 'شهريًا') + ' بـ AED ' + amt.toLocaleString() + ' ما لم يتم الإلغاء.')
                      : ('Renews ' + (isY ? 'annually' : 'monthly') + ' at AED ' + amt.toLocaleString() + ' 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>
                  <p style={{ fontSize: 12, color: 'var(--fg-muted)', lineHeight: 1.5, marginTop: 8 }}>{ar ? 'قد لا تكون المنتجات الرقمية قابلة للاسترداد بعد التنزيل، إلا إذا كان الملف معيباً أو غير مطابق للوصف.' : 'Digital products may not be refundable after download unless defective or not as described.'}</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' && (window.stripeConfigured && window.stripeConfigured() ? (
                  // Live Stripe: card is collected on Stripe's secure page — no on-site card fields.
                  <div style={{ marginTop: 16, padding: '12px 14px', borderRadius: 10, background: 'var(--bg-tint)', fontSize: 12.5, color: 'var(--fg-secondary)', display: 'flex', alignItems: 'center', gap: 8 }}>
                    <Icon name="lock" size={14} style={{ color: 'var(--gold-deep)', flexShrink: 0 }} />{ar ? 'ستُدخِل بيانات بطاقتك بأمان على صفحة الدفع (Stripe) في الخطوة التالية.' : 'You’ll enter your card securely on the next step (Stripe).'}
                  </div>
                ) : (
                  <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 === 'tabby' && <Note>{ar ? 'قسّم قيمة طلبك على 4 دفعات بدون فوائد مع تابي.' : 'Split your order into 4 interest-free payments with Tabby.'}</Note>}
                {method === 'tamara' && <Note>{ar ? 'قسّم قيمة طلبك على 3 دفعات بدون فوائد مع تمارا.' : 'Split your order into 3 interest-free payments with Tamara.'}</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.meta && it.meta.rental ? (' · ' + (it.meta.appliedDays || 1) + (ar ? ' أيام' : ' days') + ' @ ' + money(it.meta.perDay || 0) + (ar ? '/يوم' : '/day')) : ''}{it.digital ? ' · ' + (ar ? 'رقمي' : 'digital') : ''}</div>
                        {it.meta && it.meta.rental && it.meta.appliedDays > (it.meta.selectedDays || 1) ? <div style={{ fontSize: 11, color: 'var(--gold-deep)', marginTop: 1 }}>{ar ? ('حد أدنى ' + it.meta.minDays + ' أيام مطبّق') : (it.meta.minDays + '-day minimum applied')}</div> : null}
                      </div>
                      <div style={{ fontSize: 13.5, fontWeight: 600 }}>{money(it.price * it.qty)}</div>
                    </div>
                  ))}
                </div>
                {errors.rentalItem ? <div style={{ padding: '8px 12px', borderRadius: 8, background: 'var(--error-bg,#fef2f2)', color: 'var(--error,#dc2626)', fontSize: 12.5, marginBottom: 10 }}>{ar ? 'يرجى مراجعة عنصر التأجير قبل الدفع. السعر أو مدة الإيجار مفقودة.' : 'Please review this rental item before checkout. Price or rental duration is missing.'}</div> : null}
                {/* 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>}
                {errors.order && <div style={{ background: 'var(--error-bg)', color: 'var(--error)', padding: '10px 14px', borderRadius: 10, fontSize: 12.5, marginTop: 12 }}>{ar ? 'تعذّر إرسال طلبك. يرجى المحاولة مرة أخرى أو التواصل عبر واتساب.' : 'We couldn’t submit your order. Please try again, or reach us on WhatsApp.'}</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);
  React.useEffect(() => {
    try {
      if (!order) return;
      var key = 'saraya_purchase_tracked_' + order.id;
      if (sessionStorage.getItem(key)) return;
      sessionStorage.setItem(key, '1');
      var T2 = order.totals || {};
      window.sarayaTrack && window.sarayaTrack('purchase', {
        transaction_id: order.number || order.id,
        currency: 'AED', value: (T2.total != null ? T2.total : 0),
        tax: T2.vat, shipping: T2.delivery,
        items: (order.items || []).map((it) => ({ item_id: it.id, item_name: (it.name && (it.name.en || it.name)) || '', price: Number(it.price) || 0, quantity: it.qty })),
      });
    } catch (e) {}
  }, [order && order.id]);
  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 to confirm your order and arrange payment.'}</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>
              {/* Honest badge: the order is received, not paid (no charge in simulated mode). */}
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 12, fontWeight: 600, padding: '3px 10px', borderRadius: 999, background: 'var(--success-bg)', color: 'var(--success)' }}><Icon name="check" size={12} />{ar ? 'تم استلام الطلب' : 'Order received'}</span>
            </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>;
}

/* Shown after returning from Stripe Checkout (#order-confirmed). The order +
   payment are recorded server-side by the webhook; the guest order isn't
   readable client-side (RLS), so this is a clean confirmation, not a receipt. */
function OrderConfirmedPage() {
  const { lang } = useLang(); const { go } = useNav(); const ar = lang === 'ar';
  return (
    <main style={{ paddingTop: 110, background: 'var(--bg-canvas)', minHeight: '60vh' }}>
      <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 ? 'تم استلام الدفعة' : 'Payment received'}</h1>
            <p style={{ fontSize: 15.5, color: 'var(--fg-secondary)', marginTop: 10, maxWidth: 520, marginInline: 'auto', lineHeight: 1.6 }}>{ar ? 'شكرًا لك. تم تأكيد طلبك، وسيتواصل معك فريق سرايا قريبًا لترتيب التفاصيل. وصلك إيصال إلى بريدك من Stripe.' : 'Thank you — your order is confirmed. The Saraya Events team will be in touch shortly to arrange the details. A receipt has been emailed to you by Stripe.'}</p>
            <div style={{ display: 'flex', gap: 10, justifyContent: 'center', marginTop: 24, flexWrap: 'wrap' }}>
              <Button variant="whatsapp" icon="message-circle" href={window.SARAYA.waLink('Hello Saraya Events, I just completed a payment and would like to confirm my order.')} target="_blank">{ar ? 'تواصل عبر واتساب' : 'WhatsApp us'}</Button>
              <Button variant="primary" icon="store" onClick={() => go('store')}>{ar ? 'العودة للمتجر' : 'Back to Store'}</Button>
            </div>
          </div>
        </Container>
      </Section>
    </main>
  );
}

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