/* ── Zafa — Search results + Category listing ───────────────────────── */

const LEVEL_ORDER = ['elite', 'premium', 'established', 'rising'];

function FilterSheet({ levels, setLevels, sort, setSort, onClose, onApply }) {
  const { lang, t } = useZafa();
  const sorts = [['top', L(lang, 'Top rated', 'الأعلى تقييماً')], ['reviews', L(lang, 'Most reviewed', 'الأكثر تقييماً')], ['az', L(lang, 'A → Z', 'أ → ي')]];
  return (
    <div className="z-overlay" onClick={onClose}>
      <div className="z-sheet" onClick={(e) => e.stopPropagation()}>
        <div className="z-grab" />
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18 }}>
          <h2 className="h2" style={{ margin: 0 }}>{t('allFilters')}</h2>
          <button onClick={onClose} className="z-glass" style={{ background: 'var(--rose-100)', color: 'var(--rose-deep)', boxShadow: 'none' }}><Icon name="x" size={18} /></button>
        </div>
        <p className="lbl" style={{ marginBottom: 10 }}>{L(lang, 'Vendor level', 'مستوى المزوّد')}</p>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 9, marginBottom: 22 }}>
          {LEVEL_ORDER.map(lv => <Chip key={lv} on={levels.includes(lv)} onClick={() => setLevels(s => s.includes(lv) ? s.filter(x => x !== lv) : [...s, lv])}>{L(lang, LEVELS[lv].en, LEVELS[lv].ar)}</Chip>)}
        </div>
        <p className="lbl" style={{ marginBottom: 10 }}>{t('sortBy')}</p>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 9, marginBottom: 26 }}>
          {sorts.map(([k, lbl]) => <Chip key={k} on={sort === k} onClick={() => setSort(k)}>{lbl}</Chip>)}
        </div>
        <Btn variant="rose" onClick={onApply}>{L(lang, 'Show results', 'عرض النتائج')}</Btn>
      </div>
    </div>
  );
}

function sortVendors(arr, sort, lang) {
  const a = [...arr];
  if (sort === 'reviews') a.sort((x, y) => y.reviews - x.reviews);
  else if (sort === 'az') a.sort((x, y) => vName(x, lang).localeCompare(vName(y, lang)));
  else a.sort((x, y) => y.rating - x.rating);
  return a;
}

/* ── Category listing ── */
function CategoryListing({ catId }) {
  const { lang, t, pop } = useZafa();
  const cat = catOf(catId);
  const [levels, setLevels] = React.useState([]);
  const [sort, setSort] = React.useState('top');
  const [sheet, setSheet] = React.useState(false);
  const [loading, setLoading] = React.useState(true);
  React.useEffect(() => { const id = setTimeout(() => setLoading(false), 650); return () => clearTimeout(id); }, [catId]);

  const inCat = VENDORS.filter(v => v.cat === catId);
  const others = VENDORS.filter(v => v.cat !== catId);
  let primary = inCat.length ? inCat : VENDORS.slice(0, 4);
  if (levels.length) primary = primary.filter(v => levels.includes(v.level));
  primary = sortVendors(primary, sort, lang);
  const fc = levels.length + (sort !== 'top' ? 1 : 0);
  const th = catTheme(catId);

  return (
    <div className="z-scroll no-bar" style={{ background: 'var(--bg)', position: 'relative' }}>
      {/* arched category banner */}
      <div style={{ position: 'relative', padding: '8px 16px 0' }}>
        <div className="arch" style={{ height: 190 }}>
          <CoverArt theme={th} icon={cat.icon} cat={catId} id={`catban-${catId}`} seed={'b' + catId} w={800} h={420} />
          <div style={{ position: 'absolute', inset: 0, background: 'rgba(20,14,17,.34)' }} />
        </div>
        <button onClick={pop} className="z-glass" style={{ position: 'absolute', top: 18, insetInlineStart: 26 }}><Icon name="left" size={20} className="flip-x" /></button>
        <div style={{ position: 'absolute', bottom: 16, insetInlineStart: 30, color: '#fff' }}>
          <h1 className="serif" style={{ margin: 0, fontSize: 27, fontWeight: 600, color: '#fff' }}>{L(lang, cat.en, cat.ar)}</h1>
          <p style={{ margin: '2px 0 0', fontSize: 13, color: 'rgba(255,255,255,.85)' }}>{cat.n} {L(lang, 'vendors', 'مزوّد')}</p>
        </div>
      </div>

      {/* filter chips */}
      <div className="no-bar" style={{ display: 'flex', gap: 9, overflowX: 'auto', padding: '16px 20px 4px', position: 'sticky', top: 0, background: 'var(--bg)', zIndex: 5 }}>
        <Chip rose icon="sliders" onClick={() => setSheet(true)}>{t('filters')}{fc ? ` · ${fc}` : ''}</Chip>
        {LEVEL_ORDER.map(lv => <Chip key={lv} on={levels.includes(lv)} onClick={() => setLevels(s => s.includes(lv) ? s.filter(x => x !== lv) : [...s, lv])}>{L(lang, LEVELS[lv].en, LEVELS[lv].ar)}</Chip>)}
      </div>

      {loading ? (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16, padding: '12px 20px' }}>
          {[0, 1, 2].map(i => <div key={i} className="z-card"><div className="skel" style={{ aspectRatio: '16/10' }} /><div style={{ padding: 15 }}><div className="skel" style={{ height: 18, width: '55%', borderRadius: 6 }} /><div className="skel" style={{ height: 13, width: '40%', borderRadius: 6, marginTop: 10 }} /></div></div>)}
        </div>
      ) : (
        <>
          <p className="sec" style={{ padding: '14px 22px 4px', fontSize: 13.5, fontWeight: 600 }}>{primary.length} {t('results')} · {t('sortBy')}</p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16, padding: '8px 20px 12px' }}>{primary.map((v, i) => <VendorCard key={v.id} v={v} delay={i * 50} />)}</div>
          {inCat.length > 0 && (
            <div style={{ padding: '12px 20px 32px' }}>
              <SectionHeader icon="spark" title={L(lang, 'More you might like', 'قد يعجبك أيضاً')} />
              <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>{others.slice(0, 3).map(v => <VendorCard key={v.id} v={v} />)}</div>
            </div>
          )}
        </>
      )}
      {sheet && <FilterSheet levels={levels} setLevels={setLevels} sort={sort} setSort={setSort} onClose={() => setSheet(false)} onApply={() => setSheet(false)} />}
    </div>
  );
}

/* ── Search results (tab) ── */
function SearchScreen() {
  const { lang, t, push, setTab } = useZafa();
  const [q, setQ] = React.useState('');
  const [levels, setLevels] = React.useState([]);
  const recent = L(lang, ['Florist', 'Makeup artist', 'Photographer'], ['منسق زهور', 'خبيرة مكياج', 'مصور']);
  const quickCats = CATEGORIES.slice(0, 6);

  const ql = q.trim().toLowerCase();
  let results = !ql ? [] : VENDORS.filter(v => {
    const c = catOf(v.cat);
    return vName(v, lang).toLowerCase().includes(ql) || vName(v, 'en').toLowerCase().includes(ql) || c.en.toLowerCase().includes(ql) || c.ar.includes(q) || v.tag.toLowerCase().includes(ql);
  });
  if (ql && levels.length) results = results.filter(v => levels.includes(v.level));
  const showEmpty = ql && results.length === 0;

  return (
    <div className="z-scroll no-bar" style={{ background: 'var(--bg)', display: 'flex', flexDirection: 'column' }}>
      <div style={{ position: 'sticky', top: 0, zIndex: 10, background: 'var(--bg)', padding: '12px 20px 12px' }}>
        {!ql && <h1 className="h1" style={{ margin: '0 0 16px', fontSize: 30, whiteSpace: 'pre-line' }}>{t('whatDreaming')}</h1>}
        <SearchField value={q} onChange={(e) => setQ(e.target.value)} placeholder={t('trySearch')} autoFocus />
        {ql && (
          <div className="no-bar" style={{ display: 'flex', gap: 9, overflowX: 'auto', marginTop: 12 }}>
            {LEVEL_ORDER.map(lv => <Chip key={lv} on={levels.includes(lv)} onClick={() => setLevels(s => s.includes(lv) ? s.filter(x => x !== lv) : [...s, lv])}>{L(lang, LEVELS[lv].en, LEVELS[lv].ar)}</Chip>)}
          </div>
        )}
      </div>

      {!ql && (
        <div className="fade-in" style={{ padding: '4px 20px 30px' }}>
          <SectionHeader icon="spark" title={t('recentSearches')} serif={false} />
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 9, marginBottom: 26 }}>
            {recent.map(r => <Chip key={r} icon="search" onClick={() => setQ(r)}>{r}</Chip>)}
          </div>
          <SectionHeader icon="spark" title={t('browseCategory')} serif={false} />
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: '18px 13px' }}>
            {quickCats.map((c, i) => <CategoryTile key={c.id} c={c} i={i} onClick={() => push({ name: 'category', id: c.id })} />)}
          </div>
        </div>
      )}

      {ql && !showEmpty && (
        <div style={{ padding: '14px 20px 30px' }}>
          <p className="sec" style={{ fontSize: 13.5, fontWeight: 600, margin: '0 0 12px' }}>{results.length} {t('results')} · “{q}”</p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>{results.map((v, i) => <VendorCard key={v.id} v={v} delay={i * 45} />)}</div>
        </div>
      )}

      {showEmpty && (
        <div style={{ flex: 1 }}>
          <EmptyState icon="search" title={t('noResults')} sub={t('noResultsSub')} cta={t('clearFilters')} onCta={() => { setQ(''); setLevels([]); }} />
        </div>
      )}
    </div>
  );
}

Object.assign(window, { CategoryListing, SearchScreen, FilterSheet });
