/* ── Zafa — AI Assistant, Wishlist, Profile ─────────────────────────── */

/* canned, platform-grounded responder */
function aiReply(text, lang) {
  const q = text.toLowerCase();
  const find = (ids) => ids.map((i) => VENDORS.find((v) => v.id === i)).filter(Boolean);
  if (/(flower|floral|florist|زهور|زهر)/.test(q))
  return { text: L(lang, 'For florals, Atelier Lumière is one of our Elite vendors in Dubai — couture bouquets, arches and installations. Here’s their profile:', 'لتنسيق الزهور، أتيليه لوميير من مزوّدي النخبة في دبي. إليك ملفهم:'), vendors: find(['v1']) };
  if (/(makeup|glam|مكياج)/.test(q))
  return { text: L(lang, 'Maison Glow specialises in luxury bridal makeup and soft glam, rated 4.9 from 418 brides:', 'ميزون جلو متخصصة في مكياج العرائس الفاخر بتقييم ٤٫٩:'), vendors: find(['v3']) };
  if (/(photo|camera|film|video|تصوير|مصور)/.test(q))
  return { text: L(lang, 'Two great picks for capturing the day — editorial stills and a cinematic film:', 'خياران رائعان لتوثيق يومك — تصوير فوتوغرافي وفيلم سينمائي:'), vendors: find(['v2', 'v9']) };
  if (/(badge|level|elite|standing|شارة|مستوى|نخبة)/.test(q))
  return { text: L(lang, 'Vendor levels show standing on the platform: Rising (new & promising), Established (verified track record), Premium (consistently top-rated), and Elite (our most trusted, hand-reviewed vendors).', 'مستويات المزوّدين تعكس مكانتهم: صاعد، معتمد، مميّز، ونخبة — الأكثر ثقة لدينا.') };
  if (/(book|reserve|how.*use|deposit|احجز|حجز|كيف)/.test(q))
  return { text: L(lang, 'Booking is simple: open a vendor profile → tap “Request booking” → confirm and pay a deposit securely. The vendor then reaches out to finalise details. You can save favourites to your Wishlist first.', 'الحجز سهل: افتح ملف المزوّد ← اضغط «طلب حجز» ← ادفع دفعة الحجز بأمان، وسيتواصل معك المزوّد.') };
  if (/(budget|cheap|under|price|aed|ميزانية|سعر)/.test(q))
  return { text: L(lang, 'Tell me your category and budget and I’ll match vendors. For example, florals from Atelier Lumière start around AED 1,700 per service:', 'أخبرني بالفئة والميزانية لأرشّح لك. مثلاً، الزهور تبدأ من ١٧٠٠ درهم للخدمة:'), vendors: find(['v1', 'v6']) };
  return { text: L(lang, 'I can help you find vendors across 48 categories, explain vendor badges, or guide you through booking and payment. Try a category like “photographer” or “catering”.', 'أستطيع مساعدتك في إيجاد المزوّدين عبر ٤٨ فئة وشرح الشارات والحجز. جرّب «مصور» أو «طعام».'), vendors: find(['v6']) };
}

function ChatVendorCard({ v }) {
  const { lang, openVendor } = useZafa();
  const cat = catOf(v.cat);
  return (
    <div onClick={() => openVendor(v.id)} style={{ display: 'flex', gap: 11, padding: 9, background: '#fff', borderRadius: 14, border: '1px solid var(--stroke)', cursor: 'pointer', marginTop: 8 }}>
      <div style={{ width: 52, height: 52, borderRadius: 11, overflow: 'hidden', flexShrink: 0 }}><CoverArt theme={v.theme} icon={cat.icon} cat={v.cat} id={`chat-${v.id}`} seed={'c' + v.id} radius={10} w={200} h={200} /></div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', gap: 6, alignItems: 'center' }}>
          <span className="serif" style={{ fontSize: 15.5, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', minWidth: 0 }}>{vName(v, lang)}</span>
          <LevelBadge level={v.level} lang={lang} small />
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 3, fontSize: 12.5, color: 'var(--ink-2)' }}>
          <span style={{ color: 'var(--rose-deep)', fontWeight: 600 }}>{L(lang, cat.en, cat.ar)}</span>
          <Rating value={v.rating} lang={lang} />
        </div>
      </div>
      <Icon name="right" size={18} className="flip-x" style={{ color: 'var(--muted)', alignSelf: 'center' }} />
    </div>);

}

function AIScreen() {
  const { lang, t } = useZafa();
  const [msgs, setMsgs] = React.useState([{ role: 'ai', text: t('aiIntro') }]);
  const [input, setInput] = React.useState('');
  const [typing, setTyping] = React.useState(false);
  const scrollRef = React.useRef(null);
  React.useEffect(() => {const el = scrollRef.current;if (el) el.scrollTop = el.scrollHeight;}, [msgs, typing]);

  const send = (txt) => {
    const text = (txt || input).trim();if (!text) return;
    setMsgs((m) => [...m, { role: 'user', text }]);setInput('');setTyping(true);
    setTimeout(() => {const r = aiReply(text, lang);setTyping(false);setMsgs((m) => [...m, { role: 'ai', text: r.text, vendors: r.vendors }]);}, 1050);
  };

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)' }}>
      {/* header */}
      <div style={{ padding: '8px 18px 12px', display: 'flex', alignItems: 'center', gap: 12, borderBottom: '1px solid var(--line-2)', background: '#fff' }}>
        <div style={{ width: 46, height: 46, borderRadius: '50%', background: 'var(--rose)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink)' }}><Icon name="ai" size={24} fill="currentColor" stroke={0} /></div>
        <div style={{ flex: 1 }}>
          <h2 className="serif" style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>{t('aiTitle')}</h2>
          <p style={{ margin: '1px 0 0', fontSize: 11.5, color: 'var(--muted)', display: 'flex', alignItems: 'center', gap: 5 }}><span style={{ width: 7, height: 7, borderRadius: '50%', background: '#2E9E6B' }} />{t('aiSub')}</p>
        </div>
      </div>

      {/* messages */}
      <div ref={scrollRef} className="z-scroll no-bar" style={{ flex: 1, padding: '18px 16px 8px' }}>
        {msgs.map((m, i) =>
        <div key={i} className="fade-up" style={{ display: 'flex', justifyContent: m.role === 'user' ? 'flex-end' : 'flex-start', marginBottom: 14 }}>
            <div style={{ maxWidth: '82%' }}>
              <div style={{ padding: '12px 15px', borderRadius: m.role === 'user' ? '18px 18px 4px 18px' : '18px 18px 18px 4px',
              background: m.role === 'user' ? 'var(--rose)' : '#fff', color: 'var(--ink)',
              fontSize: 14.5, lineHeight: 1.5, boxShadow: 'var(--sh-sm)', border: m.role === 'ai' ? '1px solid var(--line-2)' : 'none', textWrap: 'pretty' }}>
                {m.text}
              </div>
              {m.vendors && m.vendors.map((v) => <ChatVendorCard key={v.id} v={v} />)}
            </div>
          </div>
        )}
        {typing && <div style={{ display: 'flex', marginBottom: 14 }}><div style={{ padding: '14px 16px', borderRadius: '18px 18px 18px 4px', background: '#fff', border: '1px solid var(--line-2)', boxShadow: 'var(--sh-sm)' }}><Dots /></div></div>}

        {/* suggestions (only at start) */}
        {msgs.length === 1 && !typing &&
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 9, marginTop: 6 }}>
            {AI_SUGGESTIONS[lang].map((s) => <Chip key={s} icon="spark" onClick={() => send(s)}>{s}</Chip>)}
          </div>
        }
      </div>

      {/* input */}
      <div style={{ padding: '10px 16px 12px', marginBottom: 92, borderTop: '1px solid var(--line)', background: '#fff' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, background: 'var(--bg)', border: '1.5px solid var(--line)', borderRadius: 999, padding: '5px 6px 5px 16px' }}>
          <input value={input} onChange={(e) => setInput(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && send()} placeholder={t('aiPlaceholder')}
          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>);

}

/* ── Wishlist ── */
function WishCard({ v }) {
  const { lang, openVendor, toggleWish } = useZafa();
  const cat = catOf(v.cat);
  return (
    <div className="z-card fade-up" style={{ cursor: 'pointer' }} onClick={() => openVendor(v.id)}>
      <div style={{ position: 'relative', aspectRatio: '3/2' }}>
        <CoverArt theme={v.theme} icon={catOf(v.cat).icon} cat={v.cat} kw={v.cat === 'makeup' || v.cat === 'flowers' ? 'bouquet,flowers' : v.kw} id={`wish-${v.id}`} seed={'wf2' + v.id} w={600} h={420} />
        <button onClick={(e) => {e.stopPropagation();toggleWish(v.id);}} style={{ position: 'absolute', top: 8, insetInlineEnd: 8, width: 34, height: 34, borderRadius: '50%', border: 'none', background: 'rgba(255,255,255,.92)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--rose-deep)', boxShadow: 'var(--sh-sm)' }}><Icon name="heart" size={17} fill="currentColor" /></button>
        <div style={{ position: 'absolute', top: 8, insetInlineStart: 8 }}><LevelBadge level={v.level} lang={lang} small /></div>
      </div>
      <div style={{ padding: '10px 12px 12px' }}>
        <h3 className="serif" style={{ margin: 0, fontSize: 15.5, fontWeight: 600, lineHeight: 1.15 }}>{vName(v, lang)}</h3>
        <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginTop: 4, fontSize: 12 }}>
          <span style={{ color: 'var(--rose-deep)', fontWeight: 600 }}>{L(lang, cat.en, cat.ar)}</span>
          <Rating value={v.rating} lang={lang} />
        </div>
      </div>
    </div>);

}

function WishlistScreen() {
  const { lang, t, wish, setTab } = useZafa();
  const saved = VENDORS.filter((v) => wish.has(v.id));
  return (
    <div className="z-scroll no-bar" style={{ background: 'var(--bg)', height: '100%' }}>
      <div style={{ padding: '12px 18px 6px', display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
        <h1 className="h1" style={{ margin: 0, fontSize: 27 }}>{t('wishlist')}</h1>
        {saved.length > 0 && <span className="sec" style={{ fontSize: 14, fontWeight: 600 }}>{saved.length} {L(lang, 'saved', 'محفوظ')}</span>}
      </div>
      {saved.length === 0 ?
      <div style={{ height: 'calc(100% - 50px)' }}><EmptyState icon="heart" title={t('wishlistEmpty')} sub={t('wishlistEmptySub')} cta={t('browseVendors')} onCta={() => setTab('home')} /></div> :
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 13, padding: '14px 18px 30px' }}>{saved.map((v) => <WishCard key={v.id} v={v} />)}</div>}
    </div>);

}

/* ── Profile & Settings ── */
function ProfileScreen() {
  const { lang, t, setLang, push, enterVendor } = useZafa();
  const rows = [
  { icon: 'bell', label: t('notifications'), dest: 'notifications' },
  { icon: 'card', label: t('payments'), dest: 'payments' },
  { icon: 'shield', label: L(lang, 'Privacy & security', 'الخصوصية والأمان'), dest: 'privacy' },
  { icon: 'chat', label: t('help'), dest: 'help' }];

  return (
    <div className="z-scroll no-bar" style={{ background: 'var(--bg)', height: '100%' }}>
      <div style={{ padding: '12px 18px 6px' }}><h1 className="h1" style={{ margin: 0, fontSize: 27 }}>{t('profile')}</h1></div>

      {/* user card */}
      <div style={{ padding: '14px 18px 4px' }}>
        <div className="z-card" style={{ padding: 16, display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ width: 60, height: 60, borderRadius: '50%', overflow: 'hidden', flexShrink: 0, border: '2px solid var(--rose-200)' }}><Img id="me-avatar" ph="" radius={30} /></div>
          <div style={{ flex: 1 }}>
            <h2 className="serif" style={{ margin: 0, fontSize: 19, fontWeight: 600 }}>{L(lang, 'Sara Al Mansoori', 'سارة المنصوري')}</h2>
            <p className="sec" style={{ margin: '2px 0 0', fontSize: 13.5, direction: 'ltr', textAlign: lang === 'ar' ? 'right' : 'left' }}>+971 50 123 4567</p>
          </div>
          <button style={{ width: 38, height: 38, borderRadius: '50%', border: '1px solid var(--line)', background: '#fff', cursor: 'pointer', color: 'var(--ink-2)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="edit" size={18} /></button>
        </div>
      </div>

      {/* become a vendor — opens the vendor experience */}
      <div style={{ padding: '18px 18px 4px' }}>
        <div onClick={() => enterVendor()} className="z-card" style={{ cursor: 'pointer', padding: 16, display: 'flex', alignItems: 'center', gap: 13 }}>
          <span style={{ width: 44, height: 44, borderRadius: 13, background: 'var(--rose-100)', color: 'var(--rose-deep)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="store" size={22} stroke={1.9} /></span>
          <div style={{ flex: 1 }}>
            <p style={{ margin: 0, fontWeight: 700, fontSize: 15 }}>{L(lang, 'Become a vendor', 'كن مزوّداً')}</p>
            <p className="muted" style={{ margin: '2px 0 0', fontSize: 12.5 }}>{L(lang, 'Subscribe & list your wedding services', 'اشترك واعرض خدماتك')}</p>
          </div>
          <Icon name="right" size={18} className="flip-x" style={{ color: 'var(--muted)' }} />
        </div>
      </div>

      {/* post an ad — guest advertiser */}
      <div style={{ padding: '18px 18px 4px' }}>
        <div onClick={() => push({ name: 'postad' })} style={{ cursor: 'pointer', borderRadius: 22, padding: 20, position: 'relative', overflow: 'hidden', background: '#2C3550', color: '#fff' }}>
          <span className="z-badge z-badge--gold" style={{ marginBottom: 12 }}><Icon name="megaphone" size={11} stroke={2} />{t('forEveryone')}</span>
          <h2 className="serif" style={{ margin: '10px 0 6px', fontSize: 22, fontWeight: 600, color: '#fff' }}>{L(lang, 'Post an ad to the marketplace', 'انشر إعلاناً في السوق')}</h2>
          <p style={{ margin: 0, fontSize: 13.5, lineHeight: 1.5, color: 'rgba(255,255,255,.8)', maxWidth: 270 }}>{t('postAdSub')}</p>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7, marginTop: 16, background: 'var(--rose)', color: 'var(--ink)', padding: '11px 18px', borderRadius: 12, fontWeight: 700, fontSize: 14 }}>
            {t('startPosting')}<Icon name="arrow" size={17} className="flip-x" />
          </div>
        </div>
      </div>

      {/* language toggle */}
      <div style={{ padding: '20px 18px 4px' }}>
        <p className="lbl" style={{ marginBottom: 10 }}>{t('language')}</p>
        <div style={{ display: 'flex', gap: 8, background: '#fff', border: '1px solid var(--line)', borderRadius: 14, padding: 5 }}>
          {[{ id: 'en', t: 'English' }, { id: 'ar', t: 'العربية' }].map((o) =>
          <button key={o.id} onClick={() => setLang(o.id)} style={{ flex: 1, height: 44, borderRadius: 10, border: 'none', cursor: 'pointer',
            background: lang === o.id ? 'var(--rose)' : 'transparent', color: 'var(--ink)', fontWeight: 600, fontSize: 15, fontFamily: o.id === 'ar' ? 'var(--serif)' : 'var(--sans)', transition: 'background .15s' }}>{o.t}</button>
          )}
        </div>
      </div>

      {/* my products */}
      <div style={{ padding: '20px 18px 4px' }}>
        <p className="lbl" style={{ marginBottom: 10 }}>{L(lang, 'Selling', 'البيع')}</p>
        <div className="z-card" style={{ padding: '2px 16px' }}>
          <button onClick={() => push({ name: 'myproducts' })} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 13, padding: '14px 0', background: 'none', border: 'none', cursor: 'pointer', textAlign: 'start' }}>
            <span style={{ width: 34, height: 34, borderRadius: 10, background: 'var(--rose-100)', color: 'var(--rose-deep)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="store" size={18} stroke={1.9} /></span>
            <span style={{ flex: 1, fontSize: 15, fontWeight: 500, color: 'var(--ink)' }}>{L(lang, 'My products', 'منتجاتي')}</span>
            <span className="muted" style={{ fontSize: 13 }}>{(window.__myProducts || MY_PRODUCTS).length}</span>
            <Icon name="right" size={17} className="flip-x" style={{ color: 'var(--muted)' }} />
          </button>
        </div>
      </div>

      {/* settings list */}
      <div style={{ padding: '20px 18px 4px' }}>
        <p className="lbl" style={{ marginBottom: 10 }}>{t('account')}</p>
        <div className="z-card" style={{ padding: '2px 16px' }}>
          {rows.map((r, i) =>
          <button key={r.label} onClick={() => push({ name: r.dest })} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 13, padding: '14px 0', background: 'none', border: 'none', borderBottom: i < rows.length - 1 ? '1px solid var(--line-2)' : 'none', cursor: 'pointer', textAlign: 'start' }}>
              <span style={{ width: 34, height: 34, borderRadius: 10, background: 'var(--rose-100)', color: 'var(--rose-deep)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name={r.icon} size={18} stroke={1.9} /></span>
              <span style={{ flex: 1, fontSize: 15, fontWeight: 500, color: 'var(--ink)' }}>{r.label}</span>
              <Icon name="right" size={17} className="flip-x" style={{ color: 'var(--muted)' }} />
            </button>
          )}
        </div>
      </div>

      <div style={{ padding: '18px 18px 36px' }}>
        <button style={{ width: '100%', height: 52, borderRadius: 14, border: '1.5px solid var(--line)', background: '#fff', cursor: 'pointer', color: '#C0392B', fontWeight: 600, fontSize: 15, fontFamily: 'var(--sans)' }}>{t('signOut')}</button>
        <p className="muted" style={{ textAlign: 'center', fontSize: 12, marginTop: 16 }}>Version 1.0.0</p>
      </div>
    </div>);

}

Object.assign(window, { AIScreen, WishlistScreen, ProfileScreen, ChatVendorCard, WishCard });