// Saraya Events — Leads, tracking, featured cards, banners, trust

const { useState: useStateLd } = React;

/* ================================================================
   TRACKING HELPER
   Phase 1: console-only. Wire analytics in Phase 2.
   ================================================================ */
// GA4 standard event name map
var _GA4_EVENTS = {
  lead_form_submit:          'generate_lead',
  checkout_start:            'begin_checkout',
  subscription_selected:     'add_to_cart',
  vendor_package_click:      'select_item',
  join_vendor_click:         'generate_lead',
  request_quote_click:       'generate_lead',
  whatsapp_click:            'whatsapp_click',
  campaign_lead_submit:      'generate_lead',
  rental_inquiry_click:      'view_item',
  vendor_contact_click:      'select_item',
  category_click:            'select_content',
  browse_marketplace_click:  'select_content',
  browse_services_click:     'select_content',
};

// Meta Pixel standard event map
var _PIXEL_EVENTS = {
  lead_form_submit:          ['Lead',              true],
  checkout_start:            ['InitiateCheckout',  true],
  subscription_selected:     ['AddToCart',         true],
  join_vendor_click:         ['Lead',              true],
  request_quote_click:       ['Lead',              true],
  campaign_lead_submit:      ['Lead',              true],
  whatsapp_click:            ['Contact',           true],
  vendor_contact_click:      ['Contact',           true],
  rental_inquiry_click:      ['ViewContent',       true],
};

window.sarayaTrack = function(event, props) {
  try {
    // Google Analytics 4
    var ga4Event = _GA4_EVENTS[event] || event;
    if (typeof gtag === 'function') {
      gtag('event', ga4Event, Object.assign({ event_category: 'saraya', saraya_event: event }, props || {}));
    }
    // Meta Pixel
    var pixelMap = _PIXEL_EVENTS[event];
    if (pixelMap && typeof fbq === 'function') {
      var pixelEventName = pixelMap[0];
      var isStandard    = pixelMap[1];
      if (isStandard) {
        fbq('track', pixelEventName, props || {});
      } else {
        fbq('trackCustom', pixelEventName, props || {});
      }
    }
  } catch (e) {}
};

/* ================================================================
   LEAD DATA MODEL
   ================================================================ */
window.LEAD_TYPES = [
  { value: 'customer_quote',     en: 'Customer Quote Request',      ar: 'طلب عرض سعر' },
  { value: 'rental_inquiry',     en: 'Rental Inquiry',              ar: 'استفسار إيجار' },
  { value: 'service_booking',    en: 'Service Booking Inquiry',     ar: 'استفسار حجز خدمة' },
  { value: 'vendor_application', en: 'Vendor Application',         ar: 'طلب انضمام كمورد' },
  { value: 'support',            en: 'Support Request',             ar: 'طلب دعم' },
  { value: 'complaint',          en: 'Complaint',                   ar: 'شكوى' },
];

window.EVENT_TYPES = [
  { value: 'wedding',     en: 'Wedding',          ar: 'زفاف' },
  { value: 'engagement',  en: 'Engagement',       ar: 'خطوبة' },
  { value: 'corporate',   en: 'Corporate Event',  ar: 'فعالية شركات' },
  { value: 'birthday',    en: 'Birthday',         ar: 'عيد ميلاد' },
  { value: 'graduation',  en: 'Graduation',       ar: 'تخرج' },
  { value: 'kids_party',  en: "Kids Party",       ar: 'حفلة أطفال' },
  { value: 'other',       en: 'Other',            ar: 'أخرى' },
];

/* ================================================================
   SAVE LEAD TO SUPABASE
   Falls back to WhatsApp if DB not configured.
   ================================================================ */
window.saveLead = async function(data) {
  const db = window.SarayaDB;
  if (!db) return { ok: false, fallback: true };
  const { error } = await db.from('leads').insert({
    lead_type:              data.leadType           || 'customer_quote',
    status:                 'new',
    name:                   data.name               || null,
    phone:                  data.phone              || null,
    email:                  data.email              || null,
    event_type:             data.eventType          || null,
    event_date:             data.eventDate          || null,
    location:               data.location           || null,
    message:                data.message            || null,
    source:                 data.source             || 'website',
    campaign:               data.campaign           || null,
    account_type:           data.accountType        || null,
    marketing_consent:      data.marketingConsent   ? true : false,
    marketing_consent_date: data.marketingConsent   ? new Date().toISOString() : null,
    marketing_source:       data.campaign || data.source || 'website',
  });
  return { ok: !error, error };
};

/* ================================================================
   LEAD CAPTURE — reusable form
   Props: leadType, source, campaign, compact, title, subtitle,
          onDone, ar
   ================================================================ */
function LeadCapture({ leadType, source, campaign, compact, title, subtitle, onDone, ar }) {
  const blank = { name: '', phone: '', email: '', eventType: '', eventDate: '', location: '', message: '', marketingConsent: false };
  const [form, setForm] = useStateLd(blank);
  const [busy, setBusy] = useStateLd(false);
  const [done, setDone] = useStateLd(false);
  const [err,  setErr]  = useStateLd('');

  const set = (k, v) => setForm((p) => ({ ...p, [k]: v }));
  const inp = {
    width: '100%', padding: '10px 13px', borderRadius: 9,
    border: '1.5px solid var(--line)', fontFamily: 'var(--font-body)',
    fontSize: 14, outline: 'none', background: 'var(--white)', boxSizing: 'border-box',
  };

  const submit = async (e) => {
    e.preventDefault();
    if (!form.name.trim()) { setErr(ar ? 'الاسم مطلوب' : 'Name is required'); return; }
    if (!form.phone.trim()) { setErr(ar ? 'رقم الهاتف مطلوب' : 'Phone is required'); return; }
    if (form.email.trim() && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) { setErr(ar ? 'البريد الإلكتروني غير صالح' : 'Please enter a valid email address'); return; }
    setBusy(true); setErr('');

    window.sarayaTrack('lead_form_submit', { lead_type: leadType, source, campaign });

    const result = await window.saveLead({ ...form, leadType, source, campaign });

    if (result.fallback) {
      const msg = "Hello Saraya Events" +
        "\nName: " + form.name +
        "\nPhone: " + form.phone +
        (form.eventType ? "\nEvent: " + form.eventType : '') +
        (form.message ? "\nMessage: " + form.message : '');
      window.open(window.SARAYA.waLink(msg), '_blank');
    }

    setBusy(false);
    setDone(true);
    onDone && onDone(form);
  };

  if (done) {
    return (
      <div style={{ textAlign: 'center', padding: compact ? '16px 0' : '32px 20px' }}>
        <span style={{ display: 'inline-flex', width: 56, height: 56, borderRadius: '50%', background: '#DCFCE7', alignItems: 'center', justifyContent: 'center', marginBottom: 14 }}>
          <Icon name="check-circle-2" size={28} style={{ color: '#16A34A' }} />
        </span>
        <h3 style={{ fontFamily: 'var(--font-display)', fontSize: compact ? 19 : 22, fontWeight: 500, marginBottom: 8 }}>
          {ar ? 'شكراً لتواصلك!' : 'Thank you!'}
        </h3>
        <p style={{ color: 'var(--fg-secondary)', fontSize: 14, lineHeight: 1.6, marginBottom: 20 }}>
          {ar ? 'سيتواصل معك فريق سرايا قريبًا.' : 'The Saraya Events team will contact you shortly.'}
        </p>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap' }}>
          <a href={window.SARAYA.waLink("Hello Saraya Events, I submitted a request and would like to follow up.")}
            target="_blank" rel="noopener noreferrer"
            onClick={() => window.sarayaTrack('whatsapp_click', { source: 'lead_done' })}
            style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '10px 18px', borderRadius: 10, background: '#25D366', color: 'white', fontWeight: 600, fontSize: 14, textDecoration: 'none' }}>
            <Icon name="message-circle" size={16} />
            {ar ? 'تابع عبر واتساب' : 'Continue on WhatsApp'}
          </a>
          <button onClick={() => { setDone(false); setForm(blank); }}
            style={{ padding: '10px 18px', borderRadius: 10, border: '1.5px solid var(--line)', background: 'var(--white)', fontFamily: 'var(--font-body)', fontSize: 14, cursor: 'pointer', color: 'var(--fg-primary)' }}>
            {ar ? 'طلب آخر' : 'Submit Another'}
          </button>
        </div>
      </div>
    );
  }

  return (
    <form onSubmit={submit} style={{ display: 'grid', gap: compact ? 10 : 14 }}>
      {title && (
        <h3 style={{ fontFamily: 'var(--font-display)', fontSize: compact ? 18 : 22, fontWeight: 500, margin: 0 }}>{title}</h3>
      )}
      {subtitle && (
        <p style={{ fontSize: 13.5, color: 'var(--fg-secondary)', margin: 0, lineHeight: 1.55 }}>{subtitle}</p>
      )}
      {err && (
        <div style={{ padding: '9px 13px', borderRadius: 8, background: '#fef2f2', color: '#dc2626', fontSize: 13 }}>{err}</div>
      )}

      <input required value={form.name} onChange={(e) => set('name', e.target.value)}
        placeholder={ar ? 'الاسم *' : 'Your name *'} style={inp} />

      <input required type="tel" value={form.phone} onChange={(e) => set('phone', e.target.value)}
        placeholder={ar ? 'واتساب / هاتف *' : 'Phone / WhatsApp *'} style={inp} />

      {!compact && (
        <input type="email" value={form.email} onChange={(e) => set('email', e.target.value)}
          placeholder={ar ? 'البريد الإلكتروني (اختياري)' : 'Email (optional)'} style={inp} />
      )}

      <select value={form.eventType} onChange={(e) => set('eventType', e.target.value)}
        style={{ ...inp, cursor: 'pointer', color: form.eventType ? 'var(--fg-primary)' : 'var(--fg-muted)' }}>
        <option value="">{ar ? '— نوع الفعالية —' : '— Event type —'}</option>
        {window.EVENT_TYPES.map((t) => (
          <option key={t.value} value={t.value}>{ar ? t.ar : t.en}</option>
        ))}
      </select>

      {!compact && (
        <>
          <input type="date" value={form.eventDate} onChange={(e) => set('eventDate', e.target.value)}
            style={{ ...inp, color: form.eventDate ? 'var(--fg-primary)' : 'var(--fg-muted)' }} />
          <input value={form.location} onChange={(e) => set('location', e.target.value)}
            placeholder={ar ? 'الموقع (اختياري)' : 'Location (optional)'} style={inp} />
        </>
      )}

      <textarea value={form.message} onChange={(e) => set('message', e.target.value)}
        rows={compact ? 2 : 3}
        placeholder={ar ? 'رسالتك (اختياري)' : 'Your message (optional)'}
        style={{ ...inp, resize: 'vertical' }} />

      <label style={{ display: 'flex', alignItems: 'flex-start', gap: 10, cursor: 'pointer', userSelect: 'none' }}>
        <input type="checkbox" checked={form.marketingConsent}
          onChange={(e) => set('marketingConsent', e.target.checked)}
          style={{ marginTop: 3, flexShrink: 0, accentColor: 'var(--gold-deep)', width: 15, height: 15 }} />
        <span style={{ fontSize: 12.5, color: 'var(--fg-secondary)', lineHeight: 1.6 }}>
          {ar
            ? 'أوافق على تلقي التحديثات والعروض والتواصل التسويقي من سرايا للفعاليات. (اختياري)'
            : 'I agree to receive updates, offers, and marketing communications from Saraya Events. (Optional)'}
        </span>
      </label>

      <button type="submit" disabled={busy} style={{
        padding: '12px 0', borderRadius: 10, border: 'none',
        cursor: busy ? 'wait' : 'pointer',
        background: 'var(--espresso)', color: 'var(--ivory)',
        fontFamily: 'var(--font-body)', fontSize: 15, fontWeight: 600,
        transition: 'opacity 150ms', opacity: busy ? 0.7 : 1,
      }}>
        {busy ? (ar ? 'جارٍ الإرسال…' : 'Sending…') : (ar ? 'إرسال الطلب' : 'Send Request')}
      </button>

      <p style={{ fontSize: 11.5, color: 'var(--fg-muted)', textAlign: 'center', margin: 0 }}>
        {ar ? 'سيتواصل معك فريق سرايا قريبًا.' : 'The Saraya team will reach out shortly.'}
      </p>
    </form>
  );
}

/* ================================================================
   CAMPAIGN BANNER CONFIG
   ================================================================ */
window.CAMPAIGN_BANNERS = {
  customer: {
    eyebrow:  { en: 'Event Marketplace', ar: 'سوق الفعاليات' },
    title:    { en: 'Plan Your Event with Verified Vendors', ar: 'خطّط فعاليتك مع موردين موثّقين' },
    subtitle: { en: 'Submit one request and receive offers from trusted event suppliers across the UAE.', ar: 'أرسل طلبًا واحدًا واستقبل عروضًا من أفضل موردي الفعاليات في الإمارات.' },
    bg: 'var(--cream)', fg: 'var(--fg-primary)', eyebrowColor: 'var(--gold-deep)',
    ctas: [
      { label: { en: 'Request a Quote', ar: 'اطلب عرض سعر' }, route: 'design',   track: 'request_quote_click',   primary: true },
      { label: { en: 'Browse Marketplace', ar: 'تصفّح السوق' }, route: 'store',  track: 'browse_marketplace_click', primary: false },
    ],
  },
  vendor: {
    eyebrow:  { en: 'Join Saraya', ar: 'انضم إلى سرايا' },
    title:    { en: 'Grow Your Event Business with Saraya', ar: 'نمّ عملك في مجال الفعاليات مع سرايا' },
    subtitle: { en: 'List your products, rentals, and services in front of customers across the UAE.', ar: 'أدرج منتجاتك وإيجاراتك وخدماتك أمام العملاء في جميع أنحاء الإمارات.' },
    bg: 'var(--espresso)', fg: 'var(--ivory)', eyebrowColor: 'var(--gold-light)',
    ctas: [
      { label: { en: 'Join as Vendor', ar: 'انضم كمورد' },       route: 'vendor-packages',  track: 'join_vendor_click',     primary: true },
      { label: { en: 'View Packages', ar: 'عرض الباقات' },       route: 'vendor-packages',  track: 'vendor_package_click',  primary: false },
    ],
  },
  rental: {
    eyebrow:  { en: 'Furniture Rental', ar: 'تأجير الأثاث' },
    title:    { en: 'Premium Event Furniture, Delivered', ar: 'أثاث فعاليات فاخر يصل إليك' },
    subtitle: { en: 'Chairs, tables, sofas and décor — rent from verified UAE suppliers for any event.', ar: 'كراسي وطاولات وأرائك وديكور — استأجر من موردين موثّقين في الإمارات.' },
    bg: 'var(--muted)', fg: 'var(--fg-primary)', eyebrowColor: 'var(--gold-deep)',
    ctas: [
      { label: { en: 'Browse Rentals', ar: 'تصفّح الإيجار' },   route: 'rental', track: 'rental_inquiry_click',   primary: true },
      { label: { en: 'Request a Quote', ar: 'اطلب عرض سعر' },  route: 'design',  track: 'request_quote_click',   primary: false },
    ],
  },
  wedding: {
    eyebrow:  { en: 'Wedding Planning', ar: 'تخطيط الزفاف' },
    title:    { en: 'Your Perfect Wedding, Beautifully Designed', ar: 'زفافك المثالي، بتصميمٍ بديع' },
    subtitle: { en: 'From décor to flowers, catering and furniture — everything from one marketplace.', ar: 'من الديكور إلى الزهور والضيافة والأثاث — كل شيء من سوق واحد.' },
    bg: 'var(--cream)', fg: 'var(--fg-primary)', eyebrowColor: 'var(--gold-deep)',
    ctas: [
      { label: { en: 'Plan My Wedding', ar: 'خطّط زفافي' },     route: 'design',    track: 'request_quote_click',    primary: true },
      { label: { en: 'Browse Services', ar: 'تصفّح الخدمات' }, route: 'services',   track: 'browse_services_click',  primary: false },
    ],
  },
};

/* ================================================================
   MARKETING BANNER
   Props: type (key in CAMPAIGN_BANNERS), style
   ================================================================ */
function MarketingBanner({ type, style }) {
  const { lang } = useLang();
  const { go } = useNav();
  const ar = lang === 'ar';
  const data = window.CAMPAIGN_BANNERS[type] || window.CAMPAIGN_BANNERS.customer;
  const isDark = data.bg === 'var(--espresso)';
  const subtitleColor = isDark ? 'rgba(250,246,240,0.78)' : 'var(--fg-secondary)';

  return (
    <section style={{ background: data.bg, padding: 'clamp(44px,6.5vw,76px) 0', ...style }}>
      <Container wide>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 32, alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ flex: '1 1 320px', maxWidth: 640 }}>
            <Eyebrow color={data.eyebrowColor}>{ar ? data.eyebrow.ar : data.eyebrow.en}</Eyebrow>
            <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(24px,3.5vw,42px)', fontWeight: 500, color: data.fg, margin: '14px 0 0', lineHeight: 1.1 }}>
              {ar ? data.title.ar : data.title.en}
            </h2>
            <p style={{ fontSize: 'clamp(14px,1.4vw,17px)', color: subtitleColor, marginTop: 14, lineHeight: 1.65 }}>
              {ar ? data.subtitle.ar : data.subtitle.en}
            </p>
          </div>
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignSelf: 'flex-end' }}>
            {data.ctas.map((cta, i) => {
              const isSecondary = !cta.primary;
              const btnStyle = isDark && isSecondary
                ? { border: '1.5px solid rgba(250,246,240,0.35)', color: 'var(--ivory)', background: 'transparent' }
                : {};
              return (
                <Button key={i}
                  variant={cta.primary ? 'primary' : 'secondary'}
                  style={btnStyle}
                  onClick={() => { window.sarayaTrack(cta.track, { banner: type }); go(cta.route); }}>
                  {ar ? cta.label.ar : cta.label.en}
                </Button>
              );
            })}
          </div>
        </div>
      </Container>
    </section>
  );
}

/* ================================================================
   FEATURED MOCK DATA  (replace with Supabase query in Phase 2)
   ================================================================ */
window.FEATURED_VENDORS = [
  { id: 'fv-1', name: { en: 'Al Nour Furniture Rentals', ar: 'شركة النور لتأجير الأثاث' }, category: { en: 'Furniture & Décor', ar: 'أثاث وديكور' }, badge: 'Featured', rating: 4.9, reviews: 47, icon: 'armchair', tone: 'champagne', city: 'Abu Dhabi', verified: true, route: 'rental' },
  { id: 'fv-2', name: { en: 'Bloom & Petal Events',       ar: 'بلوم آند بيتال' },            category: { en: 'Flowers & Floral Design', ar: 'زهور وتصميم زهري' }, badge: 'Premium Supplier', rating: 4.8, reviews: 83, icon: 'flower-2', tone: 'blush', city: 'Dubai', verified: true, route: 'store' },
  { id: 'fv-3', name: { en: 'Elite Sound & AV',           ar: 'إيليت للصوت والفيديو' },     category: { en: 'Sound & AV', ar: 'صوتيات وفيديو' }, badge: 'Verified Vendor', rating: 4.7, reviews: 31, icon: 'speaker', tone: 'espresso', city: 'Abu Dhabi', verified: true, route: 'rental' },
  { id: 'fv-4', name: { en: 'Ivory Tent Solutions',       ar: 'إيفوري للخيم' },             category: { en: 'Tents & Structures', ar: 'خيم وهياكل' }, badge: 'Featured', rating: 4.6, reviews: 22, icon: 'tent', tone: 'cream', city: 'Sharjah', verified: true, route: 'services' },
];

window.FEATURED_PRODUCTS = [
  { id: 'fp-1', name: { en: 'Gold Chiavari Chair', ar: 'كرسي كيافاري ذهبي' }, category: { en: 'Seating', ar: 'جلوس' }, price: 35, unit: { en: 'per day', ar: 'لليوم' }, badge: 'Featured', tone: 'champagne', icon: 'armchair', route: 'rental' },
  { id: 'fp-2', name: { en: 'Crystal Centerpiece',  ar: 'قطعة مركزية كريستال' }, category: { en: 'Décor', ar: 'ديكور' }, price: 120, unit: { en: 'per piece', ar: 'للقطعة' }, badge: 'Popular', tone: 'cream', icon: 'gem', route: 'store' },
  { id: 'fp-3', name: { en: 'White Folding Table 6ft', ar: 'طاولة قابلة للطي 6 قدم' }, category: { en: 'Tables', ar: 'طاولات' }, price: 25, unit: { en: 'per day', ar: 'لليوم' }, badge: 'Verified', tone: 'blush', icon: 'layout-panel-top', route: 'rental' },
  { id: 'fp-4', name: { en: 'LED Dance Floor',      ar: 'أرضية رقص LED' }, category: { en: 'Lighting', ar: 'إضاءة' }, price: 800, unit: { en: 'per event', ar: 'للفعالية' }, badge: 'Sponsored', tone: 'espresso', icon: 'zap', route: 'rental' },
];

/* ================================================================
   FEATURED VENDOR CARD
   ================================================================ */
function FeaturedVendorCard({ vendor, ar, onContact }) {
  const { go } = useNav();
  const BADGE_STYLES = {
    'Featured':          { bg: '#FEF9C3', color: '#854D0E' },
    'Premium Supplier':  { bg: 'var(--gold-tint)', color: 'var(--gold-deep)' },
    'Verified Vendor':   { bg: '#DCFCE7', color: '#15803D' },
    'Sponsored':         { bg: '#F3F4F6', color: '#374151' },
  };
  const bs = BADGE_STYLES[vendor.badge] || BADGE_STYLES['Verified Vendor'];

  return (
    <div className="saraya-lift" style={{ background: 'var(--white)', borderRadius: 16, border: '1px solid var(--line)', overflow: 'hidden', boxShadow: 'var(--shadow-soft)', display: 'flex', flexDirection: 'column', height: '100%' }}>
      {/* Top color band */}
      <div style={{ height: 80, background: 'var(--' + (vendor.tone || 'cream') + ')', display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative' }}>
        <span style={{ display: 'inline-flex', width: 52, height: 52, borderRadius: 14, background: 'var(--white)', alignItems: 'center', justifyContent: 'center', boxShadow: '0 2px 12px rgba(42,31,26,0.12)' }}>
          <Icon name={vendor.icon || 'store'} size={26} style={{ color: 'var(--gold-deep)' }} />
        </span>
        <span style={{ position: 'absolute', top: 10, insetInlineEnd: 12, padding: '3px 10px', borderRadius: 20, fontSize: 11, fontWeight: 700, letterSpacing: '0.04em', background: bs.bg, color: bs.color }}>
          {vendor.badge}
        </span>
      </div>
      <div style={{ padding: '16px 18px 18px', flex: 1, display: 'flex', flexDirection: 'column', gap: 6 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <h3 style={{ fontFamily: 'var(--font-serif)', fontSize: 17, fontWeight: 500, margin: 0, flex: 1, lineHeight: 1.2 }}>
            {ar ? vendor.name.ar : vendor.name.en}
          </h3>
          {vendor.verified && (
            <Icon name="badge-check" size={16} style={{ color: '#2563EB', flexShrink: 0 }} title="Verified Vendor" />
          )}
        </div>
        <p style={{ fontSize: 12.5, color: 'var(--gold-deep)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em', margin: 0 }}>
          {ar ? vendor.category.ar : vendor.category.en}
        </p>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 2 }}>
          <Icon name="star" size={13} style={{ color: '#F59E0B', fill: '#F59E0B' }} />
          <span style={{ fontSize: 13, fontWeight: 600 }}>{vendor.rating}</span>
          <span style={{ fontSize: 12, color: 'var(--fg-muted)' }}>({vendor.reviews} {ar ? 'تقييم' : 'reviews'})</span>
          <span style={{ fontSize: 12, color: 'var(--fg-muted)', marginInlineStart: 'auto' }}>
            <Icon name="map-pin" size={12} style={{ verticalAlign: 'middle', marginInlineEnd: 3 }} />
            {vendor.city}
          </span>
        </div>
        <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
          <button onClick={() => { window.sarayaTrack('vendor_contact_click', { vendor_id: vendor.id }); onContact && onContact(vendor); }}
            style={{ flex: 1, padding: '8px 0', borderRadius: 8, border: 'none', background: 'var(--espresso)', color: 'var(--ivory)', fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>
            {ar ? 'تواصل' : 'Contact'}
          </button>
          <button onClick={() => { window.sarayaTrack('vendor_view_click', { vendor_id: vendor.id }); go(vendor.route || 'store'); }}
            style={{ flex: 1, padding: '8px 0', borderRadius: 8, border: '1.5px solid var(--line)', background: 'var(--white)', color: 'var(--fg-primary)', fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>
            {ar ? 'عرض' : 'View'}
          </button>
        </div>
      </div>
    </div>
  );
}

/* ================================================================
   FEATURED PRODUCT / RENTAL CARD
   ================================================================ */
function FeaturedProductCard({ product, ar, onInquire }) {
  const { go } = useNav();
  const BADGE_STYLES = {
    'Featured':  { bg: 'var(--gold)', color: 'var(--espresso)' },
    'Popular':   { bg: '#FEF9C3', color: '#854D0E' },
    'Verified':  { bg: '#DCFCE7', color: '#15803D' },
    'Sponsored': { bg: '#F3F4F6', color: '#374151' },
  };
  const bs = BADGE_STYLES[product.badge] || BADGE_STYLES['Verified'];

  return (
    <div className="saraya-lift" style={{ background: 'var(--white)', borderRadius: 14, border: '1px solid var(--line)', overflow: 'hidden', boxShadow: 'var(--shadow-soft)', display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div style={{ height: 120, background: 'var(--' + (product.tone || 'cream') + ')', display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative' }}>
        <Icon name={product.icon || 'package'} size={44} stroke={1.2} style={{ color: 'var(--fg-primary)', opacity: 0.55 }} />
        <span style={{ position: 'absolute', top: 10, insetInlineStart: 12, padding: '3px 10px', borderRadius: 20, fontSize: 11, fontWeight: 700, background: bs.bg, color: bs.color }}>
          {product.badge}
        </span>
      </div>
      <div style={{ padding: '14px 16px 16px', flex: 1, display: 'flex', flexDirection: 'column', gap: 4 }}>
        <p style={{ fontSize: 11.5, color: 'var(--gold-deep)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', margin: 0 }}>
          {ar ? product.category.ar : product.category.en}
        </p>
        <h3 style={{ fontFamily: 'var(--font-serif)', fontSize: 16, fontWeight: 500, margin: 0, lineHeight: 1.25 }}>
          {ar ? product.name.ar : product.name.en}
        </h3>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 5, marginTop: 6 }}>
          <span style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 600 }}>AED {product.price}</span>
          <span style={{ fontSize: 12, color: 'var(--fg-muted)' }}>{ar ? product.unit.ar : product.unit.en}</span>
        </div>
        <button onClick={() => { window.sarayaTrack('rental_inquiry_click', { product_id: product.id }); onInquire && onInquire(product); }}
          style={{ marginTop: 'auto', paddingTop: 12, padding: '9px 0', borderRadius: 8, border: 'none', background: 'var(--cream)', color: 'var(--fg-primary)', fontFamily: 'var(--font-body)', fontSize: 13.5, fontWeight: 600, cursor: 'pointer', borderTop: '1px solid var(--line)' }}>
          {ar ? 'استفسار' : 'Inquire'}
        </button>
      </div>
    </div>
  );
}

/* ================================================================
   TRUST SECTION
   ================================================================ */
function TrustSection({ audience, ar }) {
  const isVendor = audience === 'vendor';
  const items = isVendor ? [
    { icon: 'users',          en: 'UAE customer reach',           ar: 'وصول لعملاء الإمارات' },
    { icon: 'bar-chart-2',    en: 'Analytics dashboard',          ar: 'لوحة تحليلات' },
    { icon: 'mail',           en: 'RFQ opportunities',            ar: 'طلبات عروض أسعار' },
    { icon: 'star',           en: 'Featured placement options',   ar: 'خيارات عرض مميز' },
    { icon: 'layout-dashboard', en: 'Vendor dashboard',           ar: 'لوحة تحكم المورد' },
    { icon: 'trending-up',    en: 'Growth packages',              ar: 'باقات النمو' },
  ] : [
    { icon: 'badge-check',    en: 'Verified vendors',             ar: 'موردون موثّقون' },
    { icon: 'map-pin',        en: 'UAE-focused marketplace',      ar: 'سوق مخصص للإمارات' },
    { icon: 'lock',           en: 'Secure payments',              ar: 'مدفوعات آمنة' },
    { icon: 'headset',        en: 'Complaint support',            ar: 'دعم الشكاوى' },
    { icon: 'sparkles',       en: 'Event-specialized platform',   ar: 'منصة متخصصة بالفعاليات' },
    { icon: 'languages',      en: 'Arabic & English support',     ar: 'دعم بالعربية والإنجليزية' },
  ];

  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: 12 }}>
      {items.map((item, i) => (
        <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 14px', borderRadius: 10, background: 'var(--white)', border: '1px solid var(--line)' }}>
          <Icon name={item.icon} size={18} style={{ color: 'var(--gold-deep)', flexShrink: 0 }} />
          <span style={{ fontSize: 13, fontWeight: 500, lineHeight: 1.35 }}>{ar ? item.ar : item.en}</span>
        </div>
      ))}
    </div>
  );
}

/* ================================================================
   TRUST BADGE (inline, for cards or pages)
   ================================================================ */
function TrustBadge({ type }) {
  const BADGES = {
    verified:  { icon: 'badge-check', en: 'Verified Vendor',   ar: 'مورد موثّق',    bg: '#DCFCE7', color: '#15803D' },
    featured:  { icon: 'star',        en: 'Featured Vendor',   ar: 'مورد مميز',     bg: 'var(--gold-tint)', color: 'var(--gold-deep)' },
    fast:      { icon: 'zap',         en: 'Fast Response',     ar: 'استجابة سريعة', bg: '#EFF6FF', color: '#1D4ED8' },
    premium:   { icon: 'gem',         en: 'Premium Supplier',  ar: 'مورد بريميوم',  bg: 'var(--cream)', color: 'var(--espresso)' },
    newvendor: { icon: 'sparkles',    en: 'New Vendor',        ar: 'مورد جديد',     bg: '#F0FDF4', color: '#166534' },
  };
  const { lang } = useLang();
  const ar = lang === 'ar';
  const b = BADGES[type] || BADGES.verified;
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '3px 10px', borderRadius: 20, fontSize: 11.5, fontWeight: 600, background: b.bg, color: b.color }}>
      <Icon name={b.icon} size={12} />
      {ar ? b.ar : b.en}
    </span>
  );
}

/* ================================================================
   FEATURED VENDORS SECTION (homepage block)
   ================================================================ */
function FeaturedVendorsSection() {
  const { lang } = useLang();
  const { go } = useNav();
  const ar = lang === 'ar';
  const [contactVendor, setContactVendor] = useStateLd(null);

  const vendors = window.FEATURED_VENDORS || [];
  const products = window.FEATURED_PRODUCTS || [];

  return (
    <Section bg="canvas">
      <Container wide>
        <Reveal>
          <SectionHead center
            eyebrow={ar ? 'الموردون المميزون' : 'Featured Vendors'}
            title={ar ? 'موردون موثّقون لكل فعالية' : 'Trusted vendors for every event'}
            intro={ar ? 'اختر من بين موردين معتمدين في سرايا — زهور، أثاث، صوتيات، خيم والمزيد.' : 'Browse verified Saraya vendors — flowers, furniture, AV, tents and more.'}
          />
        </Reveal>

        {/* Vendor cards */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))', gap: 20, marginTop: 44 }}>
          {vendors.map((v, i) => (
            <Reveal key={v.id} delay={i * 60}>
              <FeaturedVendorCard vendor={v} ar={ar} onContact={(vendor) => setContactVendor(vendor)} />
            </Reveal>
          ))}
        </div>

        {/* Featured rental items */}
        <div style={{ marginTop: 52 }}>
          <Reveal>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12, marginBottom: 24 }}>
              <SectionHead eyebrow={ar ? 'الإيجار المميز' : 'Featured Rentals'} title={ar ? 'قطع شائعة للإيجار' : 'Popular rental items'} />
              <Button variant="secondary" iconRight="arrow-right" onClick={() => go('rental')}>
                {ar ? 'كل الإيجار' : 'Browse all rentals'}
              </Button>
            </div>
          </Reveal>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: 16 }}>
            {products.map((p, i) => (
              <Reveal key={p.id} delay={i * 50}>
                <FeaturedProductCard product={p} ar={ar} onInquire={(prod) => setContactVendor({ name: prod.name, id: prod.id })} />
              </Reveal>
            ))}
          </div>
        </div>

        <div style={{ textAlign: 'center', marginTop: 36 }}>
          <p style={{ fontSize: 12, color: 'var(--fg-muted)', marginBottom: 14 }}>
            {ar ? '* بيانات تجريبية — سيتم استبدالها بموردين حقيقيين بعد الإطلاق.' : '* Demo data — replaced with live vendors after launch.'}
          </p>
          <Button variant="secondary" onClick={() => window.openJoinVendorModal ? window.openJoinVendorModal() : go('vendor-packages')} icon="store">
            {ar ? 'انضم كمورد مميز' : 'Become a featured vendor'}
          </Button>
        </div>
      </Container>

      {/* Contact lead modal */}
      {contactVendor && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 9000, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(0,0,0,0.45)', padding: '20px 16px' }}>
          <div style={{ background: 'var(--white)', borderRadius: 20, width: '100%', maxWidth: 440, padding: '28px 28px 24px' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20 }}>
              <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 500, margin: 0 }}>
                {ar ? 'تواصل مع المورد' : 'Contact Vendor'}
              </h3>
              <button onClick={() => setContactVendor(null)} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 4 }}>
                <Icon name="x" size={20} style={{ color: 'var(--fg-secondary)' }} />
              </button>
            </div>
            <LeadCapture leadType="customer_quote" source="featured_vendor" campaign={contactVendor.id} ar={ar} compact
              title={null} subtitle={null}
              onDone={() => setContactVendor(null)} />
          </div>
        </div>
      )}
    </Section>
  );
}

Object.assign(window, {
  LeadCapture,
  MarketingBanner,
  FeaturedVendorCard,
  FeaturedProductCard,
  TrustSection,
  TrustBadge,
  FeaturedVendorsSection,
});
