/* ── Zafa — Vendor profile + Payment ────────────────────────────────── */

function ContactBtn({ icon, label, color, href }) {
  return (
    <a href={href} target="_blank" rel="noopener" style={{ textDecoration: 'none', flex: 1, minWidth: 0 }}>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
        <div style={{ width: 52, height: 52, borderRadius: 16, background: color, color: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: 'var(--sh-sm)' }}>
          <Icon name={icon} size={23} stroke={2} style={{ color: '#ffffff' }} />
        </div>
        <span style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--ink-2)' }}>{label}</span>
      </div>
    </a>
  );
}

/* ── Gallery popup slider / lightbox ── */
function GalleryLightbox({ v, cat, svc = '', kws, total, start, lang, onClose }) {
  const [idx, setIdx] = React.useState(start);
  const go = (d) => setIdx((p) => (p + d + total) % total);
  const kw = kws[idx % kws.length];
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); if (e.key === 'ArrowRight') go(1); if (e.key === 'ArrowLeft') go(-1); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);
  return (
    <div onClick={onClose} style={{ position: 'absolute', inset: 0, zIndex: 90, background: 'rgba(12,8,10,.92)', backdropFilter: 'blur(6px)', display: 'flex', flexDirection: 'column', animation: 'fadeIn .2s' }}>
      {/* header */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 18px 8px', color: '#fff' }}>
        <span style={{ fontSize: 14, fontWeight: 600 }}>{idx + 1} / {total}</span>
        <button onClick={(e) => { e.stopPropagation(); onClose(); }} className="z-glass" style={{ background: 'rgba(255,255,255,.16)', color: '#fff', boxShadow: 'none' }}><Icon name="x" size={20} /></button>
      </div>

      {/* main image */}
      <div onClick={(e) => e.stopPropagation()} style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '0 16px', position: 'relative', minHeight: 0 }}>
        <div style={{ width: '100%', aspectRatio: '4/5', maxHeight: '100%', borderRadius: 18, overflow: 'hidden', boxShadow: '0 20px 50px rgba(0,0,0,.5)' }}>
          <CoverArt key={idx} theme={v.theme} icon={cat.icon} cat={v.cat} kw={kw} seed={'lb' + svc + idx + v.id} id={`lb-${v.id}-${idx}`} radius={18} w={640} h={800} />
        </div>
        {/* arrows */}
        <button onClick={(e) => { e.stopPropagation(); go(-1); }} style={lbArrow('start')}><Icon name="left" size={22} className="flip-x" /></button>
        <button onClick={(e) => { e.stopPropagation(); go(1); }} style={lbArrow('end')}><Icon name="right" size={22} className="flip-x" /></button>
      </div>

      {/* thumbnail strip */}
      <div onClick={(e) => e.stopPropagation()} className="no-bar" style={{ display: 'flex', gap: 8, overflowX: 'auto', padding: '14px 16px 26px', scrollSnapType: 'x mandatory' }}>
        {Array.from({ length: total }).map((_, i) => (
          <div key={i} onClick={() => setIdx(i)} style={{ flexShrink: 0, width: 56, height: 56, borderRadius: 11, overflow: 'hidden', cursor: 'pointer', scrollSnapAlign: 'center', border: i === idx ? '2.5px solid var(--rose)' : '2.5px solid transparent', opacity: i === idx ? 1 : .6 }}>
            <CoverArt theme={v.theme} icon={cat.icon} cat={v.cat} kw={kws[i % kws.length]} seed={'lb' + svc + i + v.id} id={`lbt-${v.id}-${i}`} radius={9} w={120} h={120} />
          </div>
        ))}
      </div>
    </div>
  );
}
function lbArrow(side) {
  return { position: 'absolute', insetInlineStart: side === 'start' ? 22 : 'auto', insetInlineEnd: side === 'end' ? 22 : 'auto', top: '50%', transform: 'translateY(-50%)', width: 44, height: 44, borderRadius: '50%', border: 'none', cursor: 'pointer', background: 'rgba(255,255,255,.92)', color: 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 6px 16px rgba(0,0,0,.3)' };
}

/* additional services a vendor also offers — each switches Services + Gallery */
const SVC_LIB = {
  photography: { icon: 'camera', en: 'Photography', ar: 'التصوير',
    services: [['Full-day coverage', 'تغطية يوم كامل'], ['Engagement shoot', 'جلسة خطوبة'], ['Album & prints', 'ألبوم ومطبوعات'], ['Second shooter', 'مصوّر إضافي']],
    kw: ['wedding,photography,couple', 'wedding,photographer,candid', 'wedding,photo,ceremony', 'wedding,portrait,bride', 'wedding,photo,details', 'wedding,photography,reception', 'wedding,photo,blackandwhite', 'wedding,photographer,goldenhour'] },
  videography: { icon: 'video', en: 'Videography', ar: 'تصوير فيديو',
    services: [['Cinematic highlight film', 'فيلم ملخّص سينمائي'], ['Full ceremony film', 'تصوير المراسم كاملة'], ['Drone coverage', 'تصوير بالدرون'], ['Same-day edit', 'مونتاج بنفس اليوم']],
    kw: ['wedding,videography,film', 'wedding,video,cinematic', 'wedding,film,drone', 'wedding,video,ceremony', 'wedding,videographer,couple', 'wedding,film,reception', 'wedding,video,details', 'wedding,cinematography,bride'] },
  makeup: { icon: 'makeup', en: 'Makeup', ar: 'المكياج',
    services: [['Bridal makeup', 'مكياج العروس'], ['Trial session', 'جلسة تجريبية'], ['Bridesmaids glam', 'مكياج الوصيفات'], ['Airbrush finish', 'مكياج إيربراش']],
    kw: ['bridal,makeup,beauty', 'wedding,makeup,bride', 'makeup,artist,glam', 'bridal,beauty,portrait', 'wedding,makeup,details', 'makeup,bridal,lipstick', 'bridal,glam,eyes', 'wedding,beauty,bride'] },
  food: { icon: 'food', en: 'Food & Catering', ar: 'الطعام والضيافة',
    services: [['Buffet service', 'خدمة البوفيه'], ['Live cooking stations', 'محطات طهي مباشرة'], ['Plated fine dining', 'عشاء فاخر مُقدّم'], ['Dessert table', 'طاولة الحلويات']],
    kw: ['wedding,catering,buffet', 'wedding,food,plated', 'wedding,banquet,table', 'wedding,catering,canape', 'wedding,food,dessert', 'wedding,dining,reception', 'wedding,catering,station', 'wedding,food,gourmet'] },
  kiosk: { icon: 'kiosk', en: 'Kiosks', ar: 'الأكشاك',
    services: [['Coffee & tea kiosk', 'كشك القهوة والشاي'], ['Dates & sweets kiosk', 'كشك التمور والحلى'], ['Favors kiosk', 'كشك الهدايا'], ['Custom branded setup', 'تجهيز مخصّص بعلامتك']],
    kw: ['wedding,kiosk,coffee', 'wedding,dessert,stand', 'wedding,sweets,table', 'wedding,favors,gifts', 'wedding,kiosk,setup', 'wedding,catering,cart', 'wedding,dates,arabic', 'wedding,stand,decor'] },
};

function VendorProfile({ id }) {
  const { lang, t, pop, wish, toggleWish, push } = useZafa();
  const v = VENDORS.find(x => x.id === id);
  if (!v) return null;
  const cat = catOf(v.cat);
  const th = THEMES[v.theme] || THEMES.rose;
  const saved = wish.has(v.id);
  const tags = [cat, ...CATEGORIES.filter(c => c.id !== v.cat).slice(0, 2)];

  // ── multi-service support ──
  const galleryTotal = 38;
  const [lightbox, setLightbox] = React.useState(null); // null | index
  const [activeSvc, setActiveSvc] = React.useState('primary'); // 'primary' | photography | videography | makeup

  // primary (flowers) service is built from the vendor's own data
  const primarySvc = {
    icon: cat.icon, en: cat.en, ar: cat.ar,
    services: v.services.map((s) => [s, s]),
    kw: ['bouquet', 'flowers', 'wedding,flowers,arch', 'wedding,floral,decor', 'flowers,table', 'roses', 'wedding,flowers,aisle', 'wedding,floral,installation'],
  };
  const cur = activeSvc === 'primary' ? primarySvc : SVC_LIB[activeSvc];
  const galleryKw = cur.kw;

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)' }}>
      <div className="z-scroll no-bar" style={{ flex: 1 }}>
        {/* cover */}
        <div style={{ position: 'relative', height: 268 }}>
          <CoverArt theme={v.theme} icon={cat.icon} cat={v.cat} src={v.id === 'v1' ? window.ASSET('vendorCover1') : undefined} id={`cover-${v.id}`} seed={'cv' + v.id} w={800} h={520} ph={L(lang, 'Add cover', 'أضف غلافاً')} />
          <div style={{ position: 'absolute', top: 0, insetInline: 0, height: 84, background: 'rgba(0,0,0,.14)' }} />
          {/* top controls */}
          <div style={{ position: 'absolute', top: 0, insetInline: 0, padding: '14px 16px', display: 'flex', justifyContent: 'space-between' }}>
            <button onClick={pop} style={ctrlBtn}><Icon name="left" size={20} className="flip-x" /></button>
            <div style={{ display: 'flex', gap: 9 }}>
              <button style={ctrlBtn}><Icon name="share" size={18} /></button>
              <button onClick={() => toggleWish(v.id)} style={{ ...ctrlBtn, color: saved ? 'var(--rose-deep)' : 'var(--ink)' }}><Icon name="heart" size={19} fill={saved ? 'currentColor' : 'none'} /></button>
            </div>
          </div>
          {/* floating profile picture — straddles the cover edge */}
          <div style={{ position: 'absolute', bottom: -38, insetInlineStart: 28, width: 92, height: 92, borderRadius: 24, overflow: 'hidden', border: '3px solid #fff', background: th.soft, boxShadow: '0 10px 26px rgba(27,20,24,.22)', zIndex: 3 }}>
            <CoverArt theme={v.theme} icon={cat.icon} cat={v.cat} src={monogramURI(v.name, v.theme, '#2C3550')} id={`logo-${v.id}`} seed={'lg' + v.id} radius={21} w={220} h={220} />
          </div>
        </div>

        {/* identity card */}
        <div style={{ padding: '0 18px', marginTop: 14, position: 'relative' }}>
          <div className="z-card" style={{ padding: '50px 18px 18px', borderRadius: 24 }}>
            <div style={{ display: 'flex', gap: 6, marginBottom: 6 }}><LevelBadge level={v.level} lang={lang} /></div>
            <h1 className="serif" style={{ margin: 0, fontSize: 25, fontWeight: 600, lineHeight: 1.1 }}>{vName(v, lang)}</h1>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 12, flexWrap: 'wrap' }}>
              <Rating value={v.rating} reviews={`${v.reviews} ${t('reviews')}`} lang={lang} />
              <span className="muted">·</span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, color: 'var(--ink-2)', fontSize: 13.5 }}><Icon name="pin" size={14} style={{ color: th.accent }} />{vLoc(v, lang)}</span>
            </div>
            <p className="sec" style={{ margin: '12px 0 0', fontSize: 14.5, lineHeight: 1.5, textWrap: 'pretty' }}>{v.tag}</p>
          </div>
        </div>

        {/* my other services — tabs switch Services + Gallery below */}
        <div style={{ padding: '20px 18px 4px' }}>
          <p className="lbl" style={{ marginBottom: 12 }}>{L(lang, 'My other services', 'خدماتي الأخرى')}</p>
          <div className="no-bar" style={{ display: 'flex', gap: 9, overflowX: 'auto' }}>
            {[{ id: 'primary', icon: primarySvc.icon, en: primarySvc.en, ar: primarySvc.ar }, ...['photography', 'videography', 'makeup', 'food', 'kiosk'].map((k) => ({ id: k, icon: SVC_LIB[k].icon, en: SVC_LIB[k].en, ar: SVC_LIB[k].ar }))].map((tb) => {
              const on = activeSvc === tb.id;
              return (
                <button key={tb.id} onClick={() => setActiveSvc(tb.id)} className={`z-chip${on ? ' z-chip--on' : ''}`} style={{ flexShrink: 0 }}>
                  <Icon name={tb.icon} size={15} />{L(lang, tb.en, tb.ar)}
                </button>
              );
            })}
          </div>
        </div>

        {/* contacts */}
        <div style={{ padding: '22px 18px 4px' }}>
          <p className="lbl" style={{ marginBottom: 14 }}>{t('contact')}</p>
          <div style={{ display: 'flex', gap: 8 }}>
            <ContactBtn icon="whatsapp" label="WhatsApp" color="#25D366" href="https://wa.me/971500000000" />
            <ContactBtn icon="phone" label={t('call')} color={th.accent} href="tel:+971500000000" />
            <ContactBtn icon="mail" label={t('email')} color="#5A4F54" href="mailto:hello@zafa.app" />
            <ContactBtn icon="instagram" label="Instagram" color="#C13584" href="https://instagram.com" />
            <ContactBtn icon="link" label={L(lang, 'Links', 'روابط')} color="#2C3550" href="https://zafa.app" />
          </div>
        </div>

        {/* about / company details */}
        <div style={{ padding: '22px 18px 4px' }}>
          <p className="lbl" style={{ marginBottom: 12 }}>{t('about')}</p>
          <div className="z-card" style={{ padding: 16 }}>
            <p className="sec" style={{ margin: 0, fontSize: 14, lineHeight: 1.55, textWrap: 'pretty' }}>
              {L(lang,
                `${v.name} is a ${LEVELS[v.level].en.toLowerCase()} ${cat.en.toLowerCase()} studio based in ${v.loc.split('·')[0].trim()}, crafting bespoke celebrations since 2019. Our team brings an editorial eye and white-glove service to every wedding.`,
                `${v.ar} استوديو ${L(lang, LEVELS[v.level].en, LEVELS[v.level].ar)} لـ${cat.ar} في ${v.locAr.split('·')[0].trim()}، يصمّم احتفالات مميّزة منذ ٢٠١٩ بلمسة راقية وخدمة استثنائية لكل عروسين.`)}
            </p>
            {/* stat row — alternating brand tints */}
            <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
              {[
                { ic: 'spark', v: '6+', en: 'Years', ar: 'سنوات', bg: '#FCE7EE', col: '#F6B0C6' },
                { ic: 'heart', v: `${v.reviews}+`, en: 'Weddings', ar: 'حفل', bg: '#DFE1E5', col: '#2C3550' },
                { ic: 'chat', v: '~2h', en: 'Response', ar: 'الرد', bg: '#F1ECDF', col: '#A98432' }].
              map((st) =>
              <div key={st.en} style={{ flex: 1, background: st.bg, borderRadius: 14, padding: '13px 8px', textAlign: 'center' }}>
                  <span style={{ color: st.col, display: 'flex', justifyContent: 'center', marginBottom: 5 }}><Icon name={st.ic} size={18} /></span>
                  <p className="serif" style={{ margin: 0, fontSize: 18, fontWeight: 700, color: 'var(--ink)' }}>{st.v}</p>
                  <p style={{ margin: '1px 0 0', fontSize: 11, fontWeight: 600, color: 'var(--ink-2)' }}>{L(lang, st.en, st.ar)}</p>
                </div>
              )}
            </div>
            {/* quick facts */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 16 }}>
              {[
                { ic: 'pin', label: L(lang, 'Service area', 'منطقة الخدمة'), val: L(lang, 'UAE-wide · travels for destination weddings', 'كل الإمارات · يسافر لحفلات الوجهات') },
                { ic: 'globe', label: L(lang, 'Languages', 'اللغات'), val: L(lang, 'English · العربية · Français', 'الإنجليزية · العربية · الفرنسية') },
                { ic: 'calendar', label: L(lang, 'Availability', 'التوفّر'), val: L(lang, 'Booking 2026 · 2027 seasons', 'حجوزات موسمي ٢٠٢٦ · ٢٠٢٧') }].
              map((f) =>
              <div key={f.label} style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
                  <span style={{ width: 30, height: 30, borderRadius: 9, background: '#fff', border: '1px solid #EDE8E1', color: th.accent, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name={f.ic} size={16} stroke={1.9} /></span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <p style={{ margin: 0, fontSize: 11.5, fontWeight: 600, color: 'var(--muted)' }}>{f.label}</p>
                    <p style={{ margin: '1px 0 0', fontSize: 13.5, fontWeight: 500, color: 'var(--ink)' }}>{f.val}</p>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* services — reflects the active service tab */}
        {cur.services.length > 0 && (
          <div style={{ padding: '22px 18px 4px' }}>
            <p className="lbl" style={{ marginBottom: 12, display: 'flex', alignItems: 'center', gap: 8 }}>{t('services')}<span style={{ color: 'var(--rose-deep)', fontWeight: 600 }}>· {L(lang, cur.en, cur.ar)}</span></p>
            <div className="z-card" style={{ padding: '4px 16px' }}>
              {cur.services.map(([sEn, sAr], i) => (
                <div key={sEn} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '15px 0', borderBottom: i < cur.services.length - 1 ? '1px solid var(--line-2)' : 'none' }}>
                  <span style={{ width: 30, height: 30, borderRadius: 9, background: th.soft, color: th.accent, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="check" size={17} /></span>
                  <span style={{ flex: 1, fontSize: 15, fontWeight: 500 }}>{L(lang, sEn, sAr)}</span>
                  <span style={{ fontSize: 13, color: 'var(--muted)' }}>{L(lang, 'from', 'من')} <b style={{ color: 'var(--ink)' }}>AED {((i + 2) * 850).toLocaleString()}</b></span>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* gallery — clickable, opens popup slider */}
        <div style={{ padding: '22px 18px 30px' }}>
          <p className="lbl" style={{ marginBottom: 12, display: 'flex', alignItems: 'center', gap: 8 }}>{L(lang, 'Gallery', 'المعرض')}<span style={{ color: 'var(--rose-deep)', fontWeight: 600 }}>· {L(lang, cur.en, cur.ar)}</span></p>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            {[0, 1, 2].map(i => {
              const last = i === 2;
              const more = galleryTotal - 3;
              return (
                <div key={i} onClick={() => setLightbox(i)} style={{ position: 'relative', aspectRatio: i % 3 === 0 ? '2/1.4' : '1/1', gridColumn: i % 3 === 0 ? 'span 2' : 'span 1', borderRadius: 15, overflow: 'hidden', cursor: 'pointer' }}>
                  <CoverArt theme={v.theme} icon={cur.icon} cat={v.cat} kw={galleryKw[i]} id={`gal-${v.id}-${activeSvc}-${i}`} seed={'gf' + activeSvc + i + v.id} radius={15} ph={L(lang, 'Add photo', 'أضف صورة')} />
                  {last && (
                    <div style={{ position: 'absolute', inset: 0, background: 'rgba(20,14,17,.55)', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', color: '#fff' }}>
                      <span className="serif" style={{ fontSize: 26, fontWeight: 700, lineHeight: 1 }}>+{more}</span>
                      <span style={{ fontSize: 11, fontWeight: 600, marginTop: 4, opacity: .9 }}>{L(lang, 'View all', 'عرض الكل')}</span>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>

        {/* reviews */}
        <div style={{ padding: '4px 18px 8px' }}>
          <p className="lbl" style={{ marginBottom: 12, display: 'flex', alignItems: 'center', gap: 8 }}>{L(lang, 'Reviews', 'التقييمات')}<span style={{ color: 'var(--rose-deep)', fontWeight: 600 }}>· {v.reviews}</span></p>
          {/* rating summary */}
          <div className="z-card" style={{ padding: 16, display: 'flex', alignItems: 'center', gap: 16, marginBottom: 12 }}>
            <div style={{ textAlign: 'center', flexShrink: 0 }}>
              <p className="serif" style={{ margin: 0, fontSize: 36, fontWeight: 700, lineHeight: 1 }}>{v.rating.toFixed(1)}</p>
              <div style={{ display: 'flex', gap: 2, marginTop: 5, justifyContent: 'center' }}>{[0, 1, 2, 3, 4].map(s => <StarFill key={s} size={13} color={s < Math.round(v.rating) ? '#C8A24A' : '#E6DFDA'} />)}</div>
              <p className="muted" style={{ margin: '5px 0 0', fontSize: 11.5 }}>{v.reviews} {L(lang, 'reviews', 'تقييم')}</p>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              {[[5, 86], [4, 10], [3, 3], [2, 1], [1, 0]].map(([star, pct]) => (
                <div key={star} style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 5 }}>
                  <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-2)', width: 8 }}>{star}</span>
                  <div style={{ flex: 1, height: 6, borderRadius: 99, background: 'var(--line)', overflow: 'hidden' }}><div style={{ width: pct + '%', height: '100%', background: '#C8A24A' }} /></div>
                </div>
              ))}
            </div>
          </div>
          {/* individual reviews */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {[
              { n: 'Mariam A.', nAr: 'مريم أ.', r: 5, t: 'Absolutely stunning work — they brought our vision to life perfectly. Highly recommend!', tAr: 'عمل رائع جداً — حقّقوا رؤيتنا بإتقان. أنصح بهم بشدة!', d: '2 weeks ago', dAr: 'قبل أسبوعين' },
              { n: 'Khalid R.', nAr: 'خالد ر.', r: 5, t: 'Professional, punctual and so easy to work with. The result exceeded expectations.', tAr: 'محترفون وملتزمون بالمواعيد. النتيجة فاقت التوقعات.', d: '1 month ago', dAr: 'قبل شهر' },
              { n: 'Noura S.', nAr: 'نورة س.', r: 4, t: 'Beautiful arrangements and lovely team. Would book again for our next event.', tAr: 'تنسيقات جميلة وفريق لطيف. سأحجز معهم مجدداً.', d: '2 months ago', dAr: 'قبل شهرين' },
            ].map((rv, i) => (
              <div key={i} className="z-card" style={{ padding: 14 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <span style={{ width: 38, height: 38, borderRadius: '50%', background: 'var(--rose-100)', color: 'var(--rose-deep)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, fontWeight: 700, fontSize: 14, fontFamily: 'var(--serif)' }}>{L(lang, rv.n, rv.nAr).charAt(0)}</span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <p style={{ margin: 0, fontSize: 14, fontWeight: 600 }}>{L(lang, rv.n, rv.nAr)}</p>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 2 }}>
                      <div style={{ display: 'flex', gap: 1 }}>{[0, 1, 2, 3, 4].map(s => <StarFill key={s} size={11} color={s < rv.r ? '#C8A24A' : '#E6DFDA'} />)}</div>
                      <span className="muted" style={{ fontSize: 11 }}>· {L(lang, rv.d, rv.dAr)}</span>
                    </div>
                  </div>
                </div>
                <p className="sec" style={{ margin: '10px 0 0', fontSize: 13.5, lineHeight: 1.5, textWrap: 'pretty' }}>{L(lang, rv.t, rv.tAr)}</p>
              </div>
            ))}
          </div>
          <button style={{ width: '100%', marginTop: 12, height: 46, borderRadius: 12, border: '1.5px solid var(--line)', background: '#fff', cursor: 'pointer', color: 'var(--ink)', fontWeight: 600, fontSize: 14, fontFamily: 'var(--sans)' }}>{L(lang, `See all ${v.reviews} reviews`, `عرض كل ${v.reviews} تقييم`)}</button>

          {/* post a comment */}
          <PostReview lang={lang} />
        </div>

        {/* disclaimer / good-to-know */}
        <div style={{ padding: '4px 18px 30px' }}>
          <div style={{ background: 'var(--rose-soft)', border: '1px solid #EDE8E1', borderRadius: 18, padding: '16px 16px 18px' }}>
            <p className="lbl" style={{ margin: '0 0 12px', display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ width: 24, height: 24, borderRadius: 7, background: 'var(--rose-100)', color: 'var(--rose-deep)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="shield" size={14} /></span>
              {L(lang, 'Good to know', 'معلومات مهمة')}
            </p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {[
                L(lang, 'Payments and bookings are completed directly with the vendor, outside the app.', 'تتم المدفوعات والحجوزات مباشرة مع المزوّد خارج التطبيق.'),
                L(lang, 'Zafa is a discovery platform and is not a party to any contract or transaction.', 'المنصّة وسيلة للاكتشاف فقط وليست طرفاً في أي عقد أو معاملة.'),
                L(lang, 'Prices shown are starting estimates and may vary by date, location and package.', 'الأسعار المعروضة تقديرية وقد تختلف حسب التاريخ والموقع والباقة.'),
                L(lang, 'Confirm availability, final pricing and terms with the vendor before paying.', 'أكّد التوفّر والسعر النهائي والشروط مع المزوّد قبل الدفع.'),
                L(lang, 'Avoid advance payments before verifying the vendor and agreement details.', 'تجنّب الدفع المسبق قبل التحقق من المزوّد وتفاصيل الاتفاق.'),
                L(lang, 'Report any suspicious activity to our support team.', 'أبلغ فريق الدعم عن أي نشاط مريب.')].
              map((pt, i) => (
                <div key={i} style={{ display: 'flex', gap: 9, alignItems: 'flex-start' }}>
                  <span style={{ color: 'var(--rose-deep)', flexShrink: 0, marginTop: 2 }}><Icon name="check" size={15} stroke={2.4} /></span>
                  <span style={{ fontSize: 12.5, lineHeight: 1.45, color: 'var(--ink-2)', textWrap: 'pretty' }}>{pt}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {lightbox !== null && (
        <GalleryLightbox v={v} cat={cat} svc={activeSvc} kws={galleryKw} total={galleryTotal} start={lightbox} lang={lang} onClose={() => setLightbox(null)} />
      )}

      {/* sticky CTA */}
      <div style={{ padding: '12px 18px 26px', background: 'rgba(255,255,255,.9)', backdropFilter: 'blur(16px)', borderTop: '1px solid var(--line)', display: 'flex', gap: 12, alignItems: 'center' }}>
        <button onClick={() => toggleWish(v.id)} style={{ width: 54, height: 54, borderRadius: 14, border: '1.5px solid var(--line)', background: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: saved ? 'var(--rose-deep)' : 'var(--ink)', flexShrink: 0 }}>
          <Icon name="heart" size={22} fill={saved ? 'currentColor' : 'none'} />
        </button>
        <div style={{ flex: 1 }}>
          <Btn variant="rose" icon="chat" onClick={() => push({ name: 'chat', id: v.id })}>{t('chatNow')}</Btn>
        </div>
      </div>
    </div>
  );
}

const ctrlBtn = { width: 42, height: 42, borderRadius: '50%', background: 'rgba(255,255,255,.9)', backdropFilter: 'blur(8px)', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink)', boxShadow: 'var(--sh-sm)' };

/* ── Post a comment / review ── */
function PostReview({ lang }) {
  const [rating, setRating] = React.useState(0);
  const [hover, setHover] = React.useState(0);
  const [text, setText] = React.useState('');
  const [sent, setSent] = React.useState(false);
  if (sent) {
    return (
      <div className="z-card fade-up" style={{ marginTop: 14, padding: 16, display: 'flex', alignItems: 'center', gap: 12 }}>
        <span style={{ width: 38, height: 38, borderRadius: '50%', background: 'var(--rose-100)', color: '#2E9E6B', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="check" size={20} stroke={2.6} /></span>
        <div style={{ flex: 1 }}>
          <p style={{ margin: 0, fontSize: 14, fontWeight: 600 }}>{L(lang, 'Thanks for your review!', 'شكراً على تقييمك!')}</p>
          <p className="muted" style={{ margin: '2px 0 0', fontSize: 12 }}>{L(lang, 'It will appear once approved.', 'سيظهر بعد الموافقة.')}</p>
        </div>
      </div>
    );
  }
  return (
    <div className="z-card" style={{ marginTop: 14, padding: 16 }}>
      <p style={{ margin: 0, fontSize: 14, fontWeight: 700 }}>{L(lang, 'Write a review', 'اكتب تقييماً')}</p>
      {/* star picker */}
      <div style={{ display: 'flex', gap: 6, margin: '12px 0 14px' }}>
        {[1, 2, 3, 4, 5].map(s => (
          <button key={s} onClick={() => setRating(s)} onMouseEnter={() => setHover(s)} onMouseLeave={() => setHover(0)} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0, display: 'flex' }} aria-label={`${s} stars`}>
            <StarFill size={28} color={s <= (hover || rating) ? '#C8A24A' : '#E6DFDA'} />
          </button>
        ))}
      </div>
      <textarea value={text} onChange={(e) => setText(e.target.value)} rows={3} placeholder={L(lang, 'Share your experience with this vendor…', 'شارك تجربتك مع هذا المزوّد…')} className="z-input" style={{ height: 'auto', padding: '13px 16px', resize: 'none', lineHeight: 1.5 }} />
      <div style={{ marginTop: 12 }}>
        <Btn variant="rose" icon="chat" disabled={rating === 0 || !text.trim()} onClick={() => setSent(true)}>{L(lang, 'Post comment', 'نشر التعليق')}</Btn>
      </div>
    </div>
  );
}

/* ── Chat with vendor ── */
function ChatScreen({ id }) {
  const { lang, t, pop, push } = useZafa();
  const v = VENDORS.find((x) => x.id === id);
  const cat = catOf(v.cat);
  const th = THEMES[v.theme] || THEMES.rose;
  const greet = L(lang, `Hello! Thank you for reaching out to ${v.name}. How can we help with your big day?`, `مرحباً! شكراً لتواصلك مع ${v.ar}. كيف يمكننا مساعدتك في يومك المميّز؟`);
  const [msgs, setMsgs] = React.useState([
    { who: 'them', text: greet, t: '10:24' }]);
  const [input, setInput] = React.useState('');
  const [typing, setTyping] = React.useState(false);
  const scrollRef = React.useRef(null);
  const fileRef = React.useRef(null);
  React.useEffect(() => { const el = scrollRef.current; if (el) el.scrollTop = el.scrollHeight; }, [msgs, typing]);

  const quick = L(lang,
    ['Is my date available?', 'Share your packages', 'What\u2019s your starting price?'],
    ['هل تاريخي متاح؟', 'شاركني الباقات', 'ما السعر التقريبي؟']);

  const reply = (q) => {
    const r = /price|سعر|باقات|packages/i.test(q)
      ? L(lang, `Our ${cat.en.toLowerCase()} packages start from AED 1,700. I can send a full quote based on your date and venue.`, `تبدأ باقاتنا من ١٧٠٠ درهم. يمكنني إرسال عرض كامل حسب تاريخك وموقعك.`)
      : /date|تاريخ|available|متاح/i.test(q)
        ? L(lang, 'Could you share your wedding date and city? I\u2019ll check availability right away.', 'هل تشاركني تاريخ زفافك والمدينة؟ سأتحقق من التوفّر فوراً.')
        : L(lang, 'Lovely! Tell me a little about your vision and guest count, and I\u2019ll tailor a proposal for you.', 'رائع! أخبريني عن رؤيتك وعدد الضيوف لأجهّز لك عرضاً مخصّصاً.');
    setTyping(true);
    setTimeout(() => { setTyping(false); setMsgs((m) => [...m, { who: 'them', text: r, t: '10:25' }]); }, 1100);
  };
  const send = (txt) => {
    const text = (txt || input).trim(); if (!text) return;
    setMsgs((m) => [...m, { who: 'me', text, t: '10:25' }]); setInput(''); reply(text);
  };
  const sendImg = () => {
    setMsgs((m) => [...m, { who: 'me', img: true, t: '10:25' }]);
    setTyping(true);
    setTimeout(() => { setTyping(false); setMsgs((m) => [...m, { who: 'them', text: L(lang, 'Beautiful inspiration — thank you! We can absolutely create something in this style for you.', 'إلهام جميل — شكراً لك! يمكننا بالتأكيد تنفيذ شيء بهذا الأسلوب.'), t: '10:26' }]); }, 1200);
  };

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)' }}>
      {/* header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '8px 16px 12px', borderBottom: '1px solid var(--line-2)', background: '#fff' }}>
        <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 style={{ width: 42, height: 42, borderRadius: '50%', overflow: 'hidden', flexShrink: 0, border: `2px solid ${th.soft}` }}>
          <CoverArt theme={v.theme} icon={cat.icon} cat={v.cat} src={monogramURI(v.name, v.theme, '#2C3550')} id={`chat-av-${v.id}`} radius={21} w={120} h={120} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <p className="serif" style={{ margin: 0, fontSize: 16, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{vName(v, lang)}</p>
          <p style={{ margin: '1px 0 0', fontSize: 11.5, color: '#2E9E6B', fontWeight: 600, display: 'flex', alignItems: 'center', gap: 5 }}><span style={{ width: 7, height: 7, borderRadius: '50%', background: '#2E9E6B' }} />{t('chatWith')}</p>
        </div>
      </div>

      {/* messages */}
      <div ref={scrollRef} className="z-scroll no-bar" style={{ flex: 1, padding: '16px 16px 8px' }}>
        <p style={{ textAlign: 'center', fontSize: 11, color: 'var(--muted)', fontWeight: 600, margin: '0 0 16px' }}>{t('chatToday')}</p>
        {msgs.map((m, i) => (
          <div key={i} className="fade-up" style={{ display: 'flex', justifyContent: m.who === 'me' ? 'flex-end' : 'flex-start', marginBottom: 10 }}>
            <div style={{ maxWidth: '80%' }}>
              {m.img ? (
                <div style={{ width: 180, height: 135, borderRadius: m.who === 'me' ? '18px 18px 4px 18px' : '18px 18px 18px 4px', overflow: 'hidden', boxShadow: 'var(--sh-sm)', border: '1px solid var(--line-2)' }}>
                  <CoverArt theme={v.theme} icon={cat.icon} cat={v.cat} kw="wedding,flowers,inspiration" seed={'cimg' + i + v.id} id={`cimg-${v.id}-${i}`} radius={18} w={360} h={270} />
                </div>
              ) : (
                <div style={{ padding: '11px 14px', fontSize: 14.5, lineHeight: 1.45, textWrap: 'pretty',
                  borderRadius: m.who === 'me' ? '18px 18px 4px 18px' : '18px 18px 18px 4px',
                  background: m.who === 'me' ? 'var(--rose)' : '#fff', color: 'var(--ink)',
                  border: m.who === 'me' ? 'none' : '1px solid var(--line-2)', boxShadow: 'var(--sh-sm)' }}>{m.text}</div>
              )}
              <p style={{ margin: '3px 6px 0', fontSize: 10.5, color: 'var(--muted)', textAlign: m.who === 'me' ? 'end' : 'start' }}>{m.t}</p>
            </div>
          </div>
        ))}
        {typing && <div style={{ display: 'flex', marginBottom: 10 }}><div style={{ padding: '12px 15px', borderRadius: '18px 18px 18px 4px', background: '#fff', border: '1px solid var(--line-2)', boxShadow: 'var(--sh-sm)' }}><Dots /></div></div>}
        {/* quick replies (only before user sends) */}
        {msgs.length === 1 && !typing && (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 6 }}>
            {quick.map((q) => <Chip key={q} onClick={() => send(q)}>{q}</Chip>)}
          </div>
        )}
      </div>

      {/* input */}
      <div style={{ padding: '10px 16px 26px' }}>
        <input ref={fileRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={(e) => { if (e.target.files && e.target.files[0]) { sendImg(); e.target.value = ''; } }} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, background: '#fff', border: '1.5px solid var(--line)', borderRadius: 999, padding: '5px 6px 5px 8px' }}>
          <button onClick={() => fileRef.current && fileRef.current.click()} aria-label="Attach image" style={{ width: 40, height: 40, borderRadius: '50%', border: 'none', cursor: 'pointer', background: 'var(--rose-100)', color: 'var(--rose-deep)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <Icon name="image" size={20} stroke={1.9} />
          </button>
          <input value={input} onChange={(e) => setInput(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && send()} placeholder={t('chatPlaceholder')}
            style={{ flex: 1, border: 'none', outline: 'none', background: 'none', fontFamily: 'var(--sans)', fontSize: 15, color: 'var(--ink)', minWidth: 0 }} />
          <button onClick={() => send()} disabled={!input.trim()} style={{ width: 44, height: 44, borderRadius: '50%', border: 'none', cursor: 'pointer', background: input.trim() ? 'var(--rose)' : 'var(--line)', color: 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, transition: 'background .15s' }}>
            <Icon name="arrow" size={20} className="flip-x" />
          </button>
        </div>
      </div>
    </div>);

}

/* ── Payment ── */
function PaymentScreen({ id }) {
  const { lang, t, pop, setTab } = useZafa();
  const v = VENDORS.find(x => x.id === id);
  const [card, setCard] = React.useState('');
  const [exp, setExp] = React.useState('');
  const [cvv, setCvv] = React.useState('');
  const [name, setName] = React.useState('');
  const [outcome, setOutcome] = React.useState('success'); // demo toggle
  const [state, setState] = React.useState('form'); // form | processing | success | failed
  const amount = 1500;

  const fmtCard = (s) => s.replace(/\D/g, '').slice(0, 16).replace(/(.{4})/g, '$1 ').trim();
  const fmtExp = (s) => { const d = s.replace(/\D/g, '').slice(0, 4); return d.length > 2 ? d.slice(0, 2) + '/' + d.slice(2) : d; };
  const valid = card.replace(/\s/g, '').length >= 16 && exp.length === 5 && cvv.length >= 3 && name.length > 1;

  const pay = () => { setState('processing'); setTimeout(() => setState(outcome), 1700); };

  if (state === 'success' || state === 'failed') {
    const ok = state === 'success';
    return (
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '30px 30px 40px', background: 'var(--bg)', textAlign: 'center' }}>
        <div style={{ width: 104, height: 104, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center',
          background: ok ? 'var(--rose-100)' : '#FBEAE7', color: ok ? '#2E9E6B' : '#C0392B', animation: 'pop .5s' }}>
          <Icon name={ok ? 'check' : 'x'} size={52} stroke={2.6} />
        </div>
        <h1 className="h1" style={{ margin: '24px 0 10px' }}>{ok ? t('paySuccess') : t('payFailed')}</h1>
        <p className="sec" style={{ margin: 0, fontSize: 15, lineHeight: 1.5, maxWidth: 280 }}>{ok ? t('paySuccessSub') : t('payFailedSub')}</p>
        {ok && <div className="z-card" style={{ marginTop: 22, padding: '14px 18px', display: 'flex', justifyContent: 'space-between', width: '100%', maxWidth: 300 }}>
          <span className="sec">{vName(v, lang)}</span><span style={{ fontWeight: 700 }}>AED {amount.toLocaleString()}</span>
        </div>}
        <div style={{ marginTop: 30, width: '100%', maxWidth: 300, display: 'flex', flexDirection: 'column', gap: 10 }}>
          {ok ? <Btn variant="rose" onClick={() => { setTab('home'); pop(); }}>{t('done')}</Btn>
              : <><Btn variant="rose" onClick={() => setState('form')}>{t('tryAgain')}</Btn><Btn variant="outline" onClick={pop}>{t('back')}</Btn></>}
        </div>
      </div>
    );
  }

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)' }}>
      <div style={{ padding: '6px 18px 8px' }}><ScreenHeader title={t('payTitle')} onBack={pop} /></div>
      <div className="z-scroll no-bar" style={{ flex: 1, padding: '8px 18px 20px' }}>
        {/* summary */}
        <div className="z-card" style={{ padding: 16, display: 'flex', alignItems: 'center', gap: 13, marginBottom: 20 }}>
          <div style={{ flex: 1 }}>
            <p className="sec" style={{ margin: 0, fontSize: 12.5 }}>{t('payFor')}</p>
            <p style={{ margin: '2px 0 0', fontWeight: 600, fontSize: 15 }}>{vName(v, lang)}</p>
          </div>
          <span className="serif" style={{ fontSize: 22, fontWeight: 700, whiteSpace: 'nowrap' }}>AED {amount.toLocaleString()}</span>
        </div>

        {/* card preview */}
        <div style={{ borderRadius: 20, padding: 20, marginBottom: 20, color: '#fff', position: 'relative', overflow: 'hidden',
          background: '#1B1418' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div style={{ width: 38, height: 28, borderRadius: 6, background: '#C8A24A' }} />
            <img src={window.ASSET('logo')} alt="" style={{ height: 26, filter: 'brightness(0) invert(1)', opacity: 0.95 }} />
          </div>
          <p style={{ margin: '22px 0 14px', fontSize: 19, letterSpacing: '.12em', fontFamily: 'monospace', direction: 'ltr' }}>{card || '•••• •••• •••• ••••'}</p>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5, color: 'rgba(255,255,255,.75)' }}>
            <span style={{ textTransform: 'uppercase' }}>{name || L(lang, 'Cardholder name', 'اسم حامل البطاقة')}</span>
            <span>{exp || 'MM/YY'}</span>
          </div>
        </div>

        {/* form */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 13 }}>
          <Field label={t('cardNumber')}><input className="z-input" inputMode="numeric" value={card} onChange={(e) => setCard(fmtCard(e.target.value))} placeholder="1234 5678 9012 3456" style={{ direction: 'ltr' }} /></Field>
          <div style={{ display: 'flex', gap: 12 }}>
            <Field label={t('expiry')} flex><input className="z-input" inputMode="numeric" value={exp} onChange={(e) => setExp(fmtExp(e.target.value))} placeholder="MM/YY" style={{ direction: 'ltr' }} /></Field>
            <Field label={t('cvv')} flex><input className="z-input" inputMode="numeric" value={cvv} onChange={(e) => setCvv(e.target.value.replace(/\D/g, '').slice(0, 4))} placeholder="•••" style={{ direction: 'ltr' }} /></Field>
          </div>
          <Field label={t('nameOnCard')}><input className="z-input" value={name} onChange={(e) => setName(e.target.value)} placeholder={L(lang, 'Full name', 'الاسم الكامل')} /></Field>
        </div>

        {/* gateway alts */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '22px 0 14px' }}>
          <div className="z-hr" style={{ flex: 1 }} /><span className="muted" style={{ fontSize: 12.5 }}>{t('orPayWith')}</span><div className="z-hr" style={{ flex: 1 }} />
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          {[' Pay', 'mada', 'Tabby'].map(g => <button key={g} style={{ flex: 1, height: 50, borderRadius: 12, border: '1.5px solid var(--line)', background: '#fff', cursor: 'pointer', fontWeight: 700, fontSize: 14, color: 'var(--ink)' }}>{g === ' Pay' ? ' Pay' : g}</button>)}
        </div>

        {/* demo outcome toggle */}
        <div style={{ marginTop: 22, padding: 12, borderRadius: 14, background: 'var(--rose-soft)', border: '1px dashed var(--rose-200)' }}>
          <p style={{ margin: '0 0 8px', fontSize: 12, fontWeight: 700, color: 'var(--rose-deep)', letterSpacing: '.04em' }}>{L(lang, 'DEMO · simulate outcome', 'تجربة · محاكاة النتيجة')}</p>
          <div style={{ display: 'flex', gap: 8 }}>
            <Chip on={outcome === 'success'} onClick={() => setOutcome('success')}>{L(lang, 'Success', 'نجاح')}</Chip>
            <Chip on={outcome === 'failed'} onClick={() => setOutcome('failed')}>{L(lang, 'Decline', 'رفض')}</Chip>
          </div>
        </div>
      </div>

      <div style={{ padding: '12px 18px 26px', borderTop: '1px solid var(--line)', background: '#fff' }}>
        <Btn variant="rose" disabled={!valid || state === 'processing'} onClick={pay}>
          {state === 'processing' ? <span className="z-spin" /> : <><Icon name="shield" size={18} />{t('payNow')} AED {amount.toLocaleString()}</>}
        </Btn>
      </div>
    </div>
  );
}

function Field({ label, children, flex }) {
  return (
    <label style={{ display: 'block', flex: flex ? 1 : undefined }}>
      <span className="lbl" style={{ display: 'block', marginBottom: 7 }}>{label}</span>
      {children}
    </label>
  );
}

Object.assign(window, { VendorProfile, PaymentScreen, ContactBtn, Field, GalleryLightbox, ChatScreen });
