/* ───────────────────────────────────────────────────────────────────────────
   Surface 1 — Conversation (the product's front door)
   The recommended direction: synthesis revealed in dialogue. Intake recap →
   synthesis reveal (drivers light up in the rail) → hand-off chips into the
   Health Story, Action Plan, and the engine trace.
   ─────────────────────────────────────────────────────────────────────────── */

const CV_SYNTH = {
  jordan: "Based on your intake and what we just talked through, here's the whole picture in one paragraph. You came in with three diagnoses and a question nobody had answered — <em>why does it all feel connected?</em> Two drivers are doing most of the work: <b>Inflammation</b> and <b>Cellular Energy</b>. The autoimmune burden of Hashimoto's and the inflammatory signature of the other two all pour into the same cytokine pool — and that pool is what's affecting your mitochondria. <b>That's why the fatigue persists even though your TSH reads normal.</b>",
  dana: "Here's what the synthesis found, and I want to be precise because you've been told vague things before. Your chest pain is <b>costochondritis</b> — inflammation of the cartilage where your ribs meet your breastbone. It's reproducible on palpation and it has a mechanism: prostaglandins and inflammatory cytokines at the joint <span class=\"cite\">[T1]</span>. Your <b>hypermobile EDS</b> is why it keeps coming back — the rib joints take microtrauma more easily. <b>It was never anxiety. The anxiety came from no one explaining this.</b>",
};

const CV_WHY = {
  jordan: "Honest answer: each of your providers is excellent in their lane. The endocrinologist watches your TSH, the psychiatrist watches your mood, the rheumatologist watches the pain. Nobody's job description includes the integration — and the connecting story is exactly the gap we just closed.",
  dana: "Two reasons, and both are in the library entry. Your connective-tissue laxity creates structural vulnerability at the rib joints — a recognized EDS interaction <span class=\"cite\">[T2]</span>. And stress amplifies the inflammation through your HPA axis, so flares track with hard weeks. In otherwise-healthy people this is self-limiting; for you it recurs, and that's expected — not you failing to heal.",
};

function ConversationSurface({ persona, go }) {
  const [msgs, setMsgs] = React.useState([]);     // rendered messages
  const [typing, setTyping] = React.useState(false);
  const [awaiting, setAwaiting] = React.useState(null); // {opts, idx} | 'terminal' | null
  const [driversLive, setDriversLive] = React.useState(false);
  const [stage, setStage] = React.useState('listening');
  const streamRef = React.useRef(null);
  const timers = React.useRef([]);
  const script = persona.convo;

  const clearTimers = () => { timers.current.forEach(clearTimeout); timers.current = []; };
  const after = (ms, fn) => { const t = setTimeout(fn, ms); timers.current.push(t); };

  React.useEffect(() => {
    boot();
    return clearTimers;
    // eslint-disable-next-line
  }, [persona.id]);

  React.useEffect(() => {
    if (streamRef.current) streamRef.current.scrollTop = streamRef.current.scrollHeight;
  }, [msgs, typing, awaiting]);

  function boot() {
    clearTimers();
    setMsgs([]); setAwaiting(null); setDriversLive(false); setTyping(false); setStage('listening');
    after(400, () => playFrom(0));
  }

  function push(m) { setMsgs((prev) => [...prev, m]); }

  function playFrom(i) {
    if (i >= script.length) { setAwaiting('terminal'); return; }
    const e = script[i];
    if (e.who === 'lena') {
      setTyping(true);
      const dwell = Math.min(1300, 480 + (e.text.length * 7));
      after(dwell, () => { setTyping(false); push({ who: 'lena', text: e.text }); after(360, () => playFrom(i + 1)); });
    } else if (e.who === 'synthesis') {
      setStage('synthesis');
      setTyping(true);
      after(900, () => { setTyping(false); push({ who: 'synthesis' }); setDriversLive(true); after(500, () => playFrom(i + 1)); });
    } else if (e.who === 'opts') {
      // is this terminal (no user reply follows)?
      const next = script[i + 1];
      if (!next || next.who === 'opts') setAwaiting('terminal');
      else setAwaiting({ opts: e.opts, idx: i });
    } else {
      // a user line that follows an opts — should only render on click; skip in auto
      playFrom(i + 1);
    }
  }

  function chooseEarly() {
    if (!awaiting || awaiting === 'terminal') return;
    const userLine = script[awaiting.idx + 1];
    setAwaiting(null);
    if (userLine && userLine.who !== 'opts' && userLine.who !== 'lena' && userLine.who !== 'synthesis') {
      push({ who: 'you', text: userLine.text });
      after(420, () => playFrom(awaiting.idx + 2));
    } else {
      playFrom(awaiting.idx + 1);
    }
  }

  function askWhy() {
    setAwaiting(null);
    push({ who: 'you', text: persona.id === 'dana' ? 'why does it keep coming back?' : 'why was nobody telling me this?' });
    setTyping(true);
    after(1100, () => { setTyping(false); push({ who: 'lena', text: CV_WHY[persona.id] }); after(400, () => setAwaiting('terminal')); });
  }

  const topDrivers = persona.drivers.slice(0, 3);

  return (
    <div className="cv-wrap">
      <div className="cv-frame">
        {/* thread */}
        <div className="cv-thread">
          <div className="cv-bar">
            <div className="cv-who">
              <Avatar who="lena" size={36} />
              <div>
                <div className="cv-nm">Lena Maren, NBC-HWC</div>
                <div className="cv-role">your health educator · session 2 with {persona.name}</div>
              </div>
            </div>
            <button className="cv-restart" onClick={boot}>↻ replay</button>
          </div>

          <div className="cv-stream" ref={streamRef}>
            <div className="cv-daymark">Today · 10:42am</div>
            {msgs.map((m, k) => <CvMessage key={k} m={m} persona={persona} go={go} />)}
            {typing && (
              <div className="cv-typing"><span /><span /><span /></div>
            )}
          </div>

          <div className="cv-tray">
            {awaiting === 'terminal' ? (
              <>
                <div className="cv-hint">Where to next —</div>
                <div className="cv-chips">
                  <button className="cv-chip ghost" onClick={askWhy}>{persona.id === 'dana' ? 'why does it keep coming back?' : 'why was nobody telling me this?'}</button>
                  <button className="cv-chip" onClick={() => go('story')}>Skip to my Health Story →</button>
                  <button className="cv-chip primary" onClick={() => go('engine')}>Next · see how this was built →</button>
                </div>
              </>
            ) : awaiting ? (
              <>
                <div className="cv-hint">Pick a reply ↓</div>
                <div className="cv-chips">
                  {awaiting.opts.map((o, k) => (
                    <button key={k} className={'cv-chip' + (o.includes('→') ? ' primary' : '')} onClick={chooseEarly}>{o}</button>
                  ))}
                </div>
              </>
            ) : (
              <div className="cv-hint muted">Lena is typing…</div>
            )}
          </div>
        </div>

        {/* rail */}
        <aside className="cv-rail">
          <div className="rail-block">
            <div className="rail-eyebrow">Where we are</div>
            <div className="rail-steps">
              {[['listening', 'Listening'], ['synthesis', 'Synthesis'], ['story', 'Health Story'], ['plan', 'Action Plan'], ['care', 'Care team']].map(([k, l], idx) => {
                const order = ['listening', 'synthesis', 'story', 'plan', 'care'];
                const cur = order.indexOf(stage);
                const me = idx;
                const cls = me < cur || (stage === 'synthesis' && me <= 1) ? 'done' : (me === cur ? 'now' : '');
                return <div key={k} className={'rail-step ' + cls}><span className="rs-tick">✓</span>{l}</div>;
              })}
            </div>
          </div>

          <div className="rail-block">
            <div className="rail-eyebrow">Driver picture {driversLive ? '· live' : ''}</div>
            {driversLive ? (
              <div className="rail-drivers">
                {topDrivers.map((d) => (
                  <div className="rail-drv" key={d.code}>
                    <DriverChip code={d.code} />
                    <div className="rail-drv-track"><i style={{ width: Math.round(d.weight * 100) + '%', background: window.DRIVERS[d.code].color }} /></div>
                    <span className="rail-drv-pct">{Math.round(d.weight * 100)}</span>
                  </div>
                ))}
              </div>
            ) : (
              <p className="rail-empty">Drivers light up once we hand the conversation to the synthesis engine. Right now we're still listening.</p>
            )}
          </div>

          <StickyNote eyebrow="In her own words" tone="teal" rotate={-1.4}>
            “{persona.inHerWords}”
          </StickyNote>
        </aside>
      </div>
    </div>
  );
}

function CvMessage({ m, persona, go }) {
  if (m.who === 'synthesis') {
    return (
      <div className="cv-synth">
        <div className="cv-synth-head">
          <span className="cv-synth-badge">Synthesis</span>
          <span className="cv-synth-note">read from {persona.matched.filter((x) => x.primary).length} library entries · reviewed before you saw it</span>
        </div>
        <p dangerouslySetInnerHTML={{ __html: CV_SYNTH[persona.id] }} />
        <div className="cv-synth-drivers">
          {persona.drivers.slice(0, 2).map((d) => <DriverChip key={d.code} code={d.code} label big />)}
        </div>
      </div>
    );
  }
  if (m.who === 'lena') {
    return (
      <div className="cv-msg them">
        <Avatar who="lena" size={30} />
        <div className="cv-bub" dangerouslySetInnerHTML={{ __html: m.text }} />
      </div>
    );
  }
  return (
    <div className="cv-msg me">
      <div className="cv-bub" dangerouslySetInnerHTML={{ __html: m.text }} />
      <Avatar who={persona.id} persona={persona} size={30} />
    </div>
  );
}

window.ConversationSurface = ConversationSurface;
