// Saraya Events — Store: storefront (search / sort / filter / cards),
// product detail page, and admin product management (10 slots per category).
// Physical + digital products, Add to Cart / Buy Now / WhatsApp, Request Quote.

const { useState: useStateS, useEffect: useEffectS } = React;

// ── listing_images gallery hook ───────────────────────────────────────────────
// Fetches all images for a listing from listing_images (preferred, has is_cover + order)
// Falls back to the item.images[] array from normProduct if listing_images has none.
function useListingImages(listingId, listingType, fallbackImages) {
  const [images, setImages] = useStateS(fallbackImages || []);
  const [selIdx, setSelIdx] = useStateS(0);
  useEffectS(() => {
    setImages(fallbackImages || []);
    setSelIdx(0);
    if (!window.supabaseConfigured || !window.SarayaDB || !listingId) return;
    window.SarayaDB
      .from('listing_images')
      .select('image_url, image_order, is_cover')
      .eq('listing_id', listingId)
      .eq('listing_type', listingType)
      .order('image_order')
      .then(({ data }) => {
        if (data && data.length > 0) {
          const urls = data.map((r) => r.image_url);
          const ci = data.findIndex((r) => r.is_cover);
          setImages(urls);
          setSelIdx(ci >= 0 ? ci : 0);
        }
      })
      .catch(() => {});
  }, [listingId, listingType]);
  return { images, selIdx, setSelIdx };
}

// ── DB-backed product hook with data.js fallback ──────────────────────────────
// Called at StorePage top-level; falls through to admin.resolveStore() when
// Supabase is not configured so the admin overlay system keeps working.
function useStoreProducts() {
  const hook = window.useProducts ? window.useProducts({ onlyActive: false }) : null;
  if (!window.supabaseConfigured || !hook) return { dbItems: null, dbLoading: false };
  return { dbItems: hook.items, dbLoading: hook.loading };
}

/* effective price (respects an admin sale price) */
function effPrice(it) {
  const sp = Number(it.salePrice);
  return (sp && sp > 0 && sp < it.price) ? sp : Number(it.price) || 0;
}
function onSale(it) { const sp = Number(it.salePrice); return !!(sp && sp > 0 && sp < Number(it.price)); }

const AVAIL = {
  in:   { en: 'In stock', ar: 'متوفر', tone: 'success' },
  order:{ en: 'Made to order', ar: 'حسب الطلب', tone: 'info' },
  soon: { en: 'Coming soon', ar: 'قريبًا', tone: 'warning' },
  out:  { en: 'Unavailable', ar: 'غير متوفر', tone: 'error' },
};
function availOf(it) { return it.availability || 'in'; }

/* admin edit fields for a store product */
function storeFields(S) {
  return [
    { key: 'name.en', label: 'Product name (EN)' }, { key: 'name.ar', label: 'Product name (AR)', dir: 'rtl' },
    { key: 'category', label: 'Category', type: 'select', options: S.STORE_CATEGORIES.map((c) => ({ value: c.id, label: c.name.en })) },
    { key: 'price', label: 'Price (AED)' },
    { key: 'salePrice', label: 'Sale price (AED) — optional, leave blank for none' },
    { key: 'availability', label: 'Availability', type: 'select', options: [{ value: 'in', label: 'In stock' }, { value: 'order', label: 'Made to order' }, { value: 'soon', label: 'Coming soon' }, { value: 'out', label: 'Unavailable' }] },
    { key: 'stock', label: 'Stock count (optional — for low-stock alerts)' },
    { key: 'popular', label: 'Popular?', type: 'select', options: [{ value: '', label: 'No' }, { value: '1', label: 'Yes — mark Popular' }] },
    { key: 'isNew', label: 'New?', type: 'select', options: [{ value: '', label: 'No' }, { value: '1', label: 'Yes — mark New' }] },
    { key: 'hidden', label: 'Visibility', type: 'select', options: [{ value: '', label: 'Visible to customers' }, { value: '1', label: 'Hidden (draft)' }] },
    { key: 'digital', label: 'Type', type: 'select', options: [{ value: '', label: 'Physical product' }, { value: '1', label: 'Digital download' }] },
    { key: 'fileType', label: 'File type label (digital, e.g. PDF)' },
    { key: 'link', label: 'Open-link URL (optional — opens a page/app)' },
    { key: 'desc.en', label: 'Short description (EN)', type: 'textarea' }, { key: 'desc.ar', label: 'Short description (AR)', type: 'textarea', dir: 'rtl' },
    { key: 'included.en', label: 'What’s included — one per line (EN)', type: 'list' },
    { key: 'included.ar', label: 'What’s included — one per line (AR)', type: 'list', dir: 'rtl' },
  ];
}

/* ============================ STORE PAGE ============================ */
function StorePage() {
  const { t, lang } = useLang();
  const { go } = useNav();
  const cart = useCart();
  const admin = useAdmin();
  const S = window.SARAYA;
  const ar = lang === 'ar';
  const [cat, setCat] = useStateS('all');
  const [q, setQ] = useStateS('');
  const [sort, setSort] = useStateS('featured');

  const { dbItems, dbLoading } = useStoreProducts();
  // When Supabase is configured, always use live data — even if zero results.
  // Fall back to data.js only when Supabase is not configured (local/demo mode).
  const fallback = admin.resolveStore();
  const usingLiveData = window.supabaseConfigured && dbItems !== null;
  let items = usingLiveData ? (dbItems || []) : fallback;
  if (!admin.editMode) items = items.filter((i) => !i.hidden);            // hide drafts from public
  if (cat !== 'all') items = items.filter((i) => i.category === cat);
  if (q.trim()) { const k = q.trim().toLowerCase(); items = items.filter((i) => (i.name.en + ' ' + i.name.ar + ' ' + (i.desc ? i.desc.en : '')).toLowerCase().includes(k)); }
  items = items.slice();
  if (sort === 'price-asc') items.sort((a, b) => effPrice(a) - effPrice(b));
  else if (sort === 'price-desc') items.sort((a, b) => effPrice(b) - effPrice(a));
  else if (sort === 'newest') items.sort((a, b) => (b.isNew ? 1 : 0) - (a.isNew ? 1 : 0));
  else if (sort === 'popular') items.sort((a, b) => (b.popular ? 1 : 0) - (a.popular ? 1 : 0));

  /* admin: 10-slot cap per (real) category */
  const catCount = (cid) => admin.resolveStore().filter((i) => i.category === cid).length;
  const addProduct = () => {
    const category = cat === 'all' ? S.STORE_CATEGORIES[0].id : cat;
    if (catCount(category) >= S.STORE_CONFIG.slotsPerCategory) { admin.toastMsg('That category already has ' + S.STORE_CONFIG.slotsPerCategory + ' products (the slot limit).', 'error'); return; }
    const id = 'sp-' + Date.now().toString(36);
    admin.addStoreItem({ id, category, tone: 'cream', price: 0, availability: 'in', name: { en: 'New product', ar: 'منتج جديد' }, desc: { en: '', ar: '' } });
    admin.openEdit({ title: 'New store product', fields: storeFields(S), values: { name: { en: 'New product', ar: 'منتج جديد' }, category, availability: 'in' }, onSave: (v) => admin.mergeEntity('store:' + id, v) });
  };

  return (
    <main>
      <PageHero editKey="store-hero" slot="store-hero" eyebrow={ar ? 'السوق' : 'Marketplace'} tone="rose" icon="shopping-bag"
        title={ar ? 'سوق سرايا للفعاليات' : 'Saraya Events Marketplace'}
        intro={ar ? 'من الزهور والهدايا إلى ديكورات المناسبات ومستلزماتها — استكشف منتجات راقية مصممة للأعراس والاحتفالات والفعاليات المؤسسية واللحظات المميزة.' : 'From flowers and gifts to décor accents and event essentials, explore elegant items designed for weddings, celebrations, corporate events, and special moments.'} />

      <TrustBar />

      {/* ── Sticky filter bar ── */}
      <div style={{ position: 'sticky', top: 72, zIndex: 40, background: 'rgba(250,246,240,0.96)', backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)', borderBottom: '1px solid var(--line)' }}>
        <Container wide>

          {/* Row 1: search + sort */}
          <div style={{ display: 'flex', gap: 10, alignItems: 'center', paddingBlock: '12px 10px' }}>
            <div style={{ position: 'relative', flex: '1 1 260px', minWidth: 0 }}>
              <Icon name="search" size={16} style={{ position: 'absolute', insetInlineStart: 14, top: '50%', transform: 'translateY(-50%)', color: 'var(--fg-muted)', pointerEvents: 'none' }} />
              <input
                value={q} onChange={(e) => setQ(e.target.value)}
                placeholder={ar ? 'ابحث في السوق…' : 'Search the marketplace…'}
                style={{ width: '100%', padding: '10px 14px 10px 40px', borderRadius: 10, border: '1px solid var(--line-strong)', background: 'var(--white)', fontFamily: 'var(--font-body)', fontSize: 13.5, outline: 'none', color: 'var(--fg-primary)' }} />
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 7, flexShrink: 0 }}>
              <Icon name="arrow-up-down" size={14} style={{ color: 'var(--fg-muted)' }} />
              <select value={sort} onChange={(e) => setSort(e.target.value)} style={{ padding: '9px 28px 9px 11px', borderRadius: 10, border: '1px solid var(--line-strong)', background: 'var(--white)', fontFamily: 'var(--font-body)', fontSize: 13, cursor: 'pointer', color: 'var(--fg-primary)' }}>
                <option value="featured">{ar ? 'مميّز' : 'Featured'}</option>
                <option value="popular">{ar ? 'الأكثر طلبًا' : 'Most popular'}</option>
                <option value="newest">{ar ? 'الأحدث' : 'Newest'}</option>
                <option value="price-asc">{ar ? 'السعر: الأقل أولاً' : 'Price: low to high'}</option>
                <option value="price-desc">{ar ? 'السعر: الأعلى أولاً' : 'Price: high to low'}</option>
              </select>
            </div>
          </div>

          {/* Row 2: category pills */}
          <div style={{ display: 'flex', gap: 7, overflowX: 'auto', paddingBottom: 12, scrollbarWidth: 'none' }} className="saraya-catbar">
            {/* All */}
            <button
              onClick={() => setCat('all')}
              style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '7px 15px', borderRadius: 999, border: cat === 'all' ? 'none' : '1px solid var(--line-strong)', background: cat === 'all' ? 'var(--espresso)' : 'var(--white)', color: cat === 'all' ? 'var(--ivory)' : 'var(--fg-secondary)', fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: cat === 'all' ? 700 : 500, cursor: 'pointer', whiteSpace: 'nowrap', transition: 'all 160ms', flexShrink: 0 }}>
              <Icon name="layout-grid" size={13} />
              {ar ? 'الكل' : 'All items'}
            </button>

            {/* Divider */}
            <div style={{ width: 1, background: 'var(--line)', margin: '4px 2px', flexShrink: 0 }} />

            {/* Product categories */}
            {S.STORE_CATEGORIES.map((c) => (
              <button key={c.id}
                onClick={() => setCat(c.id)}
                style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '7px 15px', borderRadius: 999, border: cat === c.id ? '1.5px solid var(--gold)' : '1px solid var(--line-strong)', background: cat === c.id ? 'var(--gold-tint)' : 'var(--white)', color: cat === c.id ? 'var(--gold-deep)' : 'var(--fg-secondary)', fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: cat === c.id ? 700 : 400, cursor: 'pointer', whiteSpace: 'nowrap', transition: 'all 160ms', flexShrink: 0 }}>
                <Icon name={c.icon} size={13} />
                {c.name[lang]}
              </button>
            ))}

            {/* Divider */}
            <div style={{ width: 1, background: 'var(--line)', margin: '4px 2px', flexShrink: 0 }} />

            {/* Furniture Rentals — links to rental subcategory */}
            <button
                            onClick={() => go('rental/furniture-rent')}
                            style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '7px 15px', borderRadius: 999, border: '1px solid var(--line-strong)', background: 'var(--white)', color: 'var(--fg-secondary)', fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 400, cursor: 'pointer', whiteSpace: 'nowrap', transition: 'all 160ms', flexShrink: 0 }}>
              <Icon name="armchair" size={13} />
              {ar ? 'أثاث التأجير' : 'Furniture Rentals'}
            </button>
          </div>

        </Container>
      </div>

      <Section bg="canvas" style={{ paddingTop: 'clamp(32px,4vw,52px)' }}>
        <Container wide>
          {cat === 'rental' ? (
            <RentalCategoryGrid />
          ) : (
          <React.Fragment>
          {admin.editMode && (
            <div style={{ marginBottom: 22, display: 'flex', flexWrap: 'wrap', gap: 12, alignItems: 'center', justifyContent: 'center' }}>
              <AdminAddButton onClick={addProduct} label={ar ? 'أضف منتجًا' : 'Add a product'} />
              {cat !== 'all' && <span style={{ fontSize: 12.5, color: 'var(--fg-muted)' }}>{catCount(cat)} / {S.STORE_CONFIG.slotsPerCategory} {ar ? 'خانة مستخدمة' : 'slots used'}</span>}
            </div>
          )}
          {dbLoading ? (
            <p style={{ textAlign: 'center', color: 'var(--fg-muted)', padding: '60px 0', fontSize: 15 }}>{ar ? 'جارٍ التحميل…' : 'Loading products…'}</p>
          ) : items.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '60px 24px' }}>
              <p style={{ color: 'var(--fg-muted)', fontSize: 15, marginBottom: 8 }}>
                {usingLiveData && !q.trim() && cat === 'all'
                  ? (ar ? 'لا توجد منتجات معتمدة في المتجر بعد. تابعونا قريبًا!' : 'No approved products yet — check back soon!')
                  : (ar ? 'لا توجد منتجات مطابقة.' : 'No matching products.')}
              </p>
              {usingLiveData && !q.trim() && cat === 'all' && (
                <p style={{ fontSize: 13, color: 'var(--fg-muted)' }}>
                  {ar ? 'هل أنت بائع؟' : 'Are you a vendor?'}{' '}
                  <a href="#partner" style={{ color: 'var(--gold-deep)', fontWeight: 600 }}>{ar ? 'سجّل الآن' : 'Register now'}</a>
                </p>
              )}
            </div>
          ) : (
            <div className="saraya-grid-4">
              {items.map((it, i) => (<Reveal key={it.id} delay={(i % 4) * 35}><StoreCard item={it} /></Reveal>))}
            </div>
          )}
          <Reveal>
            <p style={{ textAlign: 'center', marginTop: 40, fontSize: 13, color: 'var(--fg-muted)', maxWidth: 620, marginInline: 'auto' }}>
              {ar ? 'الأسعار بالدرهم الإماراتي وتشمل التنسيق. يُضاف التوصيل وضريبة القيمة المضافة (٥٪) عند الدفع.' : 'Prices in AED and include styling. Delivery and 5% VAT are added at checkout.'}
            </p>
          </Reveal>
          </React.Fragment>
          )}
        </Container>
      </Section>

      <StickyCartBar />
    </main>
  );
}

/* ---------------- Product card ---------------- */
function StoreCard({ item }) {
  const { t, lang } = useLang();
  const { go } = useNav();
  const cart = useCart();
  const admin = useAdmin();
  item = admin.resolveEntity('store:' + item.id, item);
  const ar = lang === 'ar';
  const catObj = window.SARAYA.STORE_CATEGORIES.find((c) => c.id === item.category);
  const isDigital = !!item.digital;
  const av = availOf(item); const avMeta = AVAIL[av];
  const sold = av === 'out' || av === 'soon';
  const price = effPrice(item);
  const open = () => go('product/' + item.id);
  const buyNow = () => { cart.add(item, 1); go('checkout'); };
  const waMsg = `Hello Saraya Events, I’d like to enquire about: ${item.name.en}.`;

  const card = (
    <div className="saraya-lift" style={{ background: 'var(--white)', border: '1px solid var(--line)', borderRadius: 14, overflow: 'hidden', boxShadow: 'var(--shadow-soft)', display: 'flex', flexDirection: 'column', height: '100%', opacity: item.hidden ? 0.6 : 1 }}>
      <div style={{ position: 'relative', cursor: 'pointer' }} onClick={open}>
        <Img tone={item.tone} icon={isDigital ? 'download' : (catObj ? catObj.icon : 'shopping-bag')} ratio="1/1" radius={0} src={item.src} slot={'store:' + item.id} fit={isDigital ? 'cover' : 'cover'} />
        {window.WishlistButton && item.supabaseId && (
          <div style={{ position: 'absolute', top: 8, insetInlineEnd: 8, zIndex: 13 }} onClick={(e) => e.stopPropagation()}>
            {React.createElement(window.WishlistButton, { productId: item.supabaseId, size: 22 })}
          </div>
        )}
        <div style={{ position: 'absolute', top: 10, insetInlineStart: 10, display: 'flex', flexDirection: 'column', gap: 6, zIndex: 12 }}>
          {isDigital && <Badge tone="dark">{ar ? 'رقمي' : 'Digital'}</Badge>}
          {item.popular && <Badge tone="gold">{ar ? 'الأكثر طلبًا' : 'Popular'}</Badge>}
          {item.isNew && <Badge tone="rose">{ar ? 'جديد' : 'New'}</Badge>}
          {onSale(item) && <Badge tone="rose">{ar ? 'تخفيض' : 'Sale'}</Badge>}
          {item.hidden && <Badge tone="dark">{ar ? 'مسودة' : 'Hidden'}</Badge>}
        </div>
        {admin.editMode && (
          <div onClick={(e) => e.stopPropagation()} style={{ position: 'absolute', bottom: 10, insetInlineStart: '50%', transform: 'translateX(-50%)', display: 'flex', gap: 6, zIndex: 13 }}>
            <button onClick={() => admin.moveStore(item.id, -1)} title={ar ? 'نقل لليسار' : 'Move back'} style={{ width: 30, height: 30, borderRadius: 999, border: 'none', cursor: 'pointer', background: 'var(--white)', color: 'var(--espresso)', boxShadow: 'var(--shadow-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="arrow-left" size={15} /></button>
            <button onClick={() => admin.moveStore(item.id, 1)} title={ar ? 'نقل لليمين' : 'Move forward'} style={{ width: 30, height: 30, borderRadius: 999, border: 'none', cursor: 'pointer', background: 'var(--white)', color: 'var(--espresso)', boxShadow: 'var(--shadow-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="arrow-right" size={15} /></button>
          </div>
        )}
      </div>
      <div style={{ padding: '14px 16px 16px', display: 'flex', flexDirection: 'column', flex: 1 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 }}>
          <span style={{ fontSize: 10.5, color: 'var(--gold-deep)', fontWeight: 600, letterSpacing: '0.14em', textTransform: 'uppercase' }}>{catObj ? catObj.name[lang] : ''}</span>
          <span style={{ fontSize: 11, color: 'var(--' + (avMeta.tone === 'error' ? 'error' : avMeta.tone === 'warning' ? 'warning' : 'success') + ')', fontWeight: 600 }}>{avMeta[lang]}</span>
        </div>
        <button onClick={open} style={{ textAlign: 'start', background: 'none', border: 'none', cursor: 'pointer', padding: 0, fontFamily: 'var(--font-serif)', fontSize: 18, fontWeight: 500, margin: '4px 0 4px', lineHeight: 1.15, color: 'var(--fg-primary)' }}>{item.name[lang]}</button>
        {item.desc && item.desc[lang] && <p style={{ fontSize: 12.5, lineHeight: 1.5, color: 'var(--fg-secondary)', margin: '0 0 10px' }}>{item.desc[lang]}</p>}
        {isDigital && item.fileType && <div style={{ fontSize: 11, color: 'var(--fg-muted)', marginBottom: 8, display: 'flex', alignItems: 'center', gap: 5 }}><Icon name="file-down" size={13} />{item.fileType} · {ar ? 'تحميل فوري' : 'Instant download'}</div>}
        <div style={{ marginTop: 'auto' }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 10 }}>
            <span style={{ fontFamily: 'var(--font-display)', fontSize: 21, fontWeight: 600, color: 'var(--fg-primary)', whiteSpace: 'nowrap' }}>{money(price)}</span>
            {onSale(item) && <span style={{ fontSize: 13, color: 'var(--fg-muted)', textDecoration: 'line-through' }}>{money(item.price)}</span>}
          </div>
          {item.requestQuote ? (
            <Button variant="primary" size="sm" full icon="file-text" onClick={open}>{ar ? 'اطلب عرض سعر' : 'Request Quote'}</Button>
          ) : (
            <div style={{ display: 'grid', gap: 7 }}>
              <div style={{ display: 'flex', gap: 7 }}>
                <Button variant="secondary" size="sm" full icon={cart.has(item.id) ? 'check' : 'plus'} onClick={() => cart.add(item, 1)} disabled={sold}>{cart.has(item.id) ? (ar ? 'في السلة' : 'In cart') : (ar ? 'أضف' : 'Add')}</Button>
                <Button variant="primary" size="sm" full onClick={buyNow} disabled={sold}>{ar ? 'اشترِ الآن' : 'Buy Now'}</Button>
              </div>
              {item.link
                ? <Button variant="gold" size="sm" full icon="wand-sparkles" href={item.link} target="_blank">{item.linkLabel ? (item.linkLabel[lang] || item.linkLabel.en) : (ar ? 'افتح' : 'Open')}</Button>
                                : React.createElement(Button, { variant: "primary", size: "sm", full: true, icon: "file-text", onClick: () => window.openItemRFQModal && window.openItemRFQModal(item) }, ar ? 'اطلب عرض سعر' : 'Request a Quote')}
            </div>
          )}
          {admin.editMode && isDigital && <DigitalFileControl id={item.id} />}
        </div>
      </div>
    </div>
  );
  return <AdminCardWrap
    onEdit={() => admin.openEdit({ title: 'Edit store product', fields: storeFields(window.SARAYA), values: item, onSave: (v) => admin.mergeEntity('store:' + item.id, v) })}
    onDelete={() => { if (window.confirm('Delete this product?')) admin.deleteStoreItem(item.id); }}>{card}</AdminCardWrap>;
}

/* admin: attach/replace the downloadable file for a digital product */
function DigitalFileControl({ id }) {
  const admin = useAdmin();
  const [name, setName] = useStateS(null);
  useEffectS(() => { window.getDigitalFile(id).then((r) => setName(r ? r.name : null)); }, [id]);
  return (
    <button onClick={() => window.pickDigitalFile(id, (n) => { if (n) { setName(n); admin.toastMsg('File attached'); } })}
      style={{ marginTop: 8, width: '100%', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 7, padding: '8px 10px', borderRadius: 8, background: 'var(--bg-tint)', border: '1px dashed var(--gold)', cursor: 'pointer', fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--fg-primary)' }}>
      <Icon name="paperclip" size={14} style={{ color: 'var(--gold-deep)' }} />{name ? ('File: ' + name) : 'Upload download file'}
    </button>
  );
}

/* ---------------- Product detail page ---------------- */
function ProductDetailPage({ productId }) {
  const { t, lang } = useLang();
  const { go } = useNav();
  const cart = useCart();
  const admin = useAdmin();
  const ar = lang === 'ar';
  // Try local store first; for Supabase items (UUID), fetch live from DB
  const localBase = admin.resolveStore().find((i) => i.id === productId);
  const [liveItem, setLiveItem] = useStateS(null);
  useEffectS(() => {
    setLiveItem(null);
    if (!localBase && window.supabaseConfigured && window.SarayaService) {
      window.SarayaService.products.get(productId).then((d) => setLiveItem(d || null)).catch(() => {});
    }
  }, [productId]);
  const base = localBase || liveItem;
  const [qty, setQty] = useStateS(1);
  const [meta, setMeta] = useStateS({});
  const fallbackImgs = base ? ((base.images && base.images.length > 0) ? base.images : (base.src ? [base.src] : [])) : [];
  const { images: galleryImgs, selIdx, setSelIdx } = useListingImages(base ? base.id : null, 'product', fallbackImgs);
  if (!base) {
    return (
      <main style={{ paddingTop: 140, minHeight: '60vh' }}><Container>
        {!localBase && window.supabaseConfigured && !liveItem
          ? <p style={{ color: 'var(--fg-muted)' }}>{ar ? 'جارٍ التحميل…' : 'Loading…'}</p>
          : <p style={{ color: 'var(--fg-muted)' }}>{ar ? 'المنتج غير موجود.' : 'Product not found.'} <button onClick={() => go('store')} style={{ color: 'var(--gold-deep)', background: 'none', border: 'none', cursor: 'pointer' }}>{ar ? 'العودة للمتجر' : 'Back to store'}</button></p>}
      </Container></main>
    );
  }
  const item = base;
  const catObj = window.SARAYA.STORE_CATEGORIES.find((c) => c.id === item.category);
  const isDigital = !!item.digital;
  const isFloral = item.category === 'flowers' || item.category === 'gifts';
  const isEvent = item.category === 'party';
  const av = availOf(item); const sold = av === 'out' || av === 'soon';
  const price = effPrice(item);
  const setM = (k, v) => setMeta((p) => Object.assign({}, p, { [k]: v }));
  const included = item.included && item.included[lang] && item.included[lang].length ? item.included[lang] : null;
  const related = admin.resolveStore().filter((i) => i.category === item.category && i.id !== item.id && !i.hidden).slice(0, 4);
  // Multi-image gallery: prefer listing_images table, fall back to item.images[]
  const mainImg = galleryImgs[selIdx] || item.src || null;

  const addToCart = () => cart.add(item, qty, Object.keys(meta).length ? meta : null);
  const buyNow = () => { addToCart(); go('checkout'); };
  const waMsg = `Hello Saraya Events, I’d like to enquire about: ${item.name.en}` + (price ? ` (${money(price)})` : '') + '.';

  return (
    <main style={{ paddingTop: 96 }}>
      <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: 18 }}><Icon name="arrow-left" size={16} />{ar ? 'المتجر' : 'Store'}</button>
          <div className="saraya-split" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 44, alignItems: 'start' }}>
            {/* gallery */}
            <div>
              {/* Main image */}
              {mainImg
                ? <img src={mainImg} alt={item.name ? item.name[lang] : ''} style={{ width: '100%', aspectRatio: '1/1', objectFit: 'cover', borderRadius: 18, display: 'block', background: 'var(--gold-tint)' }} />
                : <Img tone={item.tone} icon={isDigital ? 'download' : (catObj ? catObj.icon : 'shopping-bag')} slot={'store:' + item.id} ratio="1/1" radius={18} />}
              {/* Thumbnails: real images when available, else admin-upload slots */}
              <div style={{ display: 'flex', gap: 8, marginTop: 10, overflowX: 'auto', paddingBottom: 4, scrollbarWidth: 'none' }}>
                {galleryImgs.length > 1
                  ? galleryImgs.map((url, idx) => (
                    <button key={idx} onClick={() => setSelIdx(idx)}
                      style={{ flexShrink: 0, width: 80, height: 80, borderRadius: 10, overflow: 'hidden', border: idx === selIdx ? '2.5px solid var(--gold-deep)' : '1.5px solid var(--line)', padding: 0, cursor: 'pointer', background: 'none' }}>
                      <img src={url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
                    </button>
                  ))
                  : [0, 1, 2].map((n) => <Img key={n} tone={item.tone} icon="image" slot={'store:' + item.id + ':' + n} ratio="1/1" radius={10} plain style={{ width: 80, height: 80, flexShrink: 0 }} />)}
              </div>
            </div>
            {/* info */}
            <div>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 10 }}>
                {catObj && <Badge tone="cream">{catObj.name[lang]}</Badge>}
                {isDigital && <Badge tone="dark">{ar ? 'رقمي' : 'Digital'}</Badge>}
                {item.popular && <Badge tone="gold">{ar ? 'الأكثر طلبًا' : 'Popular'}</Badge>}
                {item.isNew && <Badge tone="rose">{ar ? 'جديد' : 'New'}</Badge>}
              </div>
              <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(28px,4vw,42px)', fontWeight: 500, lineHeight: 1.08 }}>{item.name[lang]}</h1>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginTop: 12 }}>
                <span style={{ fontFamily: 'var(--font-display)', fontSize: 32, fontWeight: 600 }}>{money(price)}</span>
                {onSale(item) && <span style={{ fontSize: 17, color: 'var(--fg-muted)', textDecoration: 'line-through' }}>{money(item.price)}</span>}
                <StatusPill status={av === 'in' ? 'paid' : av === 'out' ? 'cancelled' : 'pending'} small />
              </div>
              {item.desc && item.desc[lang] && <p style={{ fontSize: 15.5, lineHeight: 1.7, color: 'var(--fg-secondary)', marginTop: 16 }}>{item.desc[lang]}</p>}

              {included && (
                <div style={{ marginTop: 18 }}>
                  <div style={{ fontSize: 12, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--gold-deep)', marginBottom: 8 }}>{ar ? 'يشمل' : 'What’s included'}</div>
                  <div style={{ display: 'grid', gap: 7 }}>{included.map((x, i) => <div key={i} style={{ display: 'flex', gap: 9, fontSize: 14, color: 'var(--fg-primary)' }}><Icon name="check" size={15} style={{ color: 'var(--gold-deep)', marginTop: 2, flexShrink: 0 }} />{x}</div>)}</div>
                </div>
              )}

              {/* fulfilment / customisation */}
              {!isDigital && (
                <div style={{ marginTop: 20, padding: '16px 18px', background: 'var(--white)', borderRadius: 14, border: '1px solid var(--line)', display: 'grid', gap: 13 }}>
                  {isFloral && <>
                    <div className="saraya-split" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                      <Field label={ar ? 'تاريخ التوصيل' : 'Delivery date'}><TextInput type="date" value={meta.deliveryDate || ''} onChange={(e) => setM('deliveryDate', e.target.value)} /></Field>
                      <Field label={ar ? 'وقت التوصيل' : 'Delivery time'}><Select value={meta.deliveryTime || ''} onChange={(e) => setM('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>
                    </div>
                    <Field label={ar ? 'رسالة الإهداء (اختياري)' : 'Gift message (optional)'}><Textarea rows={2} value={meta.giftMessage || ''} onChange={(e) => setM('giftMessage', e.target.value)} /></Field>
                    <div className="saraya-split" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                      <Field label={ar ? 'اسم المستلِم' : 'Recipient name'}><TextInput value={meta.recipientName || ''} onChange={(e) => setM('recipientName', e.target.value)} /></Field>
                      <Field label={ar ? 'جوال المستلِم' : 'Recipient mobile'}><TextInput value={meta.recipientPhone || ''} onChange={(e) => setM('recipientPhone', e.target.value)} /></Field>
                    </div>
                  </>}
                  {isEvent && <>
                    <div className="saraya-split" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                      <Field label={ar ? 'تاريخ الفعالية' : 'Event date'}><TextInput type="date" value={meta.eventDate || ''} onChange={(e) => setM('eventDate', e.target.value)} /></Field>
                      <Field label={ar ? 'وقت الفعالية' : 'Event time'}><TextInput type="time" value={meta.eventTime || ''} onChange={(e) => setM('eventTime', e.target.value)} /></Field>
                    </div>
                    <Field label={ar ? 'موقع التجهيز' : 'Setup location'}><TextInput value={meta.setupLocation || ''} onChange={(e) => setM('setupLocation', e.target.value)} /></Field>
                    <Field label={ar ? 'ملاحظات التجهيز' : 'Setup notes'}><Textarea rows={2} value={meta.setupNotes || ''} onChange={(e) => setM('setupNotes', e.target.value)} /></Field>
                  </>}
                  {!isFloral && !isEvent && <Field label={ar ? 'ملاحظة (اختياري)' : 'Note (optional)'}><Textarea rows={2} value={meta.note || ''} onChange={(e) => setM('note', e.target.value)} /></Field>}
                </div>
              )}

              {/* qty + actions */}
              <div style={{ marginTop: 20, display: 'flex', flexWrap: 'wrap', gap: 12, alignItems: 'center' }}>
                {!isDigital && !item.requestQuote && (
                  <span style={{ display: 'inline-flex', alignItems: 'center', border: '1px solid var(--line-strong)', borderRadius: 10, background: 'var(--white)' }}>
                    <QtyBtn onClick={() => setQty(Math.max(1, qty - 1))} icon="minus" /><span style={{ minWidth: 34, textAlign: 'center', fontWeight: 600 }}>{qty}</span><QtyBtn onClick={() => setQty(qty + 1)} icon="plus" />
                  </span>
                )}
              </div>
              {item.requestQuote ? (
                <div style={{ display: 'grid', gap: 9, marginTop: 14 }}>
                  <Button variant="primary" full icon="file-text" onClick={() => go('design')}>{ar ? 'اطلب عرض سعر' : 'Request a Quote'}</Button>
                  {React.createElement(Button, { variant: "primary", full: true, icon: "file-text", onClick: () => window.openItemRFQModal && window.openItemRFQModal(item) }, ar ? 'اطلب عرض سعر' : 'Request a Quote')}
                </div>
              ) : (
                <div style={{ display: 'grid', gap: 9, marginTop: 14 }}>
                  <div style={{ display: 'flex', gap: 9 }}>
                    <Button variant="secondary" full icon={cart.has(item.id) ? 'check' : 'shopping-bag'} onClick={addToCart} disabled={sold}>{ar ? 'أضف إلى السلة' : 'Add to Cart'}</Button>
                    <Button variant="primary" full icon="zap" onClick={buyNow} disabled={sold}>{ar ? 'اشترِ الآن' : 'Buy Now'}</Button>
                  </div>
                  {item.link
                    ? <Button variant="gold" full icon="wand-sparkles" href={item.link} target="_blank">{item.linkLabel ? (item.linkLabel[lang] || item.linkLabel.en) : (ar ? 'افتح' : 'Open')}</Button>
                    : React.createElement(Button, { variant: "primary", full: true, icon: "file-text", onClick: () => window.openItemRFQModal && window.openItemRFQModal(item) }, ar ? 'اطلب عرض سعر' : 'Request a Quote')}
                </div>
              )}

              {/* delivery/setup info line */}
              <div style={{ marginTop: 16, fontSize: 12.5, color: 'var(--fg-muted)', display: 'flex', flexDirection: 'column', gap: 5 }}>
                {isDigital
                  ? <span style={{ display: 'flex', alignItems: 'center', gap: 7 }}><Icon name="download" size={14} />{ar ? 'تحميل فوري بعد الدفع — لا رسوم توصيل.' : 'Instant download after payment — no delivery fee.'}</span>
                  : <>
                    <span style={{ display: 'flex', alignItems: 'center', gap: 7 }}><Icon name="truck" size={14} />{ar ? 'توصيل داخل الإمارات. مجاني للطلبات فوق ٥٠٠ درهم.' : 'UAE delivery. Free over AED 500.'}</span>
                    <span style={{ display: 'flex', alignItems: 'center', gap: 7 }}><Icon name="shield-check" size={14} />{ar ? 'دفع آمن.' : 'Secure payment.'}</span>
                  </>}
              </div>
            </div>
          </div>

          {/* reviews */}
          {window.ProductReviews && (
            <div style={{ marginTop: 56 }}>
              <SectionHead eyebrow={ar ? 'التقييمات' : 'Reviews'} title={ar ? 'آراء العملاء' : 'Customer Reviews'} />
              <div style={{ marginTop: 24, maxWidth: 680 }}>
                {React.createElement(window.ProductReviews, { productId: item.supabaseId || item.id })}
              </div>
            </div>
          )}

          {/* related */}
          {related.length > 0 && (
            <div style={{ marginTop: 64 }}>
              <SectionHead eyebrow={ar ? 'قد يعجبك أيضًا' : 'You may also like'} title={ar ? 'منتجات ذات صلة' : 'Related products'} />
              <div className="saraya-grid-4" style={{ marginTop: 28 }}>
                {related.map((r) => <StoreCard key={r.id} item={r} />)}
              </div>
            </div>
          )}
        </Container>
      </Section>
      <StickyCartBar />
    </main>
  );
}

/* ---------------- bits ---------------- */
function StoreChip({ active, onClick, icon, children }) {
  return (
    <button onClick={onClick} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '9px 16px', borderRadius: 999, whiteSpace: 'nowrap', flexShrink: 0, fontFamily: 'var(--font-body)', fontSize: 13.5, fontWeight: 500, cursor: 'pointer', background: active ? 'var(--espresso)' : 'var(--white)', color: active ? 'var(--ivory)' : 'var(--fg-primary)', border: '1px solid ' + (active ? 'var(--espresso)' : 'var(--line-strong)'), transition: 'all 180ms var(--ease-out)' }}>
      <Icon name={icon} size={15} />{children}
    </button>
  );
}
function TrustBar() {
  const { lang } = useLang(); const ar = lang === 'ar';
  const items = [
    { icon: 'shield-check', t: ar ? 'دفع آمن' : 'Secure payment' },
    { icon: 'truck', t: ar ? 'توصيل داخل الإمارات' : 'UAE delivery available' },
    { icon: 'download', t: ar ? 'تحميل فوري للمنتجات الرقمية' : 'Instant digital downloads' },
    { icon: 'message-circle', t: ar ? 'دعم عبر واتساب' : 'WhatsApp support' },
  ];
  return (
    <div style={{ background: 'var(--white)', borderBottom: '1px solid var(--line)' }}>
      <Container wide style={{ display: 'flex', flexWrap: 'wrap', gap: 18, justifyContent: 'center', paddingBlock: 14 }}>
        {items.map((x, i) => <span key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--fg-secondary)' }}><Icon name={x.icon} size={16} style={{ color: 'var(--gold-deep)' }} />{x.t}</span>)}
      </Container>
    </div>
  );
}
/* sticky cart + WhatsApp on mobile */
function StickyCartBar() {
  const { lang } = useLang(); const cart = useCart(); const { go } = useNav();
  if (cart.count === 0) return null;
  return (
    <div className="saraya-sticky-cart" style={{ position: 'fixed', insetInline: 0, bottom: 0, zIndex: 70, padding: '0 14px 14px', pointerEvents: 'none' }}>
      <div style={{ maxWidth: 520, margin: '0 auto', display: 'flex', gap: 9, pointerEvents: 'auto' }}>
        <button onClick={() => cart.setOpen(true)} style={{ flex: 1, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 10, padding: '14px 20px', borderRadius: 999, background: 'var(--espresso)', color: 'var(--ivory)', border: 'none', cursor: 'pointer', boxShadow: 'var(--shadow-deep)', fontFamily: 'var(--font-body)', fontSize: 14.5, fontWeight: 600 }}>
          <Icon name="shopping-bag" size={19} />{lang === 'ar' ? 'السلة' : 'View Cart'} · {money(cart.totals.total)}
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { StorePage, StoreCard, ProductDetailPage, effPrice });
