/* ============================================================
   IJMA AI — ruling page (the heart)
   ============================================================ */
function RulingHeader({ ruling, onNav }) {
  const st = ruling.status;
  const current = st.modern || st;
  return (
    <header style={{ paddingTop: '2.2rem' }}>
      <button className="btn btn-ghost" style={{ marginBottom: '1.4rem', paddingLeft: 0 }} onClick={() => onNav('#/browse')}>
        <span style={{ display: 'inline-flex', transform: 'rotate(180deg)', marginRight: '.4em', verticalAlign: '-2px' }}><Icon name="arrow" size={14} /></span>
        All questions
      </button>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: '1em', flexWrap: 'wrap', marginBottom: '.5rem' }}>
        <span className="eyebrow">{ruling.topicLabel}</span>
        <span style={{ color: 'var(--ink-4)' }}>·</span>
        <span style={{ fontFamily: 'var(--mono)', fontSize: '12px', color: 'var(--ink-3)' }}>
          <Ar className="">{ruling.arabic}</Ar> &nbsp;{ruling.translit}
        </span>
      </div>
      <h1 style={{ fontSize: 'clamp(28px,3.4vw,42px)', lineHeight: 1.14, fontWeight: 700, margin: '0 0 3.4rem', letterSpacing: '-0.01em', maxWidth: '19ch' }}>
        {ruling.question}
      </h1>
      <p style={{ fontSize: '19px', lineHeight: 1.5, color: 'var(--ink-2)', maxWidth: '62ch', margin: '0 0 1.6rem' }}>
        {ruling.summary}
      </p>

      {/* the unmistakable consensus indicator */}
      <div className="card" style={{ display: 'flex', alignItems: 'center', gap: '1.5rem', padding: '1.1rem 1.4rem', flexWrap: 'wrap' }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: '.5rem' }}>Consensus status</div>
          <StatusBadge statusKey={st.key === 'shifted' ? 'shifted' : current.key} label={st.label} />
        </div>
        {st.key === 'shifted' && (
          <div style={{ display: 'flex', alignItems: 'center', gap: '1rem', borderLeft: '1px solid var(--rule)', paddingLeft: '1.5rem', flexWrap: 'wrap' }}>
            <div>
              <div className="eyebrow" style={{ marginBottom: '.4rem' }}>Pre-modern</div>
              <StatusBadge statusKey={st.premodern.key} label={st.premodern.label} />
            </div>
            <span style={{ color: 'var(--ink-4)' }}><Icon name="arrow" size={20} /></span>
            <div>
              <div className="eyebrow" style={{ marginBottom: '.4rem' }}>Contemporary</div>
              <StatusBadge statusKey={st.modern.key} label={st.modern.label} />
            </div>
          </div>
        )}
        <div style={{ flex: 1, minWidth: '200px', fontSize: '14px', color: 'var(--ink-2)', lineHeight: 1.45, borderLeft: '1px solid var(--rule)', paddingLeft: '1.5rem' }}>
          {current.note}
        </div>
      </div>
    </header>
  );
}

const LAYOUTS = [
  { id: 'columns', label: 'Parallel columns', hint: 'Compare side by side' },
  { id: 'shape', label: 'Grouped by position', hint: 'See agreement as a shape' },
  { id: 'matrix', label: 'Matrix', hint: 'Dense scan' },
];

function ComparisonSection({ ruling }) {
  const [layout, setLayout] = useState('columns');
  return (
    <section style={{ marginTop: '3rem' }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', flexWrap: 'wrap', gap: '1rem', marginBottom: '1.3rem' }}>
        <div className="section-label" style={{ marginBottom: 0 }}>
          <span className="eyebrow">The positions</span>
          <h2>{ruling.positions.length} schools, compared</h2>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '.5rem' }}>
          <span className="eyebrow" style={{ marginRight: '.3rem' }}>Layout</span>
          {LAYOUTS.map(l => (
            <button key={l.id} className={'btn' + (layout === l.id ? ' active' : '')} title={l.hint} onClick={() => setLayout(l.id)}>
              {l.label}
            </button>
          ))}
        </div>
      </div>
      {layout === 'columns' && <ComparisonColumns ruling={ruling} />}
      {layout === 'shape' && <ComparisonShape ruling={ruling} />}
      {layout === 'matrix' && <ComparisonMatrix ruling={ruling} />}
      <p style={{ fontFamily: 'var(--mono)', fontSize: '11.5px', color: 'var(--ink-3)', marginTop: '1rem', letterSpacing: '.02em' }}>
        Evidence is collapsed by default — open any school to read the Qur'anic verses, hadith (with grading), and reasoning method it cites.
      </p>
    </section>
  );
}

function ConsensusClaimsSection({ ruling }) {
  if (!ruling.consensusClaims || !ruling.consensusClaims.length) return null;
  return (
    <section style={{ marginTop: '3.5rem' }}>
      <div className="section-label">
        <span className="eyebrow">Claimed vs. demonstrated</span>
        <h2>Is the consensus asserted, or shown?</h2>
      </div>
      <p style={{ maxWidth: '64ch', color: 'var(--ink-2)', marginTop: 0, marginBottom: '1.5rem', fontSize: '17px' }}>
        A jurist asserting ijma is not the same object as a consensus no school contradicts. Where a claim meets a
        dissent on record, the two are shown together — never blurred into one badge.
      </p>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(320px,1fr))', gap: '1.2rem' }}>
        {ruling.consensusClaims.map((c, i) => <ClaimSlip key={i} claim={c} />)}
      </div>
    </section>
  );
}

function RelatedSection({ ruling, onNav }) {
  if (!ruling.relatedSlugs || !ruling.relatedSlugs.length) return null;
  return (
    <section style={{ marginTop: '3.5rem', borderTop: '1px solid var(--rule)', paddingTop: '1.8rem' }}>
      <div className="eyebrow" style={{ marginBottom: '1rem' }}>Related questions</div>
      <div style={{ display: 'flex', gap: '1rem', flexWrap: 'wrap' }}>
        {ruling.relatedSlugs.map(slug => {
          const r = D.rulings[slug]; if (!r) return null;
          return (
            <button key={slug} className="card" onClick={() => onNav('#/ruling/' + slug)}
              style={{ textAlign: 'left', padding: '1rem 1.2rem', cursor: 'pointer', flex: '1 1 240px', background: 'var(--card)' }}>
              <div className="eyebrow" style={{ marginBottom: '.4rem' }}>{r.topicLabel}</div>
              <div style={{ fontSize: '17px', fontWeight: 600, lineHeight: 1.25 }}>{r.question}</div>
              {r.diachronic && <div style={{ marginTop: '.6rem', display: 'inline-flex', alignItems: 'center', gap: '.4em', fontFamily: 'var(--label)', fontSize: '11.5px', letterSpacing: '.04em', textTransform: 'lowercase', color: 'var(--ink-3)' }}><Icon name="clock" size={12} />Position shifted</div>}
            </button>
          );
        })}
      </div>
    </section>
  );
}

/* the Method nav lands on the slavery exemplar — keep a route into the
   al-Ijmāʿ source layer from here since it left the top nav */
function IjmaSourceLink({ onNav }) {
  const M = window.IJMA_MUNDHIR;
  if (!M) return null;
  return (
    <section style={{ marginTop: '3.5rem', borderTop: '1px solid var(--rule)', paddingTop: '1.8rem' }}>
      <div className="eyebrow" style={{ marginBottom: '1rem' }}>The source layer</div>
      <p style={{ fontSize: '16px', color: 'var(--ink-2)', maxWidth: '70ch', margin: '0 0 1rem', lineHeight: 1.55 }}>
        {M.source.note}
      </p>
      <div style={{ fontFamily: 'var(--mono)', fontSize: '12px', color: 'var(--ink-3)', margin: '0 0 1.2rem' }}>
        <strong style={{ color: 'var(--ink-2)' }}>{M.source.author}</strong> · {M.source.death} · <Ar>{M.source.ar}</Ar>
      </div>
      <button className="card" onClick={() => onNav('#/ijma')}
        style={{ textAlign: 'left', padding: '1rem 1.2rem', cursor: 'pointer', background: 'var(--card)', display: 'flex', alignItems: 'center', gap: '1rem', width: '100%' }}>
        <div>
          <div style={{ fontSize: '17px', fontWeight: 600, lineHeight: 1.25 }}>Browse al-Ijmāʿ of Ibn al-Mundhir</div>
          <div style={{ fontSize: '13.5px', color: 'var(--ink-3)', marginTop: '.25rem' }}>
            The catalogue of claimed consensus this method is tested against — {M.books.reduce((n, b) => n + b.positions.length, 0)} reported positions, with the dissents on record.
          </div>
        </div>
        <span style={{ marginLeft: 'auto', color: 'var(--ink-4)' }}><Icon name="arrow" size={18} /></span>
      </button>
    </section>
  );
}

function RulingPage({ slug, onNav }) {
  const ruling = D.rulings[slug] || D.rulings.slavery;
  useEffect(() => { window.scrollTo(0, 0); }, [slug]);
  return (
    <main className="page-pad fade-in" key={slug} style={{ maxWidth: 'var(--maxw)', margin: '0 auto', padding: '0 clamp(1.2rem,4vw,3rem) 5rem' }}>
      <RulingHeader ruling={ruling} onNav={onNav} />
      <ComparisonSection ruling={ruling} />
      <ConsensusClaimsSection ruling={ruling} />
      {ruling.diachronic && <DiachronicView ruling={ruling} />}
      <RelatedSection ruling={ruling} onNav={onNav} />
      {slug === 'slavery' && <IjmaSourceLink onNav={onNav} />}
    </main>
  );
}

Object.assign(window, { RulingPage });
