// pdp.jsx — product detail, cart, checkout, confirmation, quick-view modal

function PDP({ product, lang, addToCart, setRoute, openPDP }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const fam = SCENT_FAMILIES.find(f => f.id === product.family);
  const [size, setSize] = React.useState(product.sizes[1]);
  const [tab, setTab] = React.useState('notes');
  const btnRef = React.useRef();

  // Scent profile (synthetic, but consistent per product)
  const profile = React.useMemo(() => {
    const seed = product.id.charCodeAt(2);
    const fams = ['oud', 'rose', 'amber', 'musk', 'spice', 'flora', 'woody'];
    return fams.map((f, i) => {
      let v = 20 + (((seed * (i + 3)) % 60));
      if (f === product.family) v = 88 + ((seed % 10));
      return { family: f, val: v };
    });
  }, [product.id]);

  const related = PRODUCTS.filter(p => p.family === product.family && p.id !== product.id).slice(0, 4);

  return (
    <>
      <section className="pdp">
        <div className="pdp-l" style={{ background: `color-mix(in oklab, ${product.tone} 14%, var(--bg-2))` }}>
          <div className="pdp-meta-l">
            <div>{t('استبرق', 'ISTABRAQ')}</div>
            <div className="mono" style={{ marginTop: 4 }}>N°{product.id.slice(1)}</div>
          </div>
          <div className="pdp-meta-l-r">
            <div style={{ fontSize: 11, letterSpacing: '0.2em', textTransform: 'uppercase', fontStyle: 'normal', fontFamily: 'var(--f-en-body)' }}>{product.origin}</div>
            <div style={{ fontSize: 16, marginTop: 4 }}>{product.year}</div>
          </div>
          {product.image
            ? <img className="pdp-photo" src={product.image} alt={lang === 'ar' ? product.name_ar : product.name_en} />
            : (
            <div className="pdp-bottle" style={{ background: `linear-gradient(170deg, ${product.tone} 0%, color-mix(in oklab, ${product.tone} 55%, #000) 100%)` }}>
              <div className="pdp-label">
                ISTABRAQ<br />
                <span style={{ fontSize: 20, letterSpacing: '0.08em' }}>{product.name_en}</span><br />
                <span style={{ fontSize: 9, letterSpacing: '0.25em', marginTop: 8, display: 'block', opacity: 0.7 }}>{product.concentration} · {size.ml}ML</span>
              </div>
            </div>
            )}
        </div>

        <div className="pdp-r">
          <a className="eyebrow" style={{ cursor: 'pointer', color: 'var(--ink-3)' }} onClick={() => setRoute('shop')}>
            <I.arrowL /> {t('عودة للكولكشن', 'Back to collection')}
          </a>
          <div>
            <div className="eyebrow">{lang === 'ar' ? fam.ar : fam.en} · {product.concentration}</div>
            <h1 className="h-display pdp-title">{lang === 'ar' ? product.name_ar : product.name_en}</h1>
            <div className="pdp-title-en">{lang === 'ar' ? product.name_en : product.name_ar}</div>
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            <div className="pdp-price"><span className="cur">AED</span> {size.price}</div>
            <div style={{ display: 'flex', gap: 2, color: 'var(--accent)' }}>
              {[...Array(5)].map((_, i) => <I.star key={i} />)}
            </div>
            <span className="eyebrow" style={{ fontSize: 11 }}>{product.rating} · 124 {t('تقييم', 'reviews')}</span>
          </div>

          <p style={{ color: 'var(--ink-2)', fontSize: 16, lineHeight: 1.65, margin: 0 }}>
            {lang === 'ar'
              ? `عطر يحكي ${fam.ar} من ${product.origin}. تفتح القصة بـ${product.top_ar}، تنبض بـ${product.heart_ar}، وتنغلق بنفس ${product.base_ar} يبقى على الجلد ساعات طويلة.`
              : `A fragrance that tells the story of ${fam.en} from ${product.origin}. Opens with ${product.top_ar}, beats with ${product.heart_ar}, settles with ${product.base_ar} that lingers for hours.`}
          </p>

          <div className="pdp-notes">
            <div className="pdp-note">
              <div className="lbl">{t('النوتة العليا', 'Top notes')}</div>
              <div className="val">{product.top_ar}</div>
            </div>
            <div className="pdp-note">
              <div className="lbl">{t('قلب العطر', 'Heart')}</div>
              <div className="val">{product.heart_ar}</div>
            </div>
            <div className="pdp-note">
              <div className="lbl">{t('القاعدة', 'Base')}</div>
              <div className="val">{product.base_ar}</div>
            </div>
          </div>

          <div>
            <div className="eyebrow" style={{ marginBottom: 12 }}>{t('الحجم', 'Size')}</div>
            <div className="size-picker">
              {product.sizes.map(s => (
                <button key={s.ml} className={'size-opt' + (s.ml === size.ml ? ' on' : '')}
                        onClick={() => setSize(s)}>
                  <div className="ml">{s.ml}ml</div>
                  <div className="pr">AED {s.price}</div>
                </button>
              ))}
            </div>
          </div>

          <div className="pdp-cta">
            <button ref={btnRef} className="btn lg" style={{ flex: 2 }}
                    onClick={() => addToCart(product, btnRef.current, size)}>
              {t('أضف للسلة', 'Add to bag')} · AED {size.price}
            </button>
            <button className="btn ghost lg" style={{ flex: 1 }} aria-label="wishlist">
              <I.heart />
            </button>
          </div>

          {/* Scent profile radar */}
          <div style={{ borderTop: '1px solid var(--line)', paddingTop: 24 }}>
            <div className="eyebrow" style={{ marginBottom: 8 }}>{t('ملف الرائحة', 'Scent Profile')}</div>
            <div className="scent-radar">
              {profile.map(r => {
                const f = SCENT_FAMILIES.find(x => x.id === r.family);
                return (
                  <div key={r.family} className="scent-radar-row">
                    <span>{lang === 'ar' ? f.ar : f.en}</span>
                    <div className="scent-radar-bar">
                      <div className="scent-radar-fill" style={{ width: `${r.val}%`, background: f.tone }} />
                    </div>
                    <span className="scent-radar-val">{r.val}</span>
                  </div>
                );
              })}
            </div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 4, fontSize: 11, color: 'var(--ink-3)', paddingTop: 16, borderTop: '1px solid var(--line)' }}>
            <div><div style={{ fontWeight: 500, color: 'var(--ink)', marginBottom: 2 }}>✓ {t('شحن مجاني', 'Free shipping')}</div><div>{t('للطلبات فوق 350 AED', 'orders over AED 350')}</div></div>
            <div><div style={{ fontWeight: 500, color: 'var(--ink)', marginBottom: 2 }}>✓ {t('عينة مجانية', 'Free sample')}</div><div>{t('مع كل طلب', 'with every order')}</div></div>
            <div><div style={{ fontWeight: 500, color: 'var(--ink)', marginBottom: 2 }}>✓ {t('استرداد 14 يوم', '14-day returns')}</div><div>{t('غير مفتوح', 'unopened')}</div></div>
          </div>
        </div>
      </section>

      {/* Related */}
      <section className="section" style={{ padding: '80px 56px' }}>
        <div className="section-head" style={{ marginBottom: 32 }}>
          <h2 className="h-display section-title" style={{ fontSize: 'clamp(28px, 3.5vw, 48px)' }}>{t('قد يعجبك أيضاً', 'You may also love')}</h2>
        </div>
        <div className="product-grid">
          {related.map(p => <ProductCard key={p.id} product={p} lang={lang} onOpen={openPDP} onAddToCart={addToCart} />)}
        </div>
      </section>
    </>
  );
}

// ── Quick view modal ────────────────────────────────────────
function QuickView({ product, onClose, lang, addToCart, openFull }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const fam = SCENT_FAMILIES.find(f => f.id === product.family);
  const [size, setSize] = React.useState(product.sizes[1]);
  const btnRef = React.useRef();
  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-l" style={{ background: `color-mix(in oklab, ${product.tone} 12%, var(--bg-2))` }}>
          <div className="pdp-bottle" style={{ width: '55%', height: '70%', background: `linear-gradient(170deg, ${product.tone} 0%, color-mix(in oklab, ${product.tone} 55%, #000) 100%)` }}>
            <div className="pdp-label" style={{ fontSize: 11 }}>
              ISTABRAQ<br /><span style={{ fontSize: 16 }}>{product.name_en}</span>
            </div>
          </div>
        </div>
        <div className="modal-r">
          <button className="modal-x" onClick={onClose}><I.close /></button>
          <div className="eyebrow">{lang === 'ar' ? fam.ar : fam.en} · {product.concentration}</div>
          <h2 className="h-display" style={{ fontSize: 44, lineHeight: 1, margin: 0 }}>{lang === 'ar' ? product.name_ar : product.name_en}</h2>
          <div className="serif-en" style={{ fontSize: 18, color: 'var(--ink-2)' }}>{lang === 'ar' ? product.name_en : product.name_ar}</div>
          <div className="pdp-price" style={{ fontSize: 32 }}><span className="cur">AED</span> {size.price}</div>
          <p style={{ color: 'var(--ink-2)', fontSize: 14, margin: 0 }}>
            {lang === 'ar' ? `${product.top_ar} · ${product.heart_ar} · ${product.base_ar}` : `${product.top_ar} · ${product.heart_ar} · ${product.base_ar}`}
          </p>
          <div className="size-picker">
            {product.sizes.map(s => (
              <button key={s.ml} className={'size-opt' + (s.ml === size.ml ? ' on' : '')} onClick={() => setSize(s)}>
                <div className="ml">{s.ml}ml</div>
                <div className="pr">AED {s.price}</div>
              </button>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button ref={btnRef} className="btn" style={{ flex: 1 }}
                    onClick={() => { addToCart(product, btnRef.current, size); onClose(); }}>
              {t('أضف للسلة', 'Add to bag')}
            </button>
            <button className="btn ghost" onClick={() => { openFull(product); onClose(); }}>
              {t('التفاصيل', 'Details')}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Cart ────────────────────────────────────────────────────
function Cart({ items, setItems, lang, setRoute }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const subtotal = items.reduce((s, i) => s + i.price * i.qty, 0);
  const shipping = subtotal > 350 ? 0 : 25;
  const tax = Math.round(subtotal * 0.05);
  const total = subtotal + shipping + tax;

  const updateQty = (idx, d) => {
    const next = [...items];
    next[idx] = { ...next[idx], qty: Math.max(1, next[idx].qty + d) };
    setItems(next);
  };
  const remove = (idx) => setItems(items.filter((_, i) => i !== idx));

  if (items.length === 0) {
    return (
      <div style={{ padding: '120px 56px', textAlign: 'center' }}>
        <div className="eyebrow">{t('السلة', 'Bag')}</div>
        <h1 className="h-display" style={{ fontSize: 64, margin: '16px 0' }}>{t('سلتك فارغة', 'Your bag is empty.')}</h1>
        <p style={{ color: 'var(--ink-3)', margin: '0 0 32px' }}>{t('استكشف عطور استبرق وابدأ رحلتك.', 'Browse our fragrances and begin your journey.')}</p>
        <button className="btn lg" onClick={() => setRoute('shop')}>{t('تسوّق العطور', 'Shop fragrances')} <I.arrow /></button>
      </div>
    );
  }

  return (
    <div className="cart">
      <div className="cart-l">
        <div className="cart-head">
          <div className="eyebrow">{t('سلة التسوّق · 01', 'Shopping bag · 01')}</div>
          <h1 className="h-display">{t('السلة', 'Your bag')}</h1>
          <div className="sub">{items.reduce((s, i) => s + i.qty, 0)} {t('قطعة', 'items')}</div>
        </div>
        <div className="cart-items">
          {items.map((it, idx) => (
            <div key={idx} className="cart-item">
              <div className="cart-item-img">
                <div className="mini-bottle" style={{ background: `linear-gradient(170deg, ${it.tone}, color-mix(in oklab, ${it.tone} 55%, #000))` }} />
              </div>
              <div className="cart-item-info">
                <div className="nm">{lang === 'ar' ? it.name_ar : it.name_en}</div>
                <div className="en">{lang === 'ar' ? it.name_en : it.name_ar}</div>
                <div className="sz">{it.size}ml · {it.concentration}</div>
                <button className="cart-item-remove" onClick={() => remove(idx)}>{t('إزالة', 'Remove')}</button>
              </div>
              <div className="qty">
                <button onClick={() => updateQty(idx, -1)}><I.minus /></button>
                <span>{it.qty}</span>
                <button onClick={() => updateQty(idx, 1)}><I.plus /></button>
              </div>
              <div className="cart-item-price">{(it.price * it.qty).toLocaleString()} <span style={{ fontSize: 11, color: 'var(--ink-3)', fontStyle: 'normal', fontFamily: 'var(--f-en-body)' }}>AED</span></div>
            </div>
          ))}
        </div>
      </div>

      <aside className="cart-r">
        <div className="eyebrow">{t('الملخّص', 'Summary')}</div>
        <h2 className="h-display" style={{ fontSize: 40, lineHeight: 1, margin: '8px 0 24px' }}>{t('قبل الدفع', 'Before checkout')}</h2>

        <div className="summary-row">
          <span>{t('المجموع الفرعي', 'Subtotal')}</span>
          <span className="tabular">{subtotal.toLocaleString()} AED</span>
        </div>
        <div className="summary-row">
          <span>{t('الشحن', 'Shipping')}</span>
          <span className="tabular">{shipping === 0 ? t('مجاناً', 'Free') : `${shipping} AED`}</span>
        </div>
        <div className="summary-row">
          <span>{t('الضريبة (٥٪)', 'VAT (5%)')}</span>
          <span className="tabular">{tax.toLocaleString()} AED</span>
        </div>
        <div className="summary-row total">
          <span className="ar">{t('الإجمالي', 'Total')}</span>
          <span className="tabular">{total.toLocaleString()} <span style={{ fontSize: 14, color: 'var(--ink-3)' }}>AED</span></span>
        </div>

        <button className="btn full lg" style={{ marginTop: 24 }} onClick={() => setRoute('checkout')}>
          {t('متابعة للدفع', 'Continue to checkout')} <I.arrow />
        </button>
        <button className="btn ghost full" style={{ marginTop: 8 }} onClick={() => setRoute('shop')}>
          {t('استمر بالتسوّق', 'Continue shopping')}
        </button>

        <div style={{ marginTop: 28, padding: '16px 0', borderTop: '1px solid var(--line)', fontSize: 12, color: 'var(--ink-3)' }}>
          <div style={{ display: 'flex', gap: 14, marginBottom: 6 }}>
            <strong style={{ color: 'var(--ink)' }}>✓</strong>
            {t('عينة مجانية مع كل طلب', 'Free sample with every order')}
          </div>
          <div style={{ display: 'flex', gap: 14 }}>
            <strong style={{ color: 'var(--ink)' }}>✓</strong>
            {t('شحن مجاني فوق 350 AED', 'Free shipping over AED 350')}
          </div>
        </div>
      </aside>
    </div>
  );
}

// ── Checkout ────────────────────────────────────────────────
function Checkout({ items, lang, setRoute, setLastOrder }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const [pay, setPay] = React.useState('card');
  const [form, setForm] = React.useState({
    email: '', firstName: '', lastName: '', phone: '+971 50 ',
    address: '', city: 'دبي', emirate: 'Dubai',
    cardName: '', cardNumber: '4521 ', cardExp: '', cardCvc: '',
  });
  const upd = (k, v) => setForm({ ...form, [k]: v });
  const subtotal = items.reduce((s, i) => s + i.price * i.qty, 0);
  const shipping = subtotal > 350 ? 0 : 25;
  const tax = Math.round(subtotal * 0.05);
  const total = subtotal + shipping + tax;

  const [placing, setPlacing] = React.useState(false);
  const submit = async () => {
    if (placing) return;
    setPlacing(true);
    try {
      const order = await apiPost('checkout', {
        ...form, pay, items,
      });
      if (order && order.code) {
        setLastOrder(order);
        setRoute('confirm');
      } else {
        alert(lang === 'ar' ? 'تعذّر إتمام الطلب. حاول مجدداً.' : 'Could not place the order. Please try again.');
        setPlacing(false);
      }
    } catch (e) {
      alert(lang === 'ar' ? 'تعذّر الاتصال بالخادم.' : 'Could not reach the server.');
      setPlacing(false);
    }
  };

  return (
    <div className="checkout">
      <div className="co-l">
        <div className="eyebrow"><a onClick={() => setRoute('cart')} style={{ cursor: 'pointer' }}><I.arrowL /> {t('العودة للسلة', 'Back to bag')}</a></div>
        <h1 className="h-display" style={{ fontSize: 56, lineHeight: 1, margin: '8px 0 32px' }}>{t('إتمام الشراء', 'Checkout')}</h1>

        <div className="co-step">
          <span className="step-dot done">1</span>
          <span>{t('الشحن', 'Shipping')}</span>
          <span className="line"></span>
          <span className="step-dot on">2</span>
          <span>{t('الدفع', 'Payment')}</span>
          <span className="line"></span>
          <span className="step-dot">3</span>
          <span>{t('المراجعة', 'Review')}</span>
        </div>

        <div className="co-section">
          <h2 className="h-display">{t('معلومات التوصيل', 'Delivery details')}</h2>
          <div className="co-grid">
            <div className="field span-2"><label>{t('البريد الإلكتروني', 'Email')}</label><input value={form.email} onChange={(e) => upd('email', e.target.value)} placeholder="you@email.com" /></div>
            <div className="field"><label>{t('الاسم الأول', 'First name')}</label><input value={form.firstName} onChange={(e) => upd('firstName', e.target.value)} /></div>
            <div className="field"><label>{t('الاسم الأخير', 'Last name')}</label><input value={form.lastName} onChange={(e) => upd('lastName', e.target.value)} /></div>
            <div className="field"><label>{t('الجوّال', 'Phone')}</label><input value={form.phone} onChange={(e) => upd('phone', e.target.value)} /></div>
            <div className="field"><label>{t('الإمارة', 'Emirate')}</label>
              <select value={form.emirate} onChange={(e) => upd('emirate', e.target.value)}>
                <option>Dubai</option><option>Abu Dhabi</option><option>Sharjah</option><option>Ajman</option><option>Ras Al Khaimah</option><option>Fujairah</option><option>Umm Al Quwain</option>
              </select>
            </div>
            <div className="field span-2"><label>{t('العنوان', 'Address')}</label><input value={form.address} onChange={(e) => upd('address', e.target.value)} placeholder={t('شارع، مبنى، شقة', 'Street, building, flat')} /></div>
          </div>
        </div>

        <div className="co-section">
          <h2 className="h-display">{t('طريقة الدفع', 'Payment method')}</h2>
          <div className="pay-tabs">
            <button className={'pay-tab' + (pay === 'card' ? ' on' : '')} onClick={() => setPay('card')}>
              <svg viewBox="0 0 32 24" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="2" y="4" width="28" height="16" rx="2" /><path d="M2 10h28M6 16h4" /></svg>
              <div>
                <div style={{ fontWeight: 500 }}>{t('بطاقة', 'Card')}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>Visa · Master · Mada</div>
              </div>
            </button>
            <button className={'pay-tab' + (pay === 'apple' ? ' on' : '')} onClick={() => setPay('apple')}>
              <svg viewBox="0 0 24 24" fill="currentColor"><path d="M17.05 12.5c-.02-2.04 1.66-3.02 1.74-3.07-.94-1.38-2.42-1.57-2.95-1.59-1.26-.13-2.46.74-3.1.74-.65 0-1.63-.72-2.69-.7-1.38.02-2.66.8-3.36 2.04-1.43 2.49-.37 6.18 1.03 8.2.68.99 1.5 2.1 2.56 2.07 1.03-.04 1.42-.66 2.66-.66 1.24 0 1.6.66 2.69.64 1.11-.02 1.81-1.01 2.49-2 .78-1.15 1.1-2.27 1.12-2.32-.03-.01-2.15-.82-2.17-3.27zM15.05 6.5c.56-.68.94-1.62.84-2.56-.81.04-1.79.55-2.37 1.22-.51.6-.96 1.55-.84 2.48.9.07 1.81-.46 2.37-1.14z"/></svg>
              <div>
                <div style={{ fontWeight: 500 }}>Apple Pay</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{t('سريع وآمن', 'Fast & secure')}</div>
              </div>
            </button>
            <button className={'pay-tab' + (pay === 'cod' ? ' on' : '')} onClick={() => setPay('cod')}>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="2" y="6" width="20" height="12" rx="2" /><circle cx="12" cy="12" r="3" /></svg>
              <div>
                <div style={{ fontWeight: 500 }}>{t('الدفع عند الاستلام', 'Cash on delivery')}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{t('ادفع نقداً عند الوصول', 'Pay cash on arrival')}</div>
              </div>
            </button>
          </div>

          {pay === 'cod' && (
            <div style={{ marginTop: 24, padding: 24, background: 'var(--bg-2)', borderRadius: 4, fontSize: 14, color: 'var(--ink-2)' }}>
              {t('ستدفع المبلغ نقداً لمندوب التوصيل عند استلام طلبك. لا حاجة لبيانات بطاقة.',
                 'You will pay the courier in cash when your order arrives. No card details needed.')}
            </div>
          )}

          {pay === 'card' && (
            <div style={{ marginTop: 24 }}>
              <div className="card-prev">
                <div className="row">
                  <div className="brand">istabraq</div>
                  <div className="mono" style={{ fontSize: 10, opacity: 0.7 }}>SECURE PAY</div>
                </div>
                <div className="chip" />
                <div className="num">{(form.cardNumber || '•••• •••• •••• ••••').padEnd(19, '•')}</div>
                <div className="row">
                  <div>{form.cardName || t('اسم حامل البطاقة', 'CARDHOLDER NAME')}</div>
                  <div>{form.cardExp || 'MM/YY'}</div>
                </div>
              </div>
              <div className="co-grid">
                <div className="field span-2"><label>{t('رقم البطاقة', 'Card number')}</label><input value={form.cardNumber} onChange={(e) => upd('cardNumber', e.target.value)} placeholder="•••• •••• •••• ••••" /></div>
                <div className="field span-2"><label>{t('اسم على البطاقة', 'Name on card')}</label><input value={form.cardName} onChange={(e) => upd('cardName', e.target.value.toUpperCase())} /></div>
                <div className="field"><label>{t('انتهاء', 'Expiry')}</label><input value={form.cardExp} onChange={(e) => upd('cardExp', e.target.value)} placeholder="MM/YY" /></div>
                <div className="field"><label>CVC</label><input value={form.cardCvc} onChange={(e) => upd('cardCvc', e.target.value)} placeholder="•••" type="password" /></div>
              </div>
            </div>
          )}

          {pay === 'apple' && (
            <div style={{ marginTop: 24, padding: 40, background: 'var(--ink)', color: 'var(--bg)', borderRadius: 4, textAlign: 'center' }}>
              <svg viewBox="0 0 24 24" width="48" height="48" fill="currentColor" style={{ marginBottom: 12 }}>
                <path d="M17.05 12.5c-.02-2.04 1.66-3.02 1.74-3.07-.94-1.38-2.42-1.57-2.95-1.59-1.26-.13-2.46.74-3.1.74-.65 0-1.63-.72-2.69-.7-1.38.02-2.66.8-3.36 2.04-1.43 2.49-.37 6.18 1.03 8.2.68.99 1.5 2.1 2.56 2.07 1.03-.04 1.42-.66 2.66-.66 1.24 0 1.6.66 2.69.64 1.11-.02 1.81-1.01 2.49-2 .78-1.15 1.1-2.27 1.12-2.32-.03-.01-2.15-.82-2.17-3.27zM15.05 6.5c.56-.68.94-1.62.84-2.56-.81.04-1.79.55-2.37 1.22-.51.6-.96 1.55-.84 2.48.9.07 1.81-.46 2.37-1.14z"/>
              </svg>
              <div style={{ fontSize: 18 }}>{t('استخدم Touch ID أو Face ID للدفع', 'Use Touch ID or Face ID to pay')}</div>
              <div style={{ fontSize: 13, opacity: 0.7, marginTop: 6 }}>AED {total.toLocaleString()}</div>
            </div>
          )}
        </div>

        <button className="btn lg full" onClick={submit} disabled={placing}>
          {placing ? t('جارٍ التأكيد…', 'Placing…') : t(`أكّد الطلب · AED ${total.toLocaleString()}`, `Place order · AED ${total.toLocaleString()}`)} <I.arrow />
        </button>
      </div>

      <aside className="co-r">
        <div className="order-summary-card">
          <h3>{t('ملخّص الطلب', 'Order summary')}</h3>
          {items.map((it, idx) => (
            <div key={idx} className="order-summary-item">
              <div className="si">
                <div className="mini-bottle" style={{ background: `linear-gradient(170deg, ${it.tone}, color-mix(in oklab, ${it.tone} 55%, #000))` }} />
              </div>
              <div>
                <div className="nm">{lang === 'ar' ? it.name_ar : it.name_en}</div>
                <div className="qty-x">{it.size}ml · {t('الكمية', 'Qty')} {it.qty}</div>
              </div>
              <div className="pr">{(it.price * it.qty).toLocaleString()}</div>
            </div>
          ))}
          <div style={{ marginTop: 16, borderTop: '1px solid var(--line)', paddingTop: 12 }}>
            <div className="summary-row"><span>{t('المجموع الفرعي', 'Subtotal')}</span><span className="tabular">{subtotal.toLocaleString()} AED</span></div>
            <div className="summary-row"><span>{t('الشحن', 'Shipping')}</span><span className="tabular">{shipping === 0 ? t('مجاناً', 'Free') : `${shipping} AED`}</span></div>
            <div className="summary-row"><span>{t('الضريبة', 'VAT')}</span><span className="tabular">{tax} AED</span></div>
            <div className="summary-row total"><span className="ar">{t('الإجمالي', 'Total')}</span><span className="tabular">{total.toLocaleString()} <span style={{ fontSize: 14, color: 'var(--ink-3)' }}>AED</span></span></div>
          </div>
        </div>
      </aside>
    </div>
  );
}

// ── Confirmation ────────────────────────────────────────────
function Confirmation({ order, lang, setRoute }) {
  const t = (ar, en) => lang === 'ar' ? ar : en;
  if (!order) return null;
  return (
    <div className="confirm">
      <div className="confirm-inner">
        <div className="confirm-check">✓</div>
        <div className="eyebrow">{t('تأكيد الطلب', 'Order confirmed')}</div>
        <h1 className="h-display">{t('شكراً لك', 'Thank you.')}</h1>
        <p className="sub">
          {t(`أرسلنا تأكيد الطلب إلى ${order.email}. سيصلك خلال 48 ساعة.`,
             `We sent a confirmation to ${order.email}. Your bottles arrive within 48 hours.`)}
        </p>

        <div className="confirm-card">
          <div className="confirm-grid">
            <div>
              <div className="lbl">{t('رقم الطلب', 'Order number')}</div>
              <div className="val mono">{order.id}</div>
            </div>
            <div>
              <div className="lbl">{t('الإجمالي', 'Total')}</div>
              <div className="val serif-en" style={{ fontSize: 22 }}>AED {order.total.toLocaleString()}</div>
            </div>
            <div>
              <div className="lbl">{t('التوصيل إلى', 'Delivering to')}</div>
              <div className="val">{order.customer}</div>
              <div style={{ fontSize: 13, color: 'var(--ink-3)' }}>{order.address}</div>
            </div>
            <div>
              <div className="lbl">{t('الموعد المتوقّع', 'Estimated arrival')}</div>
              <div className="val">{t('خلال يومين عمل', '2 business days')}</div>
            </div>
          </div>
          <hr className="fine" />
          <div className="eyebrow" style={{ marginBottom: 12 }}>{t('قائمة العطور', 'Your fragrances')}</div>
          {order.items.map((it, idx) => (
            <div key={idx} className="order-summary-item">
              <div className="si"><div className="mini-bottle" style={{ background: `linear-gradient(170deg, ${it.tone}, color-mix(in oklab, ${it.tone} 55%, #000))` }} /></div>
              <div>
                <div className="nm">{lang === 'ar' ? it.name_ar : it.name_en}</div>
                <div className="qty-x">{it.size}ml × {it.qty}</div>
              </div>
              <div className="pr">{(it.price * it.qty).toLocaleString()}</div>
            </div>
          ))}
        </div>

        <div style={{ display: 'flex', gap: 12, justifyContent: 'center' }}>
          <button className="btn" onClick={() => setRoute('home')}>{t('العودة للرئيسية', 'Back home')}</button>
          <button className="btn ghost" onClick={() => setRoute('shop')}>{t('متابعة التسوّق', 'Continue shopping')}</button>
        </div>
      </div>
    </div>
  );
}

window.PDP = PDP;
window.QuickView = QuickView;
window.Cart = Cart;
window.Checkout = Checkout;
window.Confirmation = Confirmation;
