/* ===========================================================
   راویار — Browse & advanced search
   =========================================================== */
function FacetGroup({ title, items, active, onToggle, render }) {
  return (
    <div style={{ marginBottom: 22 }}>
      <div className="row between" style={{ marginBottom: 12 }}>
        <b style={{ fontSize: 14.5 }}>{title}</b>
      </div>
      <div className="col gap-1">
        {items.map((it, i) => {
          const id = it.id || it.fa || it;
          const on = active === id;
          return (
            <button key={i} onClick={() => onToggle(on ? null : id)}
              className="row between" style={{ padding: '9px 12px', borderRadius: 10, textAlign: 'start',
                background: on ? 'linear-gradient(135deg, rgba(212,169,76,.18), rgba(69,214,200,.1))' : 'transparent',
                border: `1px solid ${on ? 'var(--panel-line)' : 'transparent'}`, color: on ? 'var(--cream)' : 'var(--cream-2)' }}>
              {render ? render(it) : <span style={{ fontSize: 14 }}>{it.fa ? OMID.TX(it) : it}</span>}
            </button>
          );
        })}
      </div>
    </div>
  );
}

function BrowseScreen({ openStory }) {
  const [cat, setCat] = React.useState(null);
  const [era, setEra] = React.useState(null);
  const [poet, setPoet] = React.useState(null);
  const [sort, setSort] = React.useState('rating');
  const [q, setQ] = React.useState('');

  let results = OMID.STORIES.filter(s =>
    (!cat || s.cat === cat) && (!era || s.era === era) && (!poet || s.poet === poet) &&
    (!q || s.fa.includes(q) || s.en.toLowerCase().includes(q.toLowerCase()) || (s.bodyEn || '').toLowerCase().includes(q.toLowerCase())));
  results = [...results].sort((a, b) => sort === 'rating' ? b.rating - a.rating : b.mins - a.mins);

  const clearAll = () => { setCat(null); setEra(null); setPoet(null); setQ(''); };
  const activeCount = [cat, era, poet].filter(Boolean).length;

  return (
    <div style={{ maxWidth: 'var(--maxw)', margin: '0 auto', padding: '14px 22px 30px' }}>
      <div style={{ marginBottom: 24 }}>
        <div className="eyebrow">{L('کاوش پیشرفته', 'Advanced search')}</div>
        <h1 style={{ fontSize: 40, fontFamily: 'var(--display)', fontWeight: 400, marginTop: 6 }}>{L('مرور داستان‌ها', 'Browse stories')}</h1>
        <p className="muted" style={{ fontSize: 16, marginTop: 8 }}>{L('بر اساس موضوع، دوره، شاعر و قهرمان — کارت‌های دارای قاب طلایی، تصویرگری هوش مصنوعی دارند.', 'By theme, era, poet and hero — cards with a golden frame feature AI illustration.')}</p>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '270px 1fr', gap: 28, alignItems: 'start' }}>
        {/* Facets */}
        <aside className="panel" style={{ padding: 22, position: 'sticky', top: 120 }}>
          <div className="row between" style={{ marginBottom: 18 }}>
            <div className="row gap-2"><Icon name="filter" size={17} style={{ color: 'var(--gold-400)' }} /><b style={{ fontSize: 16 }}>{L('فیلترها', 'Filters')}</b></div>
            {activeCount > 0 && <button onClick={clearAll} className="muted" style={{ fontSize: 12.5 }}>{L('پاک کردن', 'Clear')}</button>}
          </div>
          <FacetGroup title={L('موضوع', 'Theme')} items={OMID.CATEGORIES} active={cat} onToggle={setCat}
            render={(c) => (<><span className="row gap-2"><span style={{ width: 22, height: 22, borderRadius: 6, display: 'grid', placeItems: 'center', background: `${c.hue}22`, color: c.hue }}><Icon name={c.icon} size={13} /></span>{OMID.TX(c)}</span><span className="fa-num muted" style={{ fontSize: 12 }}>{OMID.num(c.count)}</span></>)} />
          <FacetGroup title={L('دورهٔ تاریخی', 'Historical era')} items={OMID.ERAS} active={era} onToggle={setEra} />
          <FacetGroup title={L('شاعر / راوی', 'Poet / narrator')} items={OMID.POETS} active={poet} onToggle={setPoet}
            render={(p) => (<><span style={{ fontSize: 14 }}>{OMID.TX(p)}</span><span className="muted" style={{ fontSize: 12 }}>{OMID.TX(p, 'era')}</span></>)} />
        </aside>

        {/* Results */}
        <div>
          <div className="row between" style={{ marginBottom: 20, gap: 12, flexWrap: 'wrap' }}>
            <div className="row gap-2" style={{ flex: 1, minWidth: 280, background: 'rgba(231,222,201,.06)', border: '1px solid var(--hairline)', borderRadius: 999, padding: '11px 16px' }}>
              <Icon name="search" size={17} style={{ color: 'var(--muted)' }} />
              <input value={q} onChange={e => setQ(e.target.value)} placeholder={L('جستجو در داستان‌ها، آیات و شخصیت‌ها…', 'Search stories, verses and characters…')}
                style={{ background: 'none', border: 'none', outline: 'none', color: 'var(--cream)', fontSize: 14.5, flex: 1 }} />
            </div>
            <div className="row gap-1" style={{ background: 'rgba(231,222,201,.05)', borderRadius: 999, padding: 4, border: '1px solid var(--hairline)' }}>
              {[['rating', L('محبوب‌ترین', 'Top rated')], ['mins', L('بلندترین', 'Longest')]].map(([k, l]) => (
                <button key={k} onClick={() => setSort(k)} className="chip" style={{ border: 'none', background: sort === k ? 'linear-gradient(135deg,var(--gold-400),var(--gold-600))' : 'transparent', color: sort === k ? '#2a1d05' : 'var(--cream-2)' }}>{l}</button>
              ))}
            </div>
          </div>

          <div className="row between" style={{ marginBottom: 16 }}>
            <span className="muted fa-num" style={{ fontSize: 14 }}>{OMID.num(results.length)} {L('داستان یافت شد', 'stories found')}</span>
            <div className="row gap-1 wrap">
              {cat && <span className="chip is-active">{OMID.TX(OMID.catOf(cat))}</span>}
              {era && <span className="chip is-active">{era}</span>}
              {poet && <span className="chip is-active">{OMID.TX(OMID.poetOf(poet))}</span>}
            </div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(190px, 1fr))', gap: 18 }}>
            {results.map(s => <StoryCard key={s.id} story={s} onOpen={openStory} w="100%" h={290} />)}
          </div>
          {results.length === 0 && (
            <div className="panel center col gap-2" style={{ padding: 60, color: 'var(--muted)' }}>
              <Shamseh size={36} /><b style={{ fontSize: 17, color: 'var(--cream)' }}>{L('داستانی با این فیلترها پیدا نشد', 'No stories match these filters')}</b>
              <button onClick={clearAll} className="btn btn-ghost" style={{ marginTop: 8 }}>{L('پاک کردن فیلترها', 'Clear filters')}</button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
window.BrowseScreen = BrowseScreen;
