// Search results screen — match-degree sorted grid + filter sidebar
const SearchResults = ({ tags = [], setTags, onOpenRecipe, onBack, mobile = false }) => {
  const [sort, setSort] = React.useState('match');
  const [active, setActive] = React.useState({ time: null, diff: null, diet: null, cat: null });
  const [showFilter, setShowFilter] = React.useState(false);

  const results = React.useMemo(() => {
    const list = window.RECIPES.map(r => {
      const have = tags.filter(t => r.have && r.have.includes(t)).length;
      const need = (r.have || []).length;
      const m = need === 0 ? r.match : Math.round(have / Math.max(tags.length, 1) * 100);
      return { ...r, _m: tags.length === 0 ? r.match : Math.max(m, 60) };
    });
    list.sort((a, b) => {
      if (sort === 'match') return b._m - a._m;
      if (sort === 'time') return a.time - b.time;
      if (sort === 'cal') return a.cal - b.cal;
      if (sort === 'rating') return b.rating - a.rating;
      return 0;
    });
    return list;
  }, [tags, sort]);

  const W = mobile ? 'm' : 'd';

  return (
    <div className={`page page--${W}`}>
      <Header active="recipes" mobile={mobile} />

      <section className={`srhd srhd--${W}`}>
        <div className="bcrumb">
          <a onClick={onBack}>首頁</a> / <a>食材搜索</a> / <span>{tags.join(' + ') || '所有食譜'}</span>
        </div>
        <Eyebrow>搜索結果</Eyebrow>
        <h1 className="srhd__h">
          找到 <em>{results.length}</em> 道用<br />
          <span className="srhd__tags">
            {tags.map(t => (
              <span key={t} className="tag tag--lg">
                {t}<button onClick={() => setTags(tags.filter(x=>x!==t))}><Icon name="x" size={12} stroke={2}/></button>
              </span>
            ))}
            <button className="tag tag--add" onClick={() => setTags([...tags])}><Icon name="plus" size={12} stroke={2}/> 加食材</button>
          </span>
          能做的料理
        </h1>
        <div className="srhd__bar">
          <div className="srhd__sort">
            <span className="srhd__lab">排序</span>
            {[['match','匹配度'],['time','烹飪時間'],['cal','卡路里'],['rating','評分']].map(([k,l]) => (
              <button key={k} className={`pill ${sort===k?'is-on':''}`} onClick={()=>setSort(k)}>{l}</button>
            ))}
          </div>
          {mobile && (
            <button className="btn btn--ghost btn--sm" onClick={()=>setShowFilter(!showFilter)}>
              <Icon name="filter" size={14}/> 篩選
            </button>
          )}
        </div>
      </section>

      <div className={`sr sr--${W}`}>
        {!mobile && (
          <aside className="filt">
            <FilterGroup label="烹飪時間" opts={['15 分內','30 分內','1 小時內','1 小時以上']} k="time" active={active.time} set={v=>setActive({...active, time:v})}/>
            <FilterGroup label="難度" opts={['新手','家常','進階']} k="diff" active={active.diff} set={v=>setActive({...active, diff:v})}/>
            <FilterGroup label="菜系" opts={['中餐','日料','西餐','東南亞','健康輕食']} k="cat" active={active.cat} set={v=>setActive({...active, cat:v})}/>
            <FilterGroup label="飲食限制" opts={['素食','純素','無麩質','低卡','高蛋白','糖尿病友善']} k="diet" active={active.diet} set={v=>setActive({...active, diet:v})}/>
            <div className="filt__hint">
              <Icon name="sparkles" size={14}/>
              <p>找不到 100% 匹配？我們自動展開到 80% 並提示替代食材。</p>
            </div>
          </aside>
        )}
        <div className="sr__main">
          <div className={`grid grid--res grid--${W}`}>
            {results.map(r => <RecipeCard key={r.slug} r={{...r, match: r._m}} showMatch onClick={()=>onOpenRecipe && onOpenRecipe(r)}/>)}
          </div>
          <div className="sr__more"><button className="btn btn--ghost">載入更多</button></div>
        </div>
      </div>
      <Footer />
    </div>
  );
};

const FilterGroup = ({ label, opts, active, set }) => (
  <div className="fg">
    <h4 className="fg__h">{label}</h4>
    {opts.map(o => (
      <label key={o} className={`fg__o ${active===o?'is-on':''}`}>
        <input type="checkbox" checked={active===o} onChange={()=>set(active===o?null:o)}/>
        <span className="fg__box"></span>
        <span>{o}</span>
      </label>
    ))}
  </div>
);

window.SearchResults = SearchResults;
