/* AMBER & ZAFRAN — Search */
function SearchBar({ t, lang, query, onQueryChange, onBack }) {
  const inputRef = useRef(null);
  useEffect(() => { inputRef.current && inputRef.current.focus(); }, []);
  return (
    <div style={{ position: 'sticky', top: 0, zIndex: 30, background: 'rgba(251,248,243,.95)', backdropFilter: 'blur(16px)', borderBottom: '1px solid var(--line-2)' }}>
      <StatusBar dark={false} />
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '4px 18px 16px' }}>
        <button className="iconbtn" onClick={onBack} aria-label={lang === 'ar' ? 'رجوع' : 'Back'} style={{ width: 42, height: 42, display: 'grid', placeItems: 'center', flex: 'none' }}>
          <Icon.chevron style={{ transform: t.dir === 'rtl' ? 'none' : 'rotate(180deg)' }} />
        </button>
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 10, border: '1px solid var(--ink)', background: 'var(--paper)', padding: '0 14px' }}>
          <Icon.search style={{ color: 'var(--ink-soft)', flex: 'none' }} />
          <input
            ref={inputRef}
            value={query}
            onChange={(e) => onQueryChange(e.target.value)}
            placeholder={t.searchPh}
            style={{ flex: 1, border: 'none', background: 'transparent', padding: '14px 0', fontFamily: lang === 'ar' ? 'var(--arabic)' : 'var(--sans)', fontSize: 14, outline: 'none' }}
          />
          {query && (
            <button onClick={() => onQueryChange('')} style={{ flex: 'none', color: 'var(--ink-soft)' }}>
              <Icon.close style={{ width: 16, height: 16 }} />
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

// matches a product against free text across name, family, blurb, and every fragrance note (EN+AR)
function matchesQuery(p, q) {
  const needle = q.trim().toLowerCase();
  if (!needle) return true;
  const haystack = [
    p.name, p.ar, p.family, p.familyAr, p.blurb, p.blurbAr,
    ...p.notes.top.flat(), ...p.notes.heart.flat(), ...p.notes.base.flat(),
  ];
  return haystack.some((h) => h && h.toLowerCase().includes(needle));
}

// same category logic Shop uses (badge-based for "limited", everything for "gift")
function matchesCategory(p, catId) {
  if (catId === 'limited') return p.badge === 'limited';
  if (catId === 'gift') return true;
  return p.cat === catId;
}

function Search({ t, lang, go, onOpen, wish, toggleWish }) {
  const [query, setQuery] = useState('');
  const [activeCat, setActiveCat] = useState(null); // category id, set only by tapping a "Browse by" chip
  const trimmed = query.trim();
  const isActive = Boolean(trimmed || activeCat);

  // The bilingual substring-matching logic (matchesQuery/matchesCategory)
  // is unchanged — only its data source moved from the mock AZ.PRODUCTS
  // array to Supabase. The catalog is small enough that fetching it once
  // and matching in the browser is simpler and behaviorally identical to
  // before; see docs/phase2-frontend-catalog-integration.md for why this
  // wasn't pushed into a server-side SQL search instead.
  const [allProducts, setAllProducts] = useState([]);
  const [status, setStatus] = useState('loading'); // 'loading' | 'ready' | 'error'
  const load = useCallback(() => {
    setStatus('loading');
    AZCatalog.fetchAllProducts()
      .then((p) => { setAllProducts(p); setStatus('ready'); })
      .catch((e) => { console.error('Search: failed to load catalog data', e); setStatus('error'); });
  }, []);
  useEffect(load, [load]);

  const results = activeCat
    ? allProducts.filter((p) => matchesCategory(p, activeCat))
    : allProducts.filter((p) => matchesQuery(p, query));

  const activeCatEntry = activeCat && AZ.CATEGORIES.find(([id]) => id === activeCat);
  const activeLabel = activeCatEntry ? (lang === 'ar' ? activeCatEntry[2] : activeCatEntry[1]) : query;

  const setTextQuery = (v) => { setQuery(v); setActiveCat(null); };
  const pickCategory = (id) => { setActiveCat(id); setQuery(''); };

  return (
    <div>
      <SearchBar t={t} lang={lang} query={activeCat ? activeLabel : query} onQueryChange={setTextQuery} onBack={() => go('home')} />

      {status === 'loading' && <LoadingState lang={lang} />}
      {status === 'error' && <ErrorState lang={lang} onRetry={load} />}

      {status === 'ready' && !isActive && (
        <section style={{ padding: '28px 22px 8px' }}>
          <div className="kicker solo">{lang === 'ar' ? 'تصفّح حسب' : 'Browse by'}</div>
          <div className="hscroll" style={{ marginTop: 14 }}>
            {AZ.CATEGORIES.filter(([id]) => id !== 'all').map(([id, en, ar]) => (
              <button key={id} className="chip" onClick={() => pickCategory(id)}>{lang === 'ar' ? ar : en}</button>
            ))}
          </div>
          <p className="body" style={{ marginTop: 22 }}>{t.searchHint}</p>
        </section>
      )}

      {status === 'ready' && isActive && (
        <section style={{ padding: '22px 22px 0' }}>
          <span style={{ fontFamily: 'var(--sans)', fontSize: 11, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--ink-soft)' }}>
            {results.length} {t.shopCount}
          </span>
        </section>
      )}

      {status === 'ready' && isActive && results.length === 0 ? (
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16, padding: '60px 40px', textAlign: 'center' }}>
          <img src="assets/mark-black.png" alt="" style={{ width: 64, opacity: .4 }} />
          <p className="lede">{t.searchNoResults} &ldquo;{activeLabel}&rdquo;</p>
          <p className="body">{t.searchNoResultsSub}</p>
        </div>
      ) : (
        <section style={{ padding: '16px 22px 60px' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '30px 16px' }}>
            {results.map((p, i) => (
              <Reveal key={p.id} delay={(i % 2) * 60}>
                <ProductCard p={p} lang={lang} t={t} onOpen={onOpen} wished={wish.includes(p.id)} onWish={toggleWish} />
              </Reveal>
            ))}
          </div>
        </section>
      )}

      <Footer t={t} lang={lang} go={go} />
    </div>
  );
}

Object.assign(window, { Search });
