// 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',
  view_item:                 'view_item',
  add_to_cart:               'add_to_cart',
  begin_checkout:            'begin_checkout',
  purchase:                  'purchase',
  sign_up:                   'sign_up',
  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],
  view_item:                 ['ViewContent',       true],
  add_to_cart:               ['AddToCart',         true],
  begin_checkout:            ['InitiateCheckout',  true],
  purchase:                  ['Purchase',          true],
  sign_up:                   ['CompleteRegistration', 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],
};

// TikTok pixel standard event map
var _TIKTOK_EVENTS = {
  lead_form_submit:     'SubmitForm',
  request_quote_click:  'SubmitForm',
  join_vendor_click:    'SubmitForm',
  view_item:            'ViewContent',
  rental_inquiry_click: 'ViewContent',
  add_to_cart:          'AddToCart',
  begin_checkout:       'InitiateCheckout',
  purchase:             'CompletePayment',
  sign_up:              'CompleteRegistration',
  whatsapp_click:       'Contact',
  vendor_contact_click: 'Contact',
};

// Google Ads conversion labels — filled in Phase 3 once conversion actions
// exist. Format:  event_name: 'AW-XXXXXXXXXX/AbCdEfGhIj'
window.SARAYA_ADS_CONVERSIONS = window.SARAYA_ADS_CONVERSIONS || {};

window.sarayaTrack = function(event, props) {
  var p = props || {};
  // dataLayer (Google Tag Manager) — single source of truth for all tags
  try {
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push(Object.assign({ event: 'saraya_' + event, saraya_event: event }, p));
  } catch (e) {}
  // Google Analytics 4
  try {
    var ga4Event = _GA4_EVENTS[event] || event;
    if (typeof gtag === 'function') {
      gtag('event', ga4Event, Object.assign({ event_category: 'saraya', saraya_event: event }, p));
    }
    // Google Ads conversion (only when a label is configured for this event)
    var adsSendTo = window.SARAYA_ADS_CONVERSIONS[event];
    if (adsSendTo && typeof gtag === 'function') {
      var adsPayload = { send_to: adsSendTo };
      if (p.value != null) { adsPayload.value = p.value; adsPayload.currency = p.currency || 'AED'; }
      if (p.transaction_id) adsPayload.transaction_id = p.transaction_id;
      gtag('event', 'conversion', adsPayload);
    }
  } catch (e) {}
  // Meta Pixel
  try {
    var pixelMap = _PIXEL_EVENTS[event];
    if (pixelMap && typeof fbq === 'function') {
      if (pixelMap[1]) { fbq('track', pixelMap[0], p); }
      else { fbq('trackCustom', pixelMap[0], p); }
    }
  } catch (e) {}
  // TikTok Pixel
  try {
    var ttEvent = _TIKTOK_EVENTS[event];
    if (ttEvent && typeof ttq !== 'undefined' && ttq && ttq.track) { ttq.track(ttEvent, p); }
  } 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 };
  // NOTE: only columns that exist on public.leads. Sending non-existent
  // columns (previously account_type/marketing_consent*) makes PostgREST
  // reject the whole insert, silently losing every lead.
  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,
  });
  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 [hp,   setHp]   = useStateLd(''); // honeypot — real users never fill this

  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; }

    // Honeypot: real users never fill `company_website`. If it holds a value,
    // a bot submitted the form — show the normal thank-you but store nothing.
    if (hp.trim()) { setDone(true); onDone && onDone(form); return; }

    setBusy(true); setErr('');

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

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

    // DB present but the insert failed → do NOT claim success; keep the form
    // open so the visitor (and their inquiry) isn't silently dropped.
    if (!result.ok && !result.fallback) {
      setErr(ar ? 'تعذّر إرسال طلبك. حاول مرة أخرى أو تواصل معنا عبر واتساب.' : 'Sorry — we couldn’t submit your request. Please try again, or reach us on WhatsApp.');
      return;
    }

    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');
    }

    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 }}>
      <input type="text" name="company_website" autoComplete="off" tabIndex={-1} aria-hidden="true" value={hp} onChange={(e) => setHp(e.target.value)} style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, opacity: 0 }} />
      {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>
        </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 }}>
          <span style={{ fontSize: 12, color: 'var(--fg-muted)' }}>
            <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 [vendors, setVendors] = useStateLd([]);
  const [rentals, setRentals] = useStateLd([]);
  const [loaded, setLoaded] = useStateLd(false);

  window.React.useEffect(() => {
    let cancelled = false;
    (async () => {
      const db = window.SarayaDB;
      if (!db) { if (!cancelled) setLoaded(true); return; }
      const [vRes, rRes] = await Promise.all([
        db.rpc('saraya_featured_vendors', { p_limit: 8 }),
        db.from('rentals').select('*, categories(name_en, name_ar)').eq('is_active', true).eq('status', 'approved').order('created_at', { ascending: false }).limit(4),
      ]);
      if (cancelled) return;
      setVendors((vRes && vRes.data) || []);
      setRentals((rRes && rRes.data) || []);
      setLoaded(true);
    })();
    return () => { cancelled = true; };
  }, []);

  const showVendors = vendors.length >= 1;
  if (!loaded || !showVendors) return null;

  return (
    <>
      {showVendors && (
        <section style={{ padding: '64px 24px', maxWidth: 1200, margin: '0 auto' }}>
          <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(28px,4vw,38px)', fontWeight: 500, textAlign: 'center', marginBottom: 8 }}>
            {ar ? 'شركاء موردون مميزون' : 'Featured vendor partners'}
          </h2>
          <p style={{ textAlign: 'center', color: 'var(--fg-muted)', marginBottom: 32, maxWidth: 640, marginLeft: 'auto', marginRight: 'auto' }}>
            {ar ? 'نظرة على الموردين المعتمدين على منصة سرايا.' : 'A look at approved vendor partners on Saraya.'}
          </p>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(250px, 1fr))', gap: 20 }}>
            {vendors.map((v) => {
              const vname = (ar && v.trade_name_ar) ? v.trade_name_ar : (v.trade_name || (ar ? 'مورّد' : 'Vendor'));
              const mainCat = (v.business_category && v.business_category.length) ? v.business_category[0] : null;
              const vareas = (v.service_areas && v.service_areas.length) ? v.service_areas : (v.city ? [v.city] : []);
              const reqQuote = () => { window.sarayaTrack && window.sarayaTrack('vendor_quote_click', { vendor_id: v.id }); if (window.openRequestQuoteModal) window.openRequestQuoteModal({ vendorId: v.id, vendorName: vname }); else go('design'); };
              return (
                <div key={v.id} className="saraya-lift" style={{ border: '1px solid var(--line)', borderRadius: 16, padding: 20, background: 'var(--white)', display: 'flex', flexDirection: 'column', gap: 11, boxShadow: 'var(--shadow-soft)' }}>
                  <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
                    <div style={{ width: 48, height: 48, borderRadius: 12, background: 'var(--cream)', border: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden', flexShrink: 0 }}>
                      {v.logo_url ? <img src={v.logo_url} alt={vname} style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : <span style={{ fontFamily: 'var(--font-display)', fontSize: 20, color: 'var(--gold-deep)' }}>{(vname || 'V').slice(0, 1)}</span>}
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
                        <span style={{ fontFamily: 'var(--font-display)', fontSize: 17, lineHeight: 1.2 }}>{vname}</span>
                        {v.is_verified && <Icon name="badge-check" size={15} style={{ color: '#15803D', flexShrink: 0 }} />}
                      </div>
                      {mainCat && <div style={{ fontSize: 11, letterSpacing: '0.05em', textTransform: 'uppercase', color: 'var(--gold-deep)', fontWeight: 600, marginTop: 3 }}>{mainCat}</div>}
                    </div>
                  </div>
                  <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap', fontSize: 12.5, color: 'var(--fg-muted)' }}>
                    {vareas.length > 0 && <span><Icon name="map-pin" size={12} style={{ verticalAlign: 'middle', marginInlineEnd: 3 }} />{vareas.join('، ')}</span>}
                    <span>{v.active_listings} {ar ? 'قائمة نشطة' : (v.active_listings === 1 ? 'active listing' : 'active listings')}</span>
                  </div>
                  <div style={{ display: 'flex', gap: 8, marginTop: 4 }}>
                    <button onClick={reqQuote} style={{ flex: 1, padding: '9px 0', borderRadius: 9, border: 'none', background: 'var(--gold)', color: '#fff', fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 700, cursor: 'pointer' }}>
                      {ar ? 'اطلب عرض سعر' : 'Request Quote'}
                    </button>
                    <button onClick={() => { window.sarayaTrack && window.sarayaTrack('vendor_view_click', { vendor_id: v.id }); go('vendors/' + v.slug); }} style={{ flex: 1, padding: '9px 0', borderRadius: 9, border: '1px solid var(--line)', background: 'var(--white)', color: 'var(--fg-primary)', fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 700, cursor: 'pointer' }}>
                      {ar ? 'عرض المتجر' : 'View Store'}
                    </button>
                  </div>
                </div>
              );
            })}
          </div>
          <div style={{ textAlign: 'center', marginTop: 28 }}>
            <button onClick={() => go('vendors')} style={{ padding: '11px 24px', borderRadius: 999, border: '1px solid var(--line)', background: 'transparent', fontFamily: 'var(--font-body)', fontSize: 14, fontWeight: 600, cursor: 'pointer' }}>
              {ar ? 'عرض كل الموردين' : 'View All Vendors'} {'→'}
            </button>
          </div>
        </section>
      )}
    </>
  );
}

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