/* ============================================================
   IJMA AI — browse / index page
   ============================================================ */
function BrowseRow({ ruling, onNav }) {
  const r = ruling;
  const stances = {};
  r.positions.forEach(p => { stances[p.stance] = (stances[p.stance] || 0) + 1; });
  const groupCount = Object.keys(stances).length;
  return (
    <button className="browse-row" onClick={() => onNav('#/ruling/' + r.slug)}>
      <div style={{ flex: '1 1 auto', minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '.7em', marginBottom: '.35rem', flexWrap: 'wrap' }}>
          <span className="eyebrow">{r.topicLabel}</span>
          <span style={{ fontFamily: 'var(--mono)', fontSize: '11px', color: 'var(--ink-4)' }}><Ar>{r.arabic}</Ar> {r.translit}</span>
        </div>
        <div style={{ fontSize: '20px', fontWeight: 600, lineHeight: 1.2, marginBottom: '.5rem' }}>{r.question}</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '.9em', flexWrap: 'wrap' }}>
          <span style={{ display: 'flex', gap: '.35em' }}>
            {r.positions.map(p => <span key={p.school} title={D.schools[p.school].name} className="dot" style={{ width: 9, height: 9, borderRadius: '50%', background: D.schools[p.school].color, display: 'inline-block' }} />)}
          </span>
          <span style={{ fontFamily: 'var(--mono)', fontSize: '11px', color: 'var(--ink-3)' }}>
            {groupCount === 1 ? 'unanimous' : `${groupCount} distinct positions`}
          </span>
        </div>
      </div>
      <div className="browse-row-meta">
        {r.diachronic && <span className="rowtag"><Icon name="clock" size={12} />Shifted</span>}
        {r.divergent && <span className="rowtag"><Icon name="diverge" size={12} />Diverges</span>}
        <span style={{ color: 'var(--ink-4)' }}><Icon name="arrow" size={16} /></span>
      </div>
    </button>
  );
}

function BrowsePage({ onNav }) {
  const [topic, setTopic] = useState('all');
  const [book, setBook] = useState('all');   // al-Ijmāʿ kitāb filter (main rail)
  const [ijmaFilters, setIjmaFilters] = useState({});   // contested / prohibition / permissibility
  const ijmaToggle = k => setIjmaFilters(f => ({ ...f, [k]: !f[k] }));
  const [onlyDiverge, setOnlyDiverge] = useState(false);
  const [onlyShift, setOnlyShift] = useState(false);

  const all = Object.values(D.rulings);
  const filtered = all.filter(r =>
    (topic === 'all' || r.topic === topic) &&
    (!onlyDiverge || r.divergent) &&
    (!onlyShift || r.diachronic)
  );

  return (
    <main className="fade-in" style={{ maxWidth: 'var(--maxw)', margin: '0 auto', padding: '2.4rem clamp(1.2rem,4vw,3rem) 5rem' }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: '1.5rem', flexWrap: 'wrap', marginBottom: '1.4rem' }}>
        <div style={{ flex: '1 1 22rem', minWidth: 0 }}>
          <h1 style={{ fontSize: 'clamp(28px,3.6vw,42px)', fontWeight: 700, letterSpacing: '-0.01em', margin: '0 0 .6rem' }}>Browse every question</h1>
          <p style={{ fontSize: '16px', color: 'var(--ink-2)', maxWidth: '54ch', margin: 0 }}>
            Enter by topic, or jump to where the schools disagree and where the modern position has shifted.
          </p>
        </div>
        {/* compact quick-filters, beside the header */}
        <div className="browse-quickfilters">
          <button className={'quickfilter' + (onlyDiverge ? ' on' : '')} onClick={() => setOnlyDiverge(v => !v)} title="Show only divergent questions">
            <Icon name="diverge" size={14} /> Diverges
          </button>
          <button className={'quickfilter' + (onlyShift ? ' on' : '')} onClick={() => setOnlyShift(v => !v)} title="Show only diachronic questions">
            <Icon name="clock" size={14} /> Shifted
          </button>
        </div>
      </div>

      {/* one unified rail: al-Ijmāʿ kitāb books are the main categories,
          the comparative-ruling topics are an additional group */}
      <div className="mundhir-layout">
        <aside className="mundhir-side">
          <MundhirBookNav book={book} setBook={setBook} onNav={onNav} filters={ijmaFilters} onToggle={ijmaToggle} />

          <div className="mundhir-side-title" style={{ marginTop: '1.4rem' }}>Comparative questions</div>
          <button className={'mundhir-side-item' + (topic === 'all' ? ' active' : '')} onClick={() => setTopic('all')}>
            All compared <span className="n">{all.length}</span>
          </button>
          {D.topics.map(t => {
            const n = all.filter(r => r.topic === t.id).length;
            return (
              <button key={t.id} className={'mundhir-side-item' + (topic === t.id ? ' active' : '')} onClick={() => setTopic(topic === t.id ? 'all' : t.id)}>
                {t.label} <span className="n">{n}</span>
              </button>
            );
          })}
        </aside>

        <div className="mundhir-main">
          {/* main content: the al-Ijmāʿ corpus (driven by the book rail) */}
          <MundhirCorpus book={book} setBook={setBook} embedded filters={ijmaFilters} onToggle={ijmaToggle} />

          {/* additional: the worked, multi-school comparative questions */}
          <section style={{ marginTop: '3.5rem', borderTop: '1px solid var(--rule)', paddingTop: '2rem' }}>
            <div className="section-label" style={{ marginBottom: '.8rem' }}>
              <span className="eyebrow">Worked across the schools</span>
              <h2>Comparative questions {topic !== 'all' && `· ${D.topics.find(t => t.id === topic)?.label || ''}`}</h2>
            </div>
            <div style={{ fontFamily: 'var(--mono)', fontSize: '11.5px', color: 'var(--ink-3)', margin: '0 0 .6rem', letterSpacing: '.04em' }}>
              {filtered.length} {filtered.length === 1 ? 'question' : 'questions'}
            </div>
            <div className="browse-list">
              {filtered.map(r => <BrowseRow key={r.slug} ruling={r} onNav={onNav} />)}
              {filtered.length === 0 && <div style={{ padding: '2rem', color: 'var(--ink-3)', fontStyle: 'italic' }}>No questions match these filters.</div>}
            </div>
          </section>
        </div>
      </div>
    </main>
  );
}

Object.assign(window, { BrowsePage });
