/* ============================================================
   IJMA AI — shared components (exported to window)
   ============================================================ */
const { useState, useEffect, useRef, useMemo } = React;
const D = window.IJMA;

/* ---- inline icons ---- */
function Icon({ name, size = 16, className = '' }) {
  const p = {
    chevron: <path d="M6 4l5 5-5 5" />,
    search:  <><circle cx="7.5" cy="7.5" r="5.2" /><path d="M11.5 11.5L16 16" /></>,
    arrow:   <><path d="M3 9h12" /><path d="M11 5l4 4-4 4" /></>,
    check:   <path d="M3 9l4 4 8-9" />,
    cross:   <><path d="M4 4l10 10" /><path d="M14 4L4 14" /></>,
    book:    <><path d="M3 3.5h5a2 2 0 012 2V15a2 2 0 00-2-2H3z" /><path d="M15 3.5h-5a2 2 0 00-2 2V15a2 2 0 012-2h5z" /></>,
    scale:   <><path d="M9 2v14" /><path d="M3 16h12" /><path d="M9 4l-5 1 2.5 5a2.5 2.5 0 01-5 0L4 5" /><path d="M9 4l5 1-2.5 5a2.5 2.5 0 005 0L14 5" /></>,
    filter:  <><path d="M2 4h14" /><path d="M4 9h10" /><path d="M7 14h4" /></>,
    diverge: <><path d="M9 2v5" /><path d="M9 7L4 15" /><path d="M9 7l5 8" /></>,
    clock:   <><circle cx="9" cy="9" r="6.5" /><path d="M9 5v4l3 2" /></>,
    ban:     <><circle cx="9" cy="9" r="6.5" /><path d="M4.4 4.4l9.2 9.2" /></>,
    allow:   <><circle cx="9" cy="9" r="6.5" /><path d="M5.7 9.2l2.3 2.3 4.3-4.8" /></>,
  }[name];
  return (
    <svg width={size} height={size} viewBox="0 0 18 18" fill="none"
      stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"
      className={className} aria-hidden="true">{p}</svg>
  );
}

/* ---- brand glyph: two converging/diverging strokes meeting at a node ---- */
function Brandmark({ size = 30 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" fill="none" aria-hidden="true">
      <circle cx="16" cy="16" r="15" stroke="var(--ink)" strokeWidth="1.2" opacity=".25" />
      <path d="M16 6 L9 26 M16 6 L23 26 M16 6 L16 26 M16 6 L11.5 26 M16 6 L20.5 26"
        stroke="var(--ink)" strokeWidth="1.1" strokeLinecap="round" opacity=".55" />
      <circle cx="16" cy="6" r="2.6" fill="var(--link)" />
    </svg>
  );
}

/* ---- arabic inline ---- */
function Ar({ children, className = '' }) {
  return <span className={'ar-inline ' + className} lang="ar">{children}</span>;
}

/* ---- school primitives ---- */
function schoolStyle(id) { return { '--sc': D.schools[id].color }; }
function SchoolDot({ id }) { return <span className="school-chip" style={schoolStyle(id)}><span className="dot" /></span>; }
function SchoolChip({ id, solid = false }) {
  const s = D.schools[id];
  return (
    <span className={'school-chip' + (solid ? ' solid' : '')} style={schoolStyle(id)}>
      <span className="dot" />{s.name}
    </span>
  );
}

/* ---- stance label ---- */
function StanceLabel({ stanceKey }) {
  const s = D.stances[stanceKey];
  if (!s) return null;
  return <span className={'stance ' + s.tone}>{s.label}</span>;
}

/* ---- consensus status badge ---- */
const STATUS_GLYPH = {
  ijma: 'check', majority: 'scale', ikhtilaf: 'diverge', shifted: 'clock', na: 'cross',
};
function StatusBadge({ statusKey, label }) {
  const cls = { ijma: 'status-ijma', majority: 'status-majority', ikhtilaf: 'status-ikhtilaf', shifted: 'status-shifted', na: 'status-na' }[statusKey] || 'status-na';
  return (
    <span className={'status-badge ' + cls}>
      <Icon name={STATUS_GLYPH[statusKey] || 'diverge'} size={14} className="glyph" />
      {label}
    </span>
  );
}

/* ---- source-type tag ---- */
function SourceTag({ kind }) {
  const m = D.SRC[kind] || D.SRC.reasoning;
  return <span className={'src-tag ' + m.cls}><span className="tick" />{m.label}</span>;
}
function Grading({ grade }) {
  if (!grade) return null;
  return <span className={'grading ' + grade}>{grade}</span>;
}
function SingleSource() {
  return <span className="single-mark"><Icon name="cross" size={9} />Single source</span>;
}

/* ---- one evidence item ---- */
function EvidenceItem({ ev }) {
  return (
    <div className="ev-item">
      <div className="ev-head">
        <SourceTag kind={ev.src} />
        {ev.ref && <span className="ev-ref">{ev.ref}</span>}
        {ev.title && <span className="ev-work">{ev.title}</span>}
        {ev.author && <span className="ev-author">— {ev.author}</span>}
        {ev.grading && <Grading grade={ev.grading} />}
        {ev.single && <SingleSource />}
      </div>
      {ev.method && <div className="ev-method">{ev.method}</div>}
      {ev.text && <div className="ev-text">{ev.text}</div>}
      {ev.note && !ev.text && <div className="ev-text">{ev.note}</div>}
    </div>
  );
}

/* ---- collapsible evidence block ---- */
function Evidence({ items, defaultOpen = false, label }) {
  if (!items || !items.length) return null;
  return (
    <details className="evidence" open={defaultOpen}>
      <summary>
        <Icon name="chevron" size={12} className="chev" />
        {label || `Evidence cited`} · {items.length}
      </summary>
      <div>{items.map((ev, i) => <EvidenceItem key={i} ev={ev} />)}</div>
    </details>
  );
}

/* ---- claim slip (claimed vs demonstrated) ---- */
function ClaimSlip({ claim }) {
  const isClaimed = claim.status === 'claimed';
  return (
    <div className={'claim-slip ' + (isClaimed ? 'is-claimed' : 'is-demonstrated')}>
      <span className={'claim-stamp ' + (isClaimed ? 'claimed' : 'demonstrated')}>
        {isClaimed ? 'Claimed' : 'Demonstrated'}
      </span>
      <div className="eyebrow" style={{ marginBottom: '.5rem' }}>{claim.era} · ijma claim</div>
      <div style={{ fontSize: '18px', lineHeight: 1.4, fontWeight: 500, maxWidth: '46ch' }}>
        “{claim.claim}”
      </div>
      <div style={{ marginTop: '.6rem', fontSize: '13.5px', color: 'var(--ink-3)' }}>
        Asserted by <strong style={{ color: 'var(--ink-2)', fontWeight: 600 }}>{claim.claimant}</strong>
        {claim.work && <> · <span className="ev-work">{claim.work}</span></>}
      </div>
      {claim.contestedBy && claim.contestedBy.length > 0 && (
        <div className="claim-contest">
          <span className="x"><Icon name="cross" size={13} /></span>
          <div>
            <div className="eyebrow" style={{ color: '#9a3d3d', marginBottom: '.35rem' }}>Dissent on record — claim not demonstrated</div>
            <div style={{ display: 'flex', gap: '.5em', flexWrap: 'wrap', marginBottom: '.4rem' }}>
              {claim.contestedBy.map(id => <SchoolChip key={id} id={id} solid />)}
            </div>
            <div style={{ fontSize: '14px', color: 'var(--ink-2)', lineHeight: 1.5 }}>{claim.note}</div>
          </div>
        </div>
      )}
      {(!claim.contestedBy || !claim.contestedBy.length) && claim.note && (
        <div style={{ marginTop: '.8rem', paddingTop: '.7rem', borderTop: '1px solid var(--rule)', fontSize: '14px', color: 'var(--ink-2)', lineHeight: 1.5 }}>
          {claim.note}
        </div>
      )}
    </div>
  );
}

Object.assign(window, {
  Icon, Brandmark, Ar, schoolStyle, SchoolDot, SchoolChip,
  StanceLabel, StatusBadge, SourceTag, Grading, SingleSource,
  EvidenceItem, Evidence, ClaimSlip,
});
