/* ───────────────────────────────────────────────────────────────────────────
   Surface 2 — Synthesis engine trace  (the moat, made visible)
   Shows the engine READING: intake signal → matched library entries (the real
   costochondritis entry, openable) → two tailoring passes (physiological from
   the library + personal from the six calibration instruments) → driver profile
   → conflicts preserved, never flattened. Plus a generic-AI contrast.
   ─────────────────────────────────────────────────────────────────────────── */

function EngineSurface({ persona, go }) {
  return (
    <div className="surface">
      <SurfaceHead
        eyebrow="The synthesis engine · how it reads"
        title={<>Not a prompt. <em>A traversal.</em></>}
        sub="Any well-prompted model can generate plausible health content. The engine does something a prompt can't: it traverses a tiered-evidence knowledge base that maps conditions to physiological drivers through specific mechanisms — and it carries the uncertainty forward instead of laundering it into confidence. Here is that traversal, step by step." />

      <div className="pipe">
        <Stage n="1" title="Intake signal in" tag={`${persona.intake.length} signals · ${persona.name}`}>
          <p className="stage-lede">What {persona.name} actually said, tagged to where it came from and provisionally mapped to drivers. Nothing is invented; an unchecked signal contributes nothing.</p>
          <div className="sig-list">
            {persona.intake.map((s, i) => (
              <div className="sig" key={i}>
                <span className="sig-check">✓</span>
                <div className="sig-text">{s.text}<span className="sig-src">{s.section}</span></div>
                <div className="sig-maps">{s.maps.map((c) => <DriverChip key={c} code={c} />)}</div>
              </div>
            ))}
          </div>
        </Stage>

        <PipeArrow />

        <Stage n="2" title="Library entries matched" tag={`${persona.matched.length} of 23 entries · 10 libraries`}>
          <p className="stage-lede">The signal activates entries in the Conditions Library. Each is a structured, version-controlled, tier-tagged document — not a paragraph the model wrote on the spot.</p>
          <div className="match-list">
            {persona.matched.map((m) => (
              <MatchCard key={m.id} m={m} openable={m.id === 'COND-COSTO-001'} />
            ))}
          </div>
        </Stage>

        <PipeArrow />

        <Stage n="3" title="Two tailoring passes" tag="physiological × personal">
          <p className="stage-lede">The output is tailored twice. One pass reads the biology. The other reads the person. Two individuals with identical drivers should receive genuinely different documents.</p>
          <div className="tailor-grid">
            <div className="tailor-col physio">
              <div className="tailor-head"><span className="tailor-dot" />Physiological tailoring<span className="tailor-from">from the library</span></div>
              <p className="tailor-sub">What the individual's biology says — driver activation states and mechanisms, each carrying its evidence tier.</p>
              <div className="dmap">
                {persona.drivers.map((d) => (
                  <div className="dmap-row" key={d.code}>
                    <div className="dmap-top">
                      <DriverChip code={d.code} label />
                      <span className="dmap-state" style={{ color: /lead|primary/i.test(d.state) ? window.DRIVERS[d.code].color : 'var(--bf-muted)' }}>{d.state}</span>
                      <TierChip tier={d.tier} />
                    </div>
                    <p className="dmap-mech">{d.mechanism}</p>
                  </div>
                ))}
              </div>
            </div>

            <div className="tailor-col personal">
              <div className="tailor-head"><span className="tailor-dot amber" />Personal tailoring<span className="tailor-from">from 6 calibration instruments</span></div>
              <p className="tailor-sub">How this person best understands and engages — the behavioral-science layer. Doesn't change <em>what</em> is true; changes <em>how it's delivered</em>.</p>
              <div className="instr-list">
                {window.CALIBRATION_INSTRUMENTS.map((inst) => {
                  const c = persona.calibration[inst.key];
                  return (
                    <div className="instr" key={inst.key}>
                      <div className="instr-top">
                        <span className="instr-name">{inst.name}</span>
                        <span className="instr-val">{c.value}</span>
                      </div>
                      <div className="instr-meta"><span className="instr-tool">{inst.instrument}</span><span className="instr-drives">→ {inst.drives}</span></div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        </Stage>

        <PipeArrow />

        <Stage n="4" title="Driver profile" tag="the synthesis the Story is built on">
          <p className="stage-lede">The weighted result. The two highest become lead drivers — the spine of the Health Story and the reason each lever was chosen.</p>
          <div className="profile-panel">
            <DriverProfile drivers={persona.drivers} />
            <div className="profile-lead"><b>Lead read.</b> {persona.lead}</div>
          </div>
        </Stage>

        <PipeArrow />

        <Stage n="5" title="Conflicts preserved" tag="the entry says: do not flatten" warn>
          <p className="stage-lede">This is the line a generic call crosses and the engine doesn't. Where the evidence is contested, the synthesis carries the conflict forward — because the resolution changes the plan.</p>
          <div className="conflict-list">
            {persona.conflicts.map((c, i) => <ConflictCard key={i} {...c} />)}
          </div>
        </Stage>
      </div>

      <div className="versus">
        <div className="versus-col generic">
          <div className="versus-tag">A generic AI call</div>
          <ul>
            <li>Generates plausible prose from a prompt.</li>
            <li>No provenance — you can't see which source said what.</li>
            <li>Flattens uncertainty into confident advice.</li>
            <li>Same answer regardless of who's reading it.</li>
          </ul>
        </div>
        <div className="versus-col engine">
          <div className="versus-tag">The synthesis engine</div>
          <ul>
            <li>Traverses 23 tier-tagged entries across 10 libraries.</li>
            <li>Every claim maps to a driver, a mechanism, a citation tier.</li>
            <li>Carries conflicts forward — never launders them.</li>
            <li>Tailored twice: to the biology <em>and</em> to the person.</li>
          </ul>
        </div>
      </div>

      <FlowFooter current="engine" go={go} />
    </div>
  );
}

function Stage({ n, title, tag, warn, children }) {
  return (
    <section className={'stage' + (warn ? ' stage-warn' : '')}>
      <div className="stage-head">
        <span className="stage-n">{n}</span>
        <h2 className="stage-title">{title}</h2>
        {tag && <span className="stage-tag">{tag}</span>}
      </div>
      <div className="stage-body">{children}</div>
    </section>
  );
}

function PipeArrow() {
  return <div className="pipe-arrow" aria-hidden="true">↓</div>;
}

function MatchCard({ m, openable }) {
  const [open, setOpen] = React.useState(false);
  return (
    <div className={'match' + (m.primary ? ' primary' : '') + (open ? ' open' : '')}>
      <div className="match-row" onClick={() => openable && setOpen((o) => !o)} style={{ cursor: openable ? 'pointer' : 'default' }}>
        <div className="match-id">{m.id}</div>
        <div className="match-main">
          <div className="match-name">{m.name}<span className="match-ver">v{m.version}</span>{m.primary && <span className="match-flag">primary</span>}</div>
          <div className="match-note">{m.note}</div>
        </div>
        {openable
          ? <button className="match-open">{open ? 'close ✕' : 'open entry ↓'}</button>
          : <span className="match-lock">structured entry</span>}
      </div>
      {open && openable && <LibraryEntryViewer entry={window.LIBRARY.costo} />}
    </div>
  );
}

// ── the real entry, openable inline — this is "how the engine reads" ─────────
const ENTRY_TABS = [
  ['overview', 'Overview'],
  ['feels', 'What it feels like'],
  ['drivers', 'Driver mapping'],
  ['interactions', 'Interactions'],
  ['levers', 'Lever guidance'],
  ['tracking', 'Tracking'],
  ['conflicts', 'Conflicts'],
  ['cites', 'Citations'],
];

function LibraryEntryViewer({ entry }) {
  const [tab, setTab] = React.useState('overview');
  return (
    <div className="entry">
      <div className="entry-head">
        <div className="entry-meta">
          <span className="entry-kv"><b>ID</b> {entry.id}</span>
          <span className="entry-kv"><b>v</b> {entry.version}</span>
          <span className="entry-kv"><b>ICD-10</b> {entry.icd10}</span>
          <span className="entry-kv"><b>Reviewed</b> {entry.reviewed}</span>
          <span className="entry-kv"><b>Template</b> {entry.template}</span>
        </div>
        <p className="entry-framing">{entry.framing}</p>
        <div className="entry-toc">
          <span className="entry-toc-lab">13 sections:</span>
          {entry.sections.map((s) => <span className="entry-toc-item" key={s.n}>{s.n}</span>)}
        </div>
      </div>

      <div className="entry-tabs">
        {ENTRY_TABS.map(([k, l]) => (
          <button key={k} className={'entry-tab' + (tab === k ? ' on' : '')} onClick={() => setTab(k)}>{l}</button>
        ))}
      </div>

      <div className="entry-pane">
        {tab === 'overview' && <p className="entry-prose">{entry.overview}</p>}

        {tab === 'feels' && (
          <div className="entry-feels">
            <p className="entry-prose dim">§1a — the narrative language the Health Story is generated from:</p>
            {entry.feels.map((f, i) => (
              <div className="feel" key={i}><span className="feel-lab">{f.label}</span><p>{f.text}</p></div>
            ))}
          </div>
        )}

        {tab === 'drivers' && (
          <div className="entry-drivers">
            {entry.drivers.map((d) => (
              <div className="entry-drv" key={d.code}>
                <div className="entry-drv-top"><DriverChip code={d.code} label /><span className="entry-drv-state">{d.state}</span><TierChip tier={d.tier} /></div>
                <ul>{d.points.map((p, i) => <li key={i} dangerouslySetInnerHTML={{ __html: p }} />)}</ul>
              </div>
            ))}
          </div>
        )}

        {tab === 'interactions' && (
          <table className="entry-table">
            <thead><tr><th>Condition</th><th>Justification</th><th>Tier</th><th>Clinical significance</th></tr></thead>
            <tbody>
              {entry.interactions.map((it, i) => (
                <tr key={i}><td><b>{it.condition}</b></td><td>{it.type}</td><td><TierChip tier={it.tier} /></td><td>{it.significance}</td></tr>
              ))}
            </tbody>
          </table>
        )}

        {tab === 'levers' && (
          <div className="entry-levers">
            {entry.levers.map((l) => (
              <div className="entry-lever" key={l.key}><span className="entry-lever-name">{window.LEVERS[l.key].name}</span><p>{l.text}</p></div>
            ))}
          </div>
        )}

        {tab === 'tracking' && (
          <div className="entry-tracking">
            <p className="entry-prose dim">§7 — these auto-populate the Symptom Tracker. 2–3 signals per activated driver.</p>
            {entry.tracking.map((t) => (
              <div className="track-grp" key={t.code}><DriverChip code={t.code} label /><ul>{t.items.map((it, i) => <li key={i}>{it}</li>)}</ul></div>
            ))}
            <div className="redflags"><span className="rf-lab">Red flags — seek provider contact</span><ul>{entry.redFlags.map((r, i) => <li key={i}>{r}</li>)}</ul></div>
          </div>
        )}

        {tab === 'conflicts' && (
          <div className="entry-conflicts">
            <p className="entry-prose dim">§9 — “Do not flatten these conflicts in generated outputs.”</p>
            {entry.conflicts.map((c, i) => (
              <ConflictCard key={i} topic={c.topic} position={c.a} counter={c.b} significance={c.sig} />
            ))}
          </div>
        )}

        {tab === 'cites' && (
          <div className="entry-cites">
            <div className="tier-key">{Object.entries(entry.tierKey).map(([t, l]) => <span key={t}><TierChip tier={t} /> {l}</span>)}</div>
            <ol>{entry.citations.map((c, i) => <li key={i}>{c.replace(/^\[\d+\]\s*/, '')}</li>)}</ol>
          </div>
        )}
      </div>
    </div>
  );
}

window.EngineSurface = EngineSurface;
