/* ───────────────────────────────────────────────────────────────────────────
   Surface 5 — Editorial review  (the credibility layer, designed in from day 1)
   Three editorial surfaces, phased — but architected together, not retrofitted:
     · Carey's review  — Phase 0, NOW. A first-class working review surface.
     · Clinician       — Phase 1.5+, scaffolded.
     · Practitioner    — Phase 1.5+, scaffolded.
   Carey's surface is where the dual-tailoring control lives for the reviewer:
   adjust delivery, accept/adjust driver weight, footnote, approve.
   ─────────────────────────────────────────────────────────────────────────── */

const ED_TABS = [
  { key: 'carey', label: "Carey's review", phase: 'Phase 0 · now', live: true },
  { key: 'clinician', label: 'Clinician', phase: 'Phase 1.5+', live: false },
  { key: 'practitioner', label: 'Practitioner', phase: 'Phase 1.5+', live: false },
];

function EditorialSurface({ persona, go }) {
  const [tab, setTab] = React.useState('carey');
  return (
    <div className="surface ed-surface">
      <SurfaceHead
        eyebrow="Editorial review · the credibility layer"
        title={<>A work product. <em>Not a raw output.</em></>}
        sub="Every output is read by a credentialed human before it reaches anyone. Clinicians called this non-negotiable — so it's a first-class surface from day one, with the clinician and practitioner surfaces designed in alongside it, not bolted on later." />

      <div className="ed-tabs">
        {ED_TABS.map((t) => (
          <button key={t.key} className={'ed-tab' + (tab === t.key ? ' on' : '') + (t.live ? ' live' : '')} onClick={() => setTab(t.key)}>
            <span>{t.label}</span>
            <span className="ed-tab-phase">{t.phase}</span>
          </button>
        ))}
      </div>

      {tab === 'carey' && <CareyReview persona={persona} go={go} />}
      {tab === 'clinician' && <ScaffoldSurface kind="clinician" persona={persona} />}
      {tab === 'practitioner' && <ScaffoldSurface kind="practitioner" persona={persona} />}

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

/* ── Carey's review — the live, first-class surface ─────────────────────────── */
function CareyReview({ persona, go }) {
  const initial = LIT_TO_DEPTH[persona.calibration.literacy.value] || 'standard';
  const [depth, setDepth] = React.useState(initial);
  const [states, setStates] = React.useState({});   // passageId -> 'keep'|'flag'
  const [notes, setNotes] = React.useState({});      // passageId -> footnote string
  const [composing, setComposing] = React.useState(null);
  const [draft, setDraft] = React.useState('');
  const [weights, setWeights] = React.useState(() => Object.fromEntries(persona.drivers.map((d) => [d.code, 'accepted'])));
  const [status, setStatus] = React.useState('in-review');

  React.useEffect(() => {
    setDepth(LIT_TO_DEPTH[persona.calibration.literacy.value] || 'standard');
    setStates({}); setNotes({}); setComposing(null); setStatus('in-review');
    setWeights(Object.fromEntries(persona.drivers.map((d) => [d.code, 'accepted'])));
  }, [persona.id]);

  const flagged = Object.values(states).filter((s) => s === 'flag').length;
  const footnotes = Object.keys(notes).length;

  function setPassage(id, s) { setStates((p) => ({ ...p, [id]: p[id] === s ? 'keep' : s })); }
  function saveNote() { if (composing && draft.trim()) { setNotes((p) => ({ ...p, [composing]: draft.trim() })); } setComposing(null); setDraft(''); }
  function cycleWeight(code) { setWeights((p) => ({ ...p, [code]: p[code] === 'accepted' ? 'adjusted' : p[code] === 'adjusted' ? 'rejected' : 'accepted' })); }

  return (
    <div className="carey">
      <div className="carey-bar">
        <div className="carey-doc">
          <Avatar who={persona.id} persona={persona} size={30} />
          <div>
            <div className="cd-name">{persona.name}, {persona.age} · My Health Story</div>
            <div className="cd-meta">generated {persona.matched.filter((m) => m.primary).length}-entry synthesis · awaiting your review</div>
          </div>
        </div>
        <div className="carey-status">
          <span className={'cs-pill cs-' + status}>{status === 'approved' ? '✓ Approved' : status === 'in-review' ? '● In review' : 'Needs review'}</span>
          {flagged > 0 && <span className="cs-count">{flagged} flagged</span>}
          {footnotes > 0 && <span className="cs-count">{footnotes} footnote{footnotes > 1 ? 's' : ''}</span>}
        </div>
      </div>

      <div className="carey-grid">
        {/* draft */}
        <div className="carey-draft">
          <div className={'review-doc story-' + depth}>
            {persona.story.map((p) => {
              const st = states[p.id] || 'keep';
              return (
                <div className={'review-passage ' + st} key={p.id}>
                  <div className="rp-body">
                    <h4 className="rp-h">{p.heading}{p.drivers && p.drivers.length > 0 && <span className="rp-chips">{p.drivers.map((c) => <DriverChip key={c} code={c} />)}</span>}</h4>
                    <p>{p[depth]}</p>
                    {notes[p.id] && <div className="rp-footnote"><span>Carey's note</span>{notes[p.id]}</div>}
                  </div>
                  <div className="rp-tools">
                    <button className={'rp-tool' + (st === 'keep' ? ' on' : '')} onClick={() => setPassage(p.id, 'keep')} title="Keep">✓</button>
                    <button className={'rp-tool' + (st === 'flag' ? ' on flag' : '')} onClick={() => setPassage(p.id, 'flag')} title="Flag for revision">⚑</button>
                    <button className="rp-tool" onClick={() => { setComposing(p.id); setDraft(notes[p.id] || ''); }} title="Add footnote">✎</button>
                  </div>
                  {composing === p.id && (
                    <div className="rp-compose">
                      <textarea value={draft} autoFocus placeholder="Add a footnote or revision note…" onChange={(e) => setDraft(e.target.value)} />
                      <div className="rp-compose-actions">
                        <button className="btn sm" onClick={saveNote}>Save note</button>
                        <button className="btn sm ghost" onClick={() => { setComposing(null); setDraft(''); }}>Cancel</button>
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>

        {/* controls */}
        <aside className="carey-controls">
          <div className="cc-block">
            <div className="cc-eyebrow">Delivery calibration</div>
            <p className="cc-hint">The reviewer's hand on the personal-tailoring layer. Same synthesis, change how it lands.</p>
            <span className="cc-label">Reading depth</span>
            <div className="seg">
              {DEPTHS.map(([k, l]) => <button key={k} className={'seg-btn' + (depth === k ? ' on' : '')} onClick={() => setDepth(k)}>{l}</button>)}
            </div>
            <div className="cc-calib">
              <span>Calibrated default: <b>{persona.calibration.literacy.value}</b> · {persona.calibration.comms.value.toLowerCase()}</span>
            </div>
          </div>

          <div className="cc-block">
            <div className="cc-eyebrow">Driver weight</div>
            <p className="cc-hint">Accept the engine's read, adjust it, or reject — your call is the record.</p>
            <div className="cc-weights">
              {persona.drivers.slice(0, 3).map((d) => (
                <button key={d.code} className={'cc-weight w-' + weights[d.code]} onClick={() => cycleWeight(d.code)}>
                  <DriverChip code={d.code} />
                  <span className="cw-state">{d.state}</span>
                  <span className="cw-decision">{weights[d.code] === 'accepted' ? '✓ accept' : weights[d.code] === 'adjusted' ? '± adjust' : '✕ reject'}</span>
                </button>
              ))}
            </div>
          </div>

          <div className="cc-block">
            <div className="cc-eyebrow">Editorial action</div>
            {status !== 'approved' ? (
              <>
                <button className="btn full" onClick={() => { setStatus('approved'); }}>✓ Approve &amp; queue companion</button>
                <button className="btn full ghost" onClick={() => go('engine')}>Send back to the engine →</button>
              </>
            ) : (
              <div className="cc-approved">
                <div className="cc-approved-head">✓ Approved by Carey · {new Date().toLocaleDateString()}</div>
                <p>The Health Story ships to {persona.name}. The Care Team Companion is queued for {persona.companion.clinical.for.split('·')[0].trim()}.</p>
                <button className="btn full" onClick={() => go('care')}>View the Care Team Companion →</button>
              </div>
            )}
          </div>

          <div className="cc-foot">
            This surface is the unit economics. Faster review → more Stories per week → the model works. It's why we designed it as a screen, not a checkbox.
          </div>
        </aside>
      </div>
    </div>
  );
}

/* ── Clinician / Practitioner scaffolds — Phase 1.5+, architected now ───────── */
const SCAFFOLD = {
  clinician: {
    title: 'Clinician editorial surface',
    blurb: 'Licensed providers annotate, adjust, or add clinical context to the Health Story and Action Plan before it reaches the individual. Expressed as a non-negotiable by clinicians in early conversations.',
    rows: [
      ['Annotate in clinical language', 'Margin notes that never surface raw to the individual — they re-enter the synthesis as context.'],
      ['Adjust driver emphasis', 'A provider can up- or down-weight a driver with a reason; the change is attributed and audited.'],
      ['Add or correct context', 'Labs, a diagnosis the intake missed, a medication interaction — folded back through the engine.'],
      ['Scope-of-practice guardrail', 'The surface keeps the boundary intact: education and synthesis, not diagnosis or prescription.'],
    ],
  },
  practitioner: {
    title: 'Practitioner editorial surface',
    blurb: 'Coaches, community health workers, and non-clinician practitioners adjust framing, add context, and flag items for conversation. Especially important for community and rural settings where the practitioner is the bridge between the document and the individual.',
    rows: [
      ['Adjust framing for the relationship', 'A practitioner who knows the person can soften, sequence, or re-order without touching the synthesis.'],
      ['Flag items for conversation', 'Mark a passage to talk through in person rather than deliver cold on the page.'],
      ['Add local context', 'What is actually accessible in this community — folded into which levers get surfaced.'],
      ['Bridge the document and the person', 'The practitioner is the last mile; the surface gives them a real seat.'],
    ],
  },
};

function ScaffoldSurface({ kind, persona }) {
  const s = SCAFFOLD[kind];
  return (
    <div className="scaffold">
      <div className="scaffold-ribbon">Phase 1.5+ · scaffolded · architected from the start</div>
      <h3 className="scaffold-title">{s.title}</h3>
      <p className="scaffold-blurb">{s.blurb}</p>
      <div className="scaffold-rows">
        {s.rows.map((r, i) => (
          <div className="scaffold-row" key={i}>
            <span className="sr-n">{String(i + 1).padStart(2, '0')}</span>
            <div><div className="sr-h">{r[0]}</div><p>{r[1]}</p></div>
          </div>
        ))}
      </div>
      <div className="scaffold-note">
        <b>Why it's here now.</b> Designing the review architecture for all three surfaces from day one means Carey's Phase-0 surface and these Phase-1.5 surfaces share one data model — the annotations, the attribution, the audit trail. Retrofitting later would mean rebuilding the spine.
      </div>
    </div>
  );
}

window.EditorialSurface = EditorialSurface;
