/* ── Zafa — shared context + UI primitives (creative redesign) ──────── */
const ZafaCtx = React.createContext(null);
const useZafa = () => React.useContext(ZafaCtx);
const L = (lang, en, ar) => lang === 'ar' ? ar : en;

function vName(v, lang) {return lang === 'ar' ? v.ar : v.name;}
function vLoc(v, lang) {return lang === 'ar' ? v.locAr : v.loc;}
function catOf(id) {return CATEGORIES.find((c) => c.id === id);}

/* ── Button ── */
function Btn({ variant = 'rose', children, icon, iconR, onClick, style, disabled, sm }) {
  return (
    <button className={`z-btn z-btn--${variant}${sm ? ' z-btn--sm' : ''}`} onClick={onClick} disabled={disabled} style={style}>
      {icon && <Icon name={icon} size={sm ? 17 : 19} />}
      {children}
      {iconR && <Icon name={iconR} size={sm ? 17 : 19} className="flip-x" />}
    </button>);

}

/* ── Chip ── */
function Chip({ children, on, rose, icon, onClick }) {
  return (
    <button className={`z-chip${on ? ' z-chip--on' : ''}${rose ? ' z-chip--rose' : ''}`} onClick={onClick}>
      {icon && <Icon name={icon} size={15} />}
      {children}
    </button>);

}

/* ── Level badge ── */
function LevelBadge({ level, lang, small }) {
  const lv = LEVELS[level];if (!lv) return null;
  return (
    <span className={`z-badge z-badge--${lv.tone}`} style={small ? { fontSize: 9.5, padding: '3px 7px 2px' } : null}>
      {lv.tone === 'gold' && <Icon name="star" size={10} fill="currentColor" stroke={0} />}
      {L(lang, lv.en, lv.ar)}
    </span>);

}

/* ── Rating ── */
function Rating({ value, reviews, lang, light }) {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 13, fontWeight: 600, color: light ? 'rgba(255,255,255,.95)' : 'var(--ink)' }}>
      <StarFill size={13} />{value.toFixed(1)}
      {reviews != null && <span style={{ color: light ? 'rgba(255,255,255,.72)' : 'var(--muted)', fontWeight: 500 }}>({reviews})</span>}
    </span>);

}

/* ── plain droppable image (avatars etc.) ── */
function Img({ id, style, ph, radius = 0, fit = 'cover' }) {
  return React.createElement('image-slot', {
    id, radius: String(radius), fit, placeholder: ph || '',
    style: { width: '100%', height: '100%', display: 'block', ...style }
  });
}

/* ── Heart toggle ── */
function Heart({ id, lang, light }) {
  const { wish, toggleWish } = useZafa();
  const on = wish.has(id);
  return (
    <button onClick={(e) => {e.stopPropagation();toggleWish(id);}} className="z-glass"
    style={{ color: on ? 'var(--rose-deep)' : 'var(--ink)' }} aria-label="save">
      <Icon name="heart" size={19} fill={on ? 'currentColor' : 'none'} />
    </button>);

}

/* ── Vendor / Ad card (feed) ── */
function VendorCard({ v, delay = 0, compact }) {
  const { lang, openVendor, t } = useZafa();
  const cat = catOf(v.cat);
  const isAd = v.type === 'ad';
  return (
    <div className="z-card fade-up" style={{ animationDelay: delay + 'ms', cursor: 'pointer' }} onClick={() => openVendor(v.id)}>
      <div style={{ padding: '15px 15px 0' }}>
        <div style={{ position: 'relative', aspectRatio: compact ? '3/2' : '16/10', borderRadius: 14, overflow: 'hidden' }}>
          <CoverArt theme={v.theme} icon={cat.icon} cat={v.cat} kw={v.kw} src={v.img} id={`card-${v.id}`} radius={14} w={600} h={420} ph={L(lang, 'Add photo', 'أضف صورة')} />
          <div style={{ position: 'absolute', top: 12, insetInlineStart: 12, display: 'flex', gap: 6 }}>
            {isAd ?
            <span className="z-badge z-badge--gold"><Icon name="spark" size={11} stroke={2.4} />{t('boosted')}</span> :
            <LevelBadge level={v.level} lang={lang} />}
          </div>
          <div style={{ position: 'absolute', top: 10, insetInlineEnd: 10 }}><Heart id={v.id} lang={lang} light /></div>
        </div>
      </div>
      <div style={{ padding: compact ? '11px 15px 14px' : '12px 15px 16px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 }}>
          <h3 className="h3" style={{ margin: 0, fontSize: compact ? 16 : 19, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{vName(v, lang)}</h3>
          {!isAd && !compact && <Rating value={v.rating} lang={lang} />}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 5, color: 'var(--ink-2)', fontSize: 13 }}>
          <span style={{ color: 'var(--rose-deep)', fontWeight: 600 }}>{L(lang, cat.en, cat.ar)}</span>
          <span className="muted">·</span>
          <Icon name="pin" size={13} style={{ color: 'var(--muted)' }} />
          <span className="muted" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{vLoc(v, lang)}</span>
        </div>
        {!compact && <p className="sec" style={{ margin: '9px 0 0', fontSize: 13.5, lineHeight: 1.45, textWrap: 'pretty' }}>{isAd ? v.tag.replace(/^Guest ad · /, '') : v.tag}</p>}
      </div>
    </div>);

}

/* ── Featured carousel — same card design as “Top picks” ── */
function FeaturedCard({ v }) {
  return (
    <div style={{ minWidth: 286, width: 286, flexShrink: 0, scrollSnapAlign: 'start' }}>
      <VendorCard v={v} />
    </div>);

}

/* ── Category tile — alternating solid color boxes + line icon ── */
function CategoryTile({ c, onClick, big, i = 0 }) {
  const { lang } = useZafa();
  const alt = i % 2 === 1;
  const rose = c.id === 'flowers' || c.id === 'videography';
  const bg = rose ? '#FCE7EE' : alt ? '#DFE1E5' : '#FCE7EE';
  const ic = rose ? '#F6B0C6' : alt ? '#2C3550' : '#F6B0C6';
  return (
    <button onClick={onClick} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0,
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 7, width: '100%', textAlign: 'center' }}>
      <div style={{ width: '100%', aspectRatio: '1', borderRadius: 18, background: bg,
        display: 'flex', alignItems: 'center', justifyContent: 'center', color: ic }}>
        <Icon name={c.icon} size={30} stroke={1.8} />
      </div>
      <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink)', lineHeight: 1.2, textAlign: 'center', textWrap: 'pretty' }}>{L(lang, c.en, c.ar)}</span>
    </button>);

}

/* ── Section header ── */
function SectionHeader({ title, icon, iconColor = 'var(--gold)', action, onAction, serif = true }) {
  const heading = icon ?
  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}><Icon name={icon} size={serif ? 18 : 16} style={{ color: iconColor }} />{title}</span> :
  title;
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '0 2px', marginBottom: 13 }}>
      <h2 className={serif ? 'h2' : ''} style={serif ? { margin: 0, fontSize: 21 } : { margin: 0, fontSize: 15, fontWeight: 700, letterSpacing: '.01em' }}>{heading}</h2>
      {action && <button onClick={onAction} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--rose-deep)', fontWeight: 600, fontSize: 13.5, fontFamily: 'var(--sans)', display: 'flex', alignItems: 'center', gap: 3 }}>
        {action}<Icon name="right" size={15} className="flip-x" />
      </button>}
    </div>);

}

/* ── Animated tappable search bar (decorative) ── */
function SearchBar({ onClick, onSpark }) {
  const { lang } = useZafa();
  const phrases = L(lang,
  ['"florists in Dubai"', '"henna artists"', '"wedding cakes"'],
  ['«منسقو زهور في دبي»', '«فنانو الحناء»', '«كيك الأعراس»']);
  return (
    <div className="z-searchbar" onClick={onClick}>
      <Icon name="search" size={21} style={{ color: 'var(--rose-deep)', flexShrink: 0 }} />
      <div className="ph">
        <b>{[...phrases, phrases[0]].map((p, i) => <i key={i}>{L(lang, 'Try ', 'جرّب ')}{p}</i>)}</b>
      </div>
      <button className="z-spark-btn" onClick={(e) => {e.stopPropagation();onSpark && onSpark();}} aria-label="Filters"><Icon name="filter" size={20} stroke={2.2} /></button>
    </div>);

}

/* ── Functional search input (typing) ── */
function SearchField({ value, onChange, onFocus, placeholder, readOnly, autoFocus }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, background: '#fff', border: '1px solid var(--stroke)', borderRadius: 'var(--r-pill)', padding: '0 16px', height: 52, boxShadow: 'none' }}>
      <Icon name="search" size={20} style={{ color: 'var(--rose-deep)', flexShrink: 0 }} />
      <input value={value} onChange={onChange} onFocus={onFocus} placeholder={placeholder} readOnly={readOnly} autoFocus={autoFocus}
      style={{ flex: 1, border: 'none', outline: 'none', background: 'none', fontFamily: 'var(--sans)', fontSize: 15, color: 'var(--ink)', minWidth: 0 }} />
      {value ? <button onClick={() => onChange({ target: { value: '' } })} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--muted)', padding: 4, display: 'flex' }}><Icon name="x" size={17} /></button> : null}
    </div>);

}

/* ── Empty state ── */
function EmptyState({ icon, title, sub, cta, onCta }) {
  return (
    <div className="fade-up" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center', padding: '40px 30px', height: '100%' }}>
      <div style={{ width: 96, height: 96, borderRadius: '50%', background: 'var(--rose-100)', color: 'var(--rose-deep)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 22 }}>
        <Icon name={icon} size={40} stroke={1.6} />
      </div>
      <h2 className="h2" style={{ margin: '0 0 8px' }}>{title}</h2>
      <p className="sec" style={{ margin: 0, fontSize: 15, lineHeight: 1.5, maxWidth: 270 }}>{sub}</p>
      {cta && <div style={{ marginTop: 26, width: '100%', maxWidth: 240 }}><Btn variant="rose" onClick={onCta}>{cta}</Btn></div>}
    </div>);

}

/* ── typing dots ── */
function Dots() {
  return (
    <span style={{ display: 'inline-flex', gap: 4, alignItems: 'center', padding: '2px 0' }}>
      {[0, 1, 2].map((i) => <span key={i} style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--muted)', animation: `dot 1.2s infinite ${i * 0.15}s` }} />)}
    </span>);

}

/* ── Floating dock nav (Home · Search · AI Assistant · Wishlist · Profile) ── */
function FloatingDock() {
  const { tab, setTab, lang, push } = useZafa();
  const Item = ({ id, icon, label }) => {
    const on = tab === id;
    return (
      <button className={`z-dock-item${on ? ' z-dock-item--on' : ''}`} onClick={() => setTab(id)}>
        <Icon name={icon} size={22} stroke={on ? 2.2 : 1.8} fill={id === 'wishlist' && on ? 'currentColor' : 'none'} />
        <span>{label}</span>
      </button>);

  };
  const aiOn = tab === 'ai';
  return (
    <div className="z-dock-wrap">
      <div className="z-dock">
        <Item id="home" icon="home" label={L(lang, 'Home', 'الرئيسية')} />
        <Item id="search" icon="search" label={L(lang, 'Search', 'البحث')} />
        <button className={`z-dock-ai${aiOn ? ' on' : ''}`} onClick={() => setTab('ai')} aria-label="AI Assistant">
          <span className="z-dock-fab"><Icon name="ai" size={24} fill="currentColor" stroke={0} /></span>
          <span>{L(lang, 'AI Assistant', 'المساعد')}</span>
        </button>
        <Item id="wishlist" icon="heart" label={L(lang, 'Wishlist', 'المفضلة')} />
        <button className="z-dock-item" onClick={() => push({ name: 'marketplace' })}>
          <Icon name="store" size={22} stroke={1.8} />
          <span>{L(lang, 'Marketplace', 'السوق')}</span>
        </button>
      </div>
    </div>);

}

/* ── Account / quick settings — full page (pushed route) ── */
function QuickSettings() {
  const { lang, setLang, t, pop, setTab, 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%' }}>
      {/* header: Profile title + back */}
      <div style={{ padding: '8px 20px 2px', display: 'flex', alignItems: 'center', gap: 12 }}>
        <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>
        <h1 className="h1" style={{ margin: 0, fontSize: 27 }}>{L(lang, 'Profile', 'حسابي')}</h1>
      </div>

      {/* identity + edit */}
      <div style={{ padding: '14px 20px 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" radius={30} ph="" /></div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <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', flexShrink: 0 }}><Icon name="edit" size={18} /></button>
        </div>
      </div>

      {/* post an ad */}
      <div style={{ padding: '18px 20px 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' }}>{t('postAd')}</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 20px 4px' }}>
        <p className="lbl" style={{ marginBottom: 10 }}>{t('language')}</p>
        <div className="z-seg">
          {[{ id: 'en', t: 'English' }, { id: 'ar', t: 'العربية' }].map((o) =>
          <button key={o.id} className={lang === o.id ? 'on' : ''} onClick={() => setLang(o.id)} style={{ fontFamily: o.id === 'ar' ? 'var(--serif)' : 'var(--sans)' }}>{o.t}</button>
          )}
        </div>
      </div>

      {/* account rows */}
      <div style={{ padding: '20px 20px 4px' }}>
        <p className="lbl" style={{ marginBottom: 10 }}>{L(lang, 'Selling', 'البيع')}</p>
        <div className="z-card" style={{ padding: '2px 16px', marginBottom: 20 }}>
          <button onClick={() => push({ name: 'myproducts' })} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 13, padding: '15px 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>
        <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: '15px 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>

      {/* sign out */}
      <div style={{ padding: '20px 20px 36px' }}>
        <button onClick={pop} 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>);

}

/* ── App top bar (logo mark + bell + avatar) — no wordmark ── */
function TopBar({ onBell, title }) {
  const { push } = useZafa();
  return (
    <div style={{ position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'flex-end', minHeight: 44, padding: '2px 2px' }}>
      <img src={window.ASSET('logo')} alt="" style={{ height: 40, width: 'auto', position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%, -50%)' }} />
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <button onClick={onBell} className="z-glass" style={{ width: 44, height: 44, position: 'relative', border: '1px solid var(--line)', background: '#fff' }}>
          <Icon name="bell" size={21} stroke={1.8} />
          <span style={{ position: 'absolute', top: 11, insetInlineEnd: 12, width: 8, height: 8, borderRadius: '50%', background: 'var(--rose-deep)', border: '1.5px solid #fff' }} />
        </button>
        <button onClick={() => push({ name: 'account' })} style={{ width: 44, height: 44, borderRadius: '50%', padding: 0, border: '2px solid var(--rose-200)', background: '#fff', cursor: 'pointer', overflow: 'hidden', flexShrink: 0 }} aria-label="Account">
          <Img id="me-avatar" radius={22} ph="" />
        </button>
      </div>
    </div>);

}

/* ── Inner screen header ── */
function ScreenHeader({ title, onBack, right }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '2px 0' }}>
      <button onClick={onBack} className="z-glass" style={{ background: '#fff', border: '1px solid var(--line)', flexShrink: 0 }}>
        <Icon name="left" size={20} className="flip-x" />
      </button>
      <h1 className="serif" style={{ flex: 1, margin: 0, fontSize: 22, fontWeight: 600 }}>{title}</h1>
      {right}
    </div>);

}

Object.assign(window, {
  ZafaCtx, useZafa, L, vName, vLoc, catOf,
  Btn, Chip, LevelBadge, Rating, Img, Heart, VendorCard, FeaturedCard, CategoryTile,
  SectionHeader, SearchBar, SearchField, EmptyState, Dots, FloatingDock, TopBar, ScreenHeader, QuickSettings
});