/* ============================================================
   IJMA AI — Ibn al-Mundhir's al-Ijmāʿ browser
   The source layer of *claimed* consensus: 700+ positions Ibn
   al-Mundhir reports as ijmāʿ, with the lone dissenters he names.
   ============================================================ */
function MundhirRow({ p }) {
  const kind = ruleKind(p);
  return (
    <div className={'mundhir-row' + (p.dissent ? ' has-dissent' : '')}>
      <span className="mundhir-num">{p.n}</span>
      <div className="mundhir-body">
        <div className="mundhir-en">
          {kind && (
            <span className={'rule-mark ' + kind} title={kind === 'prohibit' ? 'Consensus on prohibition' : 'Consensus on permissibility'}>
              <Icon name={kind === 'prohibit' ? 'ban' : 'allow'} size={13} />
            </span>
          )}
          {p.en}
        </div>
        <div className="mundhir-ar"><Ar>{p.ar}</Ar></div>
        {p.dissent && (
          <div className="mundhir-dissent">
            <span className="x"><Icon name="cross" size={11} /></span>
            <span><strong>Dissent recorded</strong> — {p.dissent}</span>
          </div>
        )}
      </div>
    </div>
  );
}

function FaqItem({ item, open, onToggle }) {
  return (
    <div className={'faq-item' + (open ? ' open' : '')}>
      <button className="faq-q" onClick={onToggle} aria-expanded={open}>
        <span className="faq-cat">{item.cat}</span>
        <span className="faq-qtext">{item.q}</span>
        <span className="faq-chev"><Icon name="chevron" size={13} /></span>
      </button>
      {open && (
        <div className="faq-a">
          {item.ar && <div className="faq-ar"><Ar>{item.ar}</Ar></div>}
          <p>{item.a}</p>
        </div>
      )}
    </div>
  );
}

function MundhirFaqPage({ onNav }) {
  const M = window.IJMA_MUNDHIR;
  const faq = M.faq || [];
  const [openIdx, setOpenIdx] = useState(null);
  const [cat, setCat] = useState('all');
  useEffect(() => { window.scrollTo(0, 0); }, []);
  const cats = useMemo(() => ['all', ...Array.from(new Set(faq.map(f => f.cat)))], [faq]);
  const shown = faq.map((f, i) => ({ f, i })).filter(({ f }) => cat === 'all' || f.cat === cat);
  return (
    <main className="fade-in" style={{ maxWidth: 'var(--maxw)', margin: '0 auto', padding: '2.4rem clamp(1.2rem,4vw,3rem) 5rem' }}>
      <button className="btn btn-ghost" style={{ marginBottom: '1.4rem', paddingLeft: 0 }} onClick={() => onNav('#/ijma')}>
        <span style={{ display: 'inline-flex', transform: 'rotate(180deg)', marginRight: '.4em', verticalAlign: '-2px' }}><Icon name="arrow" size={14} /></span>
        al-Ijmāʿ
      </button>
      <div className="eyebrow" style={{ marginBottom: '.6rem' }}>The theory behind the corpus</div>
      <h1 style={{ fontSize: 'clamp(28px,3.4vw,42px)', fontWeight: 700, letterSpacing: '-0.01em', margin: '0 0 1rem', maxWidth: '22ch' }}>
        What is ijmāʿ? — a short FAQ
      </h1>
      <p style={{ maxWidth: '66ch', color: 'var(--ink-2)', margin: '0 0 1.6rem', fontSize: '18px', lineHeight: 1.55 }}>
        Drawn from the book's own theoretical introduction (<Ar>مبحث الإجماع</Ar>) — what consensus means, whose
        agreement counts, how binding it is, and why a claimed ijmāʿ is not always a demonstrated one.
      </p>
      <div className="faq-cats">
        {cats.map(c => (
          <button key={c} className={'faq-cat-btn' + (cat === c ? ' active' : '')} onClick={() => { setCat(c); setOpenIdx(null); }}>
            {c === 'all' ? 'All' : c}
          </button>
        ))}
      </div>
      <div className="faq-list">
        {shown.map(({ f, i }) => (
          <FaqItem key={i} item={f} open={openIdx === i} onToggle={() => setOpenIdx(openIdx === i ? null : i)} />
        ))}
      </div>
      <div style={{ marginTop: '2.4rem', borderTop: '1px solid var(--rule)', paddingTop: '1.6rem' }}>
        <button className="card" onClick={() => onNav('#/ijma')}
          style={{ textAlign: 'left', padding: '1rem 1.2rem', cursor: 'pointer', background: 'var(--card)' }}>
          <div className="eyebrow" style={{ marginBottom: '.4rem' }}>Continue to the source</div>
          <div style={{ fontSize: '17px', fontWeight: 600 }}>al-Ijmāʿ of Ibn al-Mundhir — {M.books.reduce((n, b) => n + b.positions.length, 0)} reported positions</div>
        </button>
      </div>
    </main>
  );
}

/* Sidebar list of kitāb categories — shared by the standalone al-Ijmāʿ page
   and the unified Browse rail. */
function MundhirBookNav({ book, setBook, onNav, filters, onToggle }) {
  const M = window.IJMA_MUNDHIR;
  const hasFaq = onNav && M.faq && M.faq.length > 0;
  const F = filters || {};
  return (
    <>
      {onToggle && (
        <>
          <div className="mundhir-side-title">Filter</div>
          <button className={'mundhir-side-item flt' + (F.dissent ? ' active' : '')} onClick={() => onToggle('dissent')}>
            <span className="flt-ic"><Icon name="diverge" size={13} /></span> Contested only
          </button>
          <button className={'mundhir-side-item flt' + (F.prohibit ? ' active' : '')} onClick={() => onToggle('prohibit')}>
            <span className="flt-ic prohibit"><Icon name="ban" size={13} /></span> On prohibition
          </button>
          <button className={'mundhir-side-item flt' + (F.permit ? ' active' : '')} onClick={() => onToggle('permit')}>
            <span className="flt-ic permit"><Icon name="allow" size={13} /></span> On permissibility
          </button>
        </>
      )}

      <div className="mundhir-side-title" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: onToggle ? '1.4rem' : 0 }}>
        <span>al-Ijmāʿ · books</span>
        {hasFaq && <button className="mundhir-faq-btn" onClick={() => onNav('#/ijma/faq')} title="What is ijmāʿ? — a short FAQ">FAQ</button>}
      </div>
      <button className={'mundhir-side-item' + (book === 'all' ? ' active' : '')} onClick={() => setBook('all')}>
        All books <span className="n">{M.books.reduce((n, b) => n + b.positions.length, 0)}</span>
      </button>
      {M.books.map(b => (
        <button key={b.id} className={'mundhir-side-item' + (book === b.id ? ' active' : '')} onClick={() => setBook(book === b.id ? 'all' : b.id)}>
          {b.en} <span className="n">{b.positions.length}</span>
        </button>
      ))}
    </>
  );
}

/* classify a reported consensus as one on prohibition vs permissibility by its
   wording — check the prohibition patterns first so negations ("not permitted")
   aren't misread as permission */
const _PROHIBIT = /\b(forbidden|forbids?|prohibit\w*|unlawful|impermissible|illicit|invalid\w*|nullif\w*|void|annul\w*|not\s+(?:permitted|allowed|lawful|valid)|may\s+not|must\s+not)\b/i;
const _PERMIT = /\b(permissible|permitted|lawful|allowed|licit|valid)\b/i;
function ruleKind(p) {
  const t = p.en || '';
  if (_PROHIBIT.test(t)) return 'prohibit';
  if (_PERMIT.test(t)) return 'permit';
  return null;
}

/* The corpus browser — book filter, dissent + prohibition/permissibility
   toggles, position lists. `embedded` mode drops the built-in sidebar/layout
   and takes book state from the parent (used by the unified Browse rail). */
function MundhirCorpus({ book: extBook, setBook: extSetBook, embedded, onNav, filters: extFilters, onToggle: extToggle }) {
  const M = window.IJMA_MUNDHIR;
  const [internalBook, setInternalBook] = useState('all');
  const [internalFilters, setInternalFilters] = useState({});
  const book = embedded ? extBook : internalBook;
  const setBook = embedded ? extSetBook : setInternalBook;
  const F = embedded ? (extFilters || {}) : internalFilters;
  const onToggle = embedded ? extToggle : (k => setInternalFilters(f => ({ ...f, [k]: !f[k] })));

  const match = p =>
    (!F.dissent || p.dissent) &&
    (!(F.prohibit || F.permit)
      || (F.prohibit && ruleKind(p) === 'prohibit')
      || (F.permit && ruleKind(p) === 'permit'));

  const books = M.books
    .filter(b => book === 'all' || b.id === book)
    .map(b => ({ ...b, shown: b.positions.filter(match) }))
    .filter(b => b.shown.length > 0);

  const main = (
      <div className="mundhir-main">
        {books.map(b => (
          <section key={b.id} className="mundhir-book">
            <div className="mundhir-book-head">
              <h2><Ar>{b.ar}</Ar> · {b.en}</h2>
              <span className="mundhir-book-count">{b.shown.length}{b.shown.length !== b.positions.length ? ` / ${b.positions.length}` : ''}</span>
            </div>
            <div className="mundhir-list">
              {b.shown.map(p => <MundhirRow key={p.n} p={p} />)}
            </div>
          </section>
        ))}
        {books.length === 0 && <div style={{ padding: '2rem', color: 'var(--ink-3)', fontStyle: 'italic' }}>No positions match these filters.</div>}

        <p style={{ fontFamily: 'var(--mono)', fontSize: '11px', color: 'var(--ink-4)', marginTop: '2.5rem', maxWidth: '74ch', lineHeight: 1.6 }}>
          Extracted from the printed text in classical book order; numbering follows the edition's sequence. Arabic is a
          concise gist of each masʾala, not the full sentence. A small number of items whose source numbers were corrupt
          are kept in running order — verify any single position against a clean edition before relying on it.
        </p>
      </div>
  );
  if (embedded) return main;
  return (
    <div className="mundhir-layout">
      <aside className="mundhir-side"><MundhirBookNav book={book} setBook={setBook} onNav={onNav} filters={F} onToggle={onToggle} /></aside>
      {main}
    </div>
  );
}

function MundhirPage({ onNav }) {
  const M = window.IJMA_MUNDHIR;
  const allPositions = useMemo(() => M.books.reduce((n, b) => n + b.positions.length, 0), [M]);
  const allDissents = useMemo(() => M.books.reduce((n, b) => n + b.positions.filter(p => p.dissent).length, 0), [M]);

  return (
    <main className="fade-in" style={{ maxWidth: 'var(--maxw)', margin: '0 auto', padding: '2.4rem clamp(1.2rem,4vw,3rem) 5rem' }}>
      <div className="eyebrow" style={{ marginBottom: '.6rem' }}>The source layer · claimed consensus</div>
      <h1 style={{ fontSize: 'clamp(28px,3.4vw,42px)', fontWeight: 700, letterSpacing: '-0.01em', margin: '0 0 1rem', maxWidth: '24ch' }}>
        al-Ijmāʿ of Ibn al-Mundhir
      </h1>
      <p style={{ fontSize: '18px', color: 'var(--ink-2)', maxWidth: '66ch', margin: '0 0 1.4rem', lineHeight: 1.55 }}>
        After the Qurʾan and the Sunna, consensus (<Ar>إجماع</Ar>) is the third source of law — yet a consensus a
        jurist <em>asserts</em> is not the same object as one no school is known to contradict. Each entry below is a
        position reported as the agreement of the people of knowledge; where a lone dissenter is named
        (<Ar>وانفرد فلان</Ar>), claim and dissent stand together — the precise point where a claimed ijmāʿ meets a
        dissent on record.
      </p>

      {/* stat cards */}
      <div style={{ display: 'flex', gap: '1rem', flexWrap: 'wrap', marginBottom: '1.6rem' }}>
        <div className="card" style={{ padding: '.9rem 1.2rem' }}>
          <div style={{ fontFamily: 'var(--mono)', fontSize: '26px', color: 'var(--ink)' }}>{allPositions}</div>
          <div className="eyebrow">positions of claimed ijmāʿ</div>
        </div>
        <div className="card" style={{ padding: '.9rem 1.2rem' }}>
          <div style={{ fontFamily: 'var(--mono)', fontSize: '26px', color: '#9a3d3d' }}>{allDissents}</div>
          <div className="eyebrow">with a dissent on record</div>
        </div>
        <div className="card" style={{ padding: '.9rem 1.2rem' }}>
          <div style={{ fontFamily: 'var(--mono)', fontSize: '26px', color: 'var(--ink)' }}>{M.books.length}</div>
          <div className="eyebrow">books (kitāb)</div>
        </div>
      </div>

      {/* the positions */}
      <div className="section-label" style={{ marginTop: '2.6rem', marginBottom: '1rem' }}>
        <span className="eyebrow">The corpus</span>
        <h2>The {allPositions} reported positions</h2>
      </div>

      <MundhirCorpus onNav={onNav} />
    </main>
  );
}

Object.assign(window, { MundhirPage, MundhirFaqPage, MundhirCorpus });
