/* ── Zafa — Customer marketplace: browse products, My products, detail ── */

const PROD_STATUS = {
  active:  { en:'Active', ar:'نشط', tone:'#2E9E6B', bg:'#E6F4EC' },
  pending: { en:'Pending review', ar:'قيد المراجعة', tone:'#A9711F', bg:'#FBF3DC' },
  sold:    { en:'Sold', ar:'مُباع', tone:'#7B7177', bg:'#F1EDEF' },
};

/* product card (grid) */
function ProductCard({ p, onClick }) {
  const { lang } = useZafa();
  const cat = catOf(p.cat) || CATEGORIES[0];
  return (
    <div className="z-card" style={{ cursor: 'pointer' }} onClick={onClick}>
      <div style={{ padding: '12px 12px 0' }}>
        <div style={{ position: 'relative', aspectRatio: '1', borderRadius: 13, overflow: 'hidden' }}>
          <CoverArt theme={catTheme(p.cat)} icon={cat.icon} cat={p.cat} kw={p.kw} id={`prod-${p.id}`} seed={'pr' + p.id} radius={13} w={400} h={400} ph={L(lang, 'Add photo', 'أضف صورة')} />
        </div>
      </div>
      <div style={{ padding: '10px 12px 13px' }}>
        <p style={{ margin: 0, fontSize: 13.5, fontWeight: 600, lineHeight: 1.25, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{L(lang, p.en, p.ar)}</p>
        <p className="serif" style={{ margin: '4px 0 0', fontSize: 16, fontWeight: 700, color: 'var(--rose-deep)' }}>AED {p.price.toLocaleString()}</p>
        <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 4, color: 'var(--muted)', fontSize: 11.5 }}>
          <Icon name="pin" size={12} />{p.loc}
        </div>
      </div>
    </div>
  );
}

/* Marketplace browse — products grouped by category + a "+" to list */
function MarketplaceBrowse() {
  const { lang, push, pop } = useZafa();
  const [q, setQ] = React.useState('');
  const cats = [...new Set(PRODUCTS.map((p) => p.cat))];
  const ql = q.trim().toLowerCase();
  const match = (p) => !ql || L(lang, p.en, p.ar).toLowerCase().includes(ql) || (catOf(p.cat) && catOf(p.cat).en.toLowerCase().includes(ql));

  return (
    <div className="z-scroll no-bar dock-pad" style={{ background: 'var(--bg)' }}>
      <div style={{ padding: '10px 20px 4px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, minWidth: 0 }}>
          <button onClick={pop} className="z-glass" style={{ background: '#fff', border: '1px solid var(--line)', flexShrink: 0 }}><Icon name="left" size={20} className="flip-x" /></button>
          <div>
            <p className="eyebrow" style={{ marginBottom: 4 }}>{L(lang, 'Pre-loved', 'مستعمل بحالة جيدة')}</p>
            <h1 className="h1" style={{ margin: 0, fontSize: 26 }}>{L(lang, 'Marketplace', 'السوق')}</h1>
          </div>
        </div>
        <button onClick={() => push({ name: 'postad' })} aria-label="List a product"
          style={{ width: 48, height: 48, borderRadius: '50%', border: 'none', cursor: 'pointer', background: 'var(--rose)', color: 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 6px 16px rgba(246,176,198,.6)', flexShrink: 0 }}>
          <Icon name="plus" size={24} stroke={2.6} />
        </button>
      </div>

      <div style={{ padding: '14px 20px 4px' }}>
        <SearchField value={q} onChange={(e) => setQ(e.target.value)} placeholder={L(lang, 'Search products', 'ابحث عن المنتجات')} />
      </div>

      {ql ? (
        <div style={{ padding: '16px 20px 30px' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 13 }}>
            {PRODUCTS.filter(match).map((p) => <ProductCard key={p.id} p={p} onClick={() => push({ name: 'product', id: p.id })} />)}
          </div>
          {PRODUCTS.filter(match).length === 0 && <EmptyState icon="search" title={L(lang, 'No products found', 'لا منتجات')} sub={L(lang, 'Try a different search.', 'جرّب بحثاً آخر.')} />}
        </div>
      ) : (
        cats.map((cid) => {
          const cat = catOf(cid) || CATEGORIES[0];
          const items = PRODUCTS.filter((p) => p.cat === cid);
          return (
            <div key={cid} style={{ padding: '16px 20px 4px' }}>
              <SectionHeader icon={cat.icon} iconColor="var(--rose-deep)" title={L(lang, cat.en, cat.ar)} />
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 13 }}>
                {items.map((p) => <ProductCard key={p.id} p={p} onClick={() => push({ name: 'product', id: p.id })} />)}
              </div>
            </div>
          );
        })
      )}
    </div>
  );
}

/* Product detail (marketplace view — contact seller) */
function ProductDetail({ id }) {
  const { lang, pop } = useZafa();
  const all = [...PRODUCTS, ...(window.__myProducts || MY_PRODUCTS)];
  const p = all.find((x) => x.id === id);
  if (!p) return null;
  const cat = catOf(p.cat) || CATEGORIES[0];
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)' }}>
      <div className="z-scroll no-bar" style={{ flex: 1 }}>
        <div style={{ position: 'relative', height: 300 }}>
          <CoverArt theme={catTheme(p.cat)} icon={cat.icon} cat={p.cat} kw={p.kw} id={`prodbig-${p.id}`} seed={'pr' + p.id} w={800} h={800} />
          <button onClick={pop} className="z-glass" style={{ position: 'absolute', top: 16, insetInlineStart: 16 }}><Icon name="left" size={20} className="flip-x" /></button>
        </div>
        <div style={{ padding: '18px 20px 24px' }}>
          <span style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--rose-deep)' }}>{L(lang, cat.en, cat.ar)}</span>
          <h1 className="serif" style={{ margin: '6px 0 6px', fontSize: 24, fontWeight: 600 }}>{L(lang, p.en, p.ar)}</h1>
          <p className="serif" style={{ margin: 0, fontSize: 26, fontWeight: 700, color: 'var(--rose-deep)' }}>AED {p.price.toLocaleString()}</p>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 10, color: 'var(--ink-2)', fontSize: 13.5 }}>
            <Icon name="pin" size={15} style={{ color: 'var(--muted)' }} />{p.loc}{p.seller ? ` · ${p.seller}` : ''}
          </div>
          <p className="sec" style={{ margin: '16px 0 0', fontSize: 14.5, lineHeight: 1.55, textWrap: 'pretty' }}>
            {L(lang, 'Gently used and in excellent condition. Perfect for couples planning their big day on a budget. Message the seller for more photos or to arrange pickup.', 'مستعمل بعناية وبحالة ممتازة. مثالي للمقبلين على الزواج بميزانية محدودة. راسل البائع لمزيد من الصور أو لترتيب الاستلام.')}
          </p>
        </div>
      </div>
      <div style={{ padding: '12px 20px 26px', borderTop: '1px solid var(--line)', background: '#fff', display: 'flex', gap: 12 }}>
        <a href="https://wa.me/971500000000" target="_blank" rel="noopener" style={{ width: 54, height: 54, borderRadius: 14, background: '#25D366', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, textDecoration: 'none' }}><Icon name="whatsapp" size={24} /></a>
        <div style={{ flex: 1 }}><Btn variant="rose" icon="chat">{L(lang, 'Message seller', 'مراسلة البائع')}</Btn></div>
      </div>
    </div>
  );
}

/* My products list */
function MyProducts() {
  const { lang, pop, push } = useZafa();
  const items = window.__myProducts || MY_PRODUCTS;
  return (
    <div className="z-scroll no-bar" style={{ background: 'var(--bg)' }}>
      <div style={{ padding: '6px 20px 6px' }}>
        <ScreenHeader title={L(lang, 'My products', 'منتجاتي')} onBack={pop} right={
          <button onClick={() => push({ name: 'postad' })} className="z-glass" style={{ background: 'var(--rose)', border: 'none', color: 'var(--ink)' }}><Icon name="plus" size={20} stroke={2.4} /></button>
        } />
      </div>
      {items.length === 0 ? (
        <div style={{ height: 'calc(100% - 60px)' }}><EmptyState icon="store" title={L(lang, 'No products yet', 'لا منتجات بعد')} sub={L(lang, 'List your pre-loved wedding items to sell on the marketplace.', 'اعرض أغراض زفافك للبيع في السوق.')} cta={L(lang, 'List a product', 'أضف منتجاً')} onCta={() => push({ name: 'postad' })} /></div>
      ) : (
        <div style={{ padding: '12px 20px 30px', display: 'flex', flexDirection: 'column', gap: 12 }}>
          {items.map((p) => {
            const cat = catOf(p.cat) || CATEGORIES[0];
            const st = PROD_STATUS[p.status] || PROD_STATUS.active;
            return (
              <div key={p.id} className="z-card" style={{ padding: 12, display: 'flex', gap: 13, alignItems: 'center', cursor: 'pointer' }} onClick={() => push({ name: 'myproduct', id: p.id })}>
                <div style={{ width: 64, height: 64, borderRadius: 13, overflow: 'hidden', flexShrink: 0 }}>
                  <CoverArt theme={catTheme(p.cat)} icon={cat.icon} cat={p.cat} kw={p.kw} id={`myp-${p.id}`} seed={'mp' + p.id} radius={12} w={180} h={180} />
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <p style={{ margin: 0, fontSize: 14.5, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{L(lang, p.en, p.ar)}</p>
                  <p className="serif" style={{ margin: '3px 0 0', fontSize: 15, fontWeight: 700, color: 'var(--rose-deep)' }}>AED {p.price.toLocaleString()}</p>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 5 }}>
                    <span style={{ fontSize: 10.5, fontWeight: 700, color: st.tone, background: st.bg, padding: '2px 8px', borderRadius: 999 }}>{L(lang, st.en, st.ar)}</span>
                    <span className="muted" style={{ fontSize: 11.5, display: 'inline-flex', alignItems: 'center', gap: 3 }}><Icon name="user" size={12} />{p.views}</span>
                  </div>
                </div>
                <Icon name="right" size={18} className="flip-x" style={{ color: 'var(--muted)' }} />
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

/* My product detail — edit & delete */
function MyProductDetail({ id }) {
  const { lang, pop } = useZafa();
  const items = window.__myProducts || MY_PRODUCTS;
  const base = items.find((x) => x.id === id);
  const [editing, setEditing] = React.useState(false);
  const [p, setP] = React.useState(base || {});
  const [removed, setRemoved] = React.useState(false);
  if (!base) return null;
  const cat = catOf(p.cat) || CATEGORIES[0];
  const st = PROD_STATUS[p.status] || PROD_STATUS.active;

  if (removed) {
    return (
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '30px 28px', background: 'var(--bg)', textAlign: 'center' }}>
        <div style={{ width: 96, height: 96, borderRadius: '50%', background: 'var(--rose-100)', color: 'var(--rose-deep)', display: 'flex', alignItems: 'center', justifyContent: 'center', animation: 'pop .5s' }}><Icon name="check" size={46} stroke={2.6} /></div>
        <h1 className="h1" style={{ margin: '22px 0 8px' }}>{L(lang, 'Product removed', 'تم حذف المنتج')}</h1>
        <p className="sec" style={{ margin: 0, fontSize: 15 }}>{L(lang, 'Your listing has been deleted.', 'تم حذف إعلانك.')}</p>
        <div style={{ marginTop: 26, width: '100%', maxWidth: 260 }}><Btn variant="rose" onClick={pop}>{L(lang, 'Back to my products', 'العودة لمنتجاتي')}</Btn></div>
      </div>
    );
  }

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)' }}>
      <div style={{ padding: '6px 20px 6px' }}><ScreenHeader title={editing ? L(lang, 'Edit product', 'تعديل المنتج') : L(lang, 'My product', 'منتجي')} onBack={editing ? () => setEditing(false) : pop} /></div>
      <div className="z-scroll no-bar" style={{ flex: 1, padding: '8px 20px 20px' }}>
        {/* image */}
        <div style={{ position: 'relative', height: 180, borderRadius: 18, overflow: 'hidden', marginBottom: 18 }}>
          <CoverArt theme={catTheme(p.cat)} icon={cat.icon} cat={p.cat} kw={p.kw} id={`mpd-${p.id}`} seed={'mp' + p.id} radius={18} w={600} h={360} />
          {editing && <Img id={`mpd-up-${p.id}`} radius={18} ph="" style={{ position: 'absolute', inset: 0 }} />}
          {editing && <span className="z-glass" style={{ position: 'absolute', top: 10, insetInlineEnd: 10, width: 34, height: 34, pointerEvents: 'none' }}><Icon name="image" size={17} /></span>}
        </div>

        {editing ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <AdField label={L(lang, 'Product name', 'اسم المنتج')}><input className="z-input" value={lang === 'ar' ? p.ar : p.en} onChange={(e) => setP((s) => ({ ...s, [lang === 'ar' ? 'ar' : 'en']: e.target.value }))} /></AdField>
            <AdField label={L(lang, 'Price (AED)', 'السعر (درهم)')}><input className="z-input" inputMode="numeric" value={p.price} onChange={(e) => setP((s) => ({ ...s, price: Number(e.target.value.replace(/\D/g, '') || 0) }))} style={{ direction: 'ltr', textAlign: lang === 'ar' ? 'right' : 'left' }} /></AdField>
            <AdField label={t2(lang, 'Location', 'الموقع')}>
              <div className="no-bar" style={{ display: 'flex', gap: 9, overflowX: 'auto', paddingBottom: 4 }}>
                {CITIES.map((c) => <Chip key={c} on={p.loc === c} onClick={() => setP((s) => ({ ...s, loc: c }))}>{c}</Chip>)}
              </div>
            </AdField>
          </div>
        ) : (
          <>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
              <span style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--rose-deep)' }}>{L(lang, cat.en, cat.ar)}</span>
              <span style={{ fontSize: 10.5, fontWeight: 700, color: st.tone, background: st.bg, padding: '2px 8px', borderRadius: 999 }}>{L(lang, st.en, st.ar)}</span>
            </div>
            <h1 className="serif" style={{ margin: '0 0 6px', fontSize: 23, fontWeight: 600 }}>{L(lang, p.en, p.ar)}</h1>
            <p className="serif" style={{ margin: 0, fontSize: 24, fontWeight: 700, color: 'var(--rose-deep)' }}>AED {p.price.toLocaleString()}</p>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 10, color: 'var(--ink-2)', fontSize: 13.5 }}><Icon name="pin" size={15} style={{ color: 'var(--muted)' }} />{p.loc}</div>

            {/* performance stats */}
            <div className="z-card" style={{ marginTop: 16, padding: 14, display: 'flex', gap: 8 }}>
              {[
                { lbl: L(lang, 'Views', 'المشاهدات'), v: p.views, serif: true },
                { lbl: L(lang, 'Saves', 'الحفظ'), v: Math.round(p.views * 0.18), serif: true },
                { lbl: L(lang, 'Messages', 'الرسائل'), v: Math.round(p.views * 0.05), serif: true }].map((m, i) => (
                <div key={i} style={{ flex: 1, textAlign: 'center', borderInlineEnd: i < 2 ? '1px solid var(--line-2)' : 'none' }}>
                  <p className="serif" style={{ margin: 0, fontSize: 19, fontWeight: 700 }}>{m.v}</p>
                  <p className="muted" style={{ margin: '2px 0 0', fontSize: 11.5, fontWeight: 600 }}>{m.lbl}</p>
                </div>
              ))}
            </div>

            {/* description */}
            <p className="lbl" style={{ margin: '20px 0 8px' }}>{L(lang, 'Description', 'الوصف')}</p>
            <p className="sec" style={{ margin: 0, fontSize: 14, lineHeight: 1.55, textWrap: 'pretty' }}>
              {L(lang, 'Gently used and in excellent condition — worn once. Dry-cleaned and stored carefully. Includes the matching veil. Open to reasonable offers.', 'مستعمل بعناية وبحالة ممتازة — لُبس مرّة واحدة. تم تنظيفه وحفظه بعناية. يشمل الطرحة المطابقة. أرحّب بالعروض المعقولة.')}
            </p>

            {/* item details */}
            <p className="lbl" style={{ margin: '20px 0 8px' }}>{L(lang, 'Item details', 'تفاصيل الغرض')}</p>
            <div className="z-card" style={{ padding: '4px 16px' }}>
              {[
                [L(lang, 'Condition', 'الحالة'), L(lang, 'Like new', 'كالجديد')],
                [L(lang, 'Size', 'المقاس'), L(lang, 'M (UK 10)', 'M')],
                [L(lang, 'Listed', 'تاريخ النشر'), L(lang, '12 Jun 2026', '١٢ يونيو ٢٠٢٦')],
                [L(lang, 'Listing ID', 'رقم الإعلان'), p.id.toUpperCase()]].map(([k, v], i, a) => (
                <div key={k} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 0', borderBottom: i < a.length - 1 ? '1px solid var(--line-2)' : 'none' }}>
                  <span className="sec" style={{ fontSize: 13.5 }}>{k}</span>
                  <span style={{ fontSize: 13.5, fontWeight: 600 }}>{v}</span>
                </div>
              ))}
            </div>

            {/* listing / fee */}
            <p className="lbl" style={{ margin: '20px 0 8px' }}>{L(lang, 'Listing', 'الإعلان')}</p>
            <div className="z-card" style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 12 }}>
              <span style={{ width: 36, height: 36, borderRadius: 11, background: 'var(--rose-100)', color: 'var(--rose-deep)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="spark" size={18} /></span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <p style={{ margin: 0, fontSize: 13.5, fontWeight: 600 }}>{p.status === 'pending' ? L(lang, 'Awaiting admin approval', 'بانتظار موافقة الإدارة') : L(lang, 'Live · expires in 5 days', 'منشور · ينتهي خلال ٥ أيام')}</p>
                <p className="muted" style={{ margin: '1px 0 0', fontSize: 12 }}>{L(lang, 'AED 15 / week listing fee', 'رسوم النشر ١٥ درهم/أسبوع')}</p>
              </div>
              <button style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--rose-deep)', fontWeight: 700, fontSize: 13, fontFamily: 'var(--sans)', flexShrink: 0 }}>{L(lang, 'Renew', 'تجديد')}</button>
            </div>
          </>
        )}
      </div>
      <div style={{ padding: '12px 20px 26px', borderTop: '1px solid var(--line)', background: '#fff', display: 'flex', gap: 12 }}>
        {editing ? (
          <Btn variant="rose" onClick={() => setEditing(false)}>{L(lang, 'Save changes', 'حفظ التغييرات')}</Btn>
        ) : (
          <>
            <button onClick={() => setRemoved(true)} style={{ width: 54, height: 54, borderRadius: 14, border: '1.5px solid #E0A99F', background: '#fff', cursor: 'pointer', color: '#C0392B', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="trash" size={22} /></button>
            <div style={{ flex: 1 }}><Btn variant="ink" icon="edit" onClick={() => setEditing(true)}>{L(lang, 'Edit product', 'تعديل المنتج')}</Btn></div>
          </>
        )}
      </div>
    </div>
  );
}
function t2(lang, en, ar) { return lang === 'ar' ? ar : en; }

Object.assign(window, { MarketplaceBrowse, ProductDetail, MyProducts, MyProductDetail, ProductCard, PROD_STATUS });
