/** Client-side search and chip filtering for the article and recipe listings. */
export function initFilters() {
  const root = document.querySelector<HTMLElement>('[data-filters]');
  const list = document.querySelector<HTMLElement>('[data-list]');
  if (!root || !list) return;
  const input = root.querySelector<HTMLInputElement>('[data-search-input]');
  const empty = document.querySelector<HTMLElement>('[data-empty]');
  const groups = new Map<string, string>(); // filter attribute -> selected value

  const normalize = (s: string) => s.toLowerCase().replace(/["'״׳]/g, '').trim();

  const apply = () => {
    const q = normalize(input?.value ?? '');
    let visible = 0;
    list.querySelectorAll<HTMLElement>(':scope > li').forEach((li) => {
      const card = li.firstElementChild as HTMLElement;
      const text = normalize(card.dataset.search ?? '');
      let show = !q || q.split(/\s+/).every((word) => text.includes(word));
      for (const [attr, value] of groups) {
        if (value && !(card.dataset[attr] ?? '').split('|').includes(value)) show = false;
      }
      li.hidden = !show;
      if (show) visible++;
    });
    if (empty) empty.hidden = visible > 0;
  };

  input?.addEventListener('input', apply);
  root.querySelectorAll<HTMLButtonElement>('button[data-tag], button[data-spice]').forEach((btn) => {
    const attr = btn.dataset.spice !== undefined ? 'spices' : 'tags';
    const value = btn.dataset.spice ?? btn.dataset.tag ?? '';
    btn.addEventListener('click', () => {
      groups.set(attr, value);
      btn.parentElement!.querySelectorAll('button').forEach((b) => b.setAttribute('aria-pressed', String(b === btn)));
      apply();
    });
  });

  const fromUrl = new URLSearchParams(location.search).get('spice');
  if (fromUrl) root.querySelector<HTMLButtonElement>(`button[data-spice="${CSS.escape(fromUrl)}"]`)?.click();
}
