/* Direction 04 · Warm Retail — 3 interactives
   Receipt tape · Postcard sequence · Bundle shelf
*/
const { useState, useEffect, useMemo, useRef } = React;
const { CAPABILITIES, project, JOURNEY, PATIENTS, buildScript } = window.Weave;

const money = (n) => '$' + n.toLocaleString();
const pad = (s, w) => String(s).padStart(w, ' ');

/* ════════════════════════════════════════════════════════════
   1 · Receipt tape
   ═══════════════════════════════════════════════════════════ */
function ReceiptTape() {
  const [enabled, setEnabled] = useState(new Set(['supplements', 'vaccines', 'autorefill']));
  const [panel, setPanel] = useState(4200);
  const result = useMemo(() => project([...enabled], panel), [enabled, panel]);

  const toggle = (id) => {
    const n = new Set(enabled);
    n.has(id) ? n.delete(id) : n.add(id);
    setEnabled(n);
  };

  const presets = [
    { n: 'Single store', v: 2400 },
    { n: 'Small chain', v: 4200 },
    { n: 'Regional', v: 9500 },
  ];

  // stable-ish receipt number based on state
  const receiptNo = useMemo(() => {
    const base = 84120 + Math.round(result.revenue / 100) + enabled.size * 11;
    return base.toString().padStart(6, '0');
  }, [result.revenue, enabled.size]);

  const today = new Date();
  const dateStr = today.toLocaleDateString('en-US', { month: 'short', day: '2-digit', year: 'numeric' }).toUpperCase();

  return (
    <div className="receipt-wrap">
      <div className="r-controls">
        <div className="r-panel-card">
          <span className="lbl">Panel size</span>
          <div className="sz">
            <span className="big">{panel.toLocaleString()}</span>
            <span className="unit">active patients</span>
          </div>
          <input
            type="range" min="800" max="12000" step="100"
            value={panel} onChange={(e) => setPanel(+e.target.value)}
          />
          <div className="presets">
            {presets.map(p => (
              <button
                key={p.n}
                className={panel === p.v ? 'on' : ''}
                onClick={() => setPanel(p.v)}
              >{p.n} · {p.v.toLocaleString()}</button>
            ))}
          </div>
        </div>

        <div className="r-caps">
          {result.breakdown.map((c) => (
            <button
              key={c.id}
              className={'r-cap ' + (c.active ? 'on' : 'off')}
              onClick={() => toggle(c.id)}
            >
              <span className="tick">✓</span>
              <span>
                <span className="nm">{c.label}</span>
                <span className="tg">{c.tag} · {c.activePatients.toLocaleString()} eligible</span>
              </span>
              <span className="mo">{money(c.monthly)}/mo</span>
            </button>
          ))}
        </div>
      </div>

      <div className="r-tape">
        <div className="r-head">
          <span className="name">Westbrook Pharmacy</span>
          <span className="sub">Revenue Projection · 30‑day</span>
          <span className="addr">1408 Lamar Blvd · Austin, TX 78704</span>
        </div>

        <div className="r-row" style={{ fontSize: '10px', letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--mute)', borderBottom: '1px solid rgba(30,26,20,0.35)', paddingBottom: '8px' }}>
          <span>Line · eligible</span>
          <span>Monthly</span>
        </div>

        {result.breakdown.map((c) => (
          <div key={c.id} className={'r-row ' + (c.active ? '' : 'dim')}>
            <span className="ln-l">
              <span>{c.label}</span>
              <span className="pt">{c.activePatients.toLocaleString()} pt × ${c.rpp}/mo</span>
            </span>
            <span className="amt">{c.active ? money(c.monthly) : '—'}</span>
          </div>
        ))}

        <div className="r-sep" />
        <div className="r-total">
          <span>Subtotal · active lines</span>
          <span>{money(result.revenue)}</span>
        </div>
        <div className="r-total">
          <span>Per patient / month</span>
          <span>{money(result.perPatient)}</span>
        </div>
        <div className="r-total">
          <span>Conversations / week</span>
          <span>{result.conversations.toLocaleString()}</span>
        </div>
        <div className="r-total">
          <span>Staff hours returned / wk</span>
          <span>{result.hours.toFixed(1)}</span>
        </div>

        <div className="r-total grand">
          <span>Monthly total</span>
          <span className="amt">{money(result.revenue)}</span>
        </div>

        <div className="barcode">
          <svg viewBox="0 0 240 36" preserveAspectRatio="none">
            {Array.from({ length: 56 }).map((_, i) => {
              const w = ((i * 37 + result.revenue) % 5 < 2) ? 1 : 2.5;
              const skip = ((i * 19 + enabled.size) % 7 === 0);
              return !skip && <rect key={i} x={i * 4 + 2} y={0} width={w} height={36} fill="#1e1a14" />;
            })}
          </svg>
          <span className="bc-txt">RX · {receiptNo} · {dateStr}</span>
        </div>

        <div className="thanks">— Thank you. Pharmacist approves every call. —</div>
      </div>
    </div>
  );
}

/* ════════════════════════════════════════════════════════════
   2 · Live multimodal stage
   Tabbed scenes. Each scene plays out in real time when active:
   voice = waveform + auto-advancing transcript + call timer
   sms   = bubbles thread in with typing indicator
   email = compose → open → supplements populate line by line
   counter = pickup queue + Dr. Ramirez exchange
   followup = voice renderer, rerun
   ═══════════════════════════════════════════════════════════ */

/* Shared data + hooks pulled from live-stage-data.js (loaded before this file).
   We reference them via window.* to avoid any hoisting/redeclaration collisions
   with the global properties live-stage-data.js installs. */
const W = window;

function CallTimer({ running, resetKey }) {
  return <span className="elapsed">{W.useCallTimer(running, resetKey)}</span>;
}

function VoiceScene({ active, resetKey }) {
  const idx = W.useAutoAdvance(W.VOICE_SCRIPT, active, resetKey);
  const visible = W.VOICE_SCRIPT.slice(0, idx);
  const scrollRef = useRef(null);
  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [idx]);

  const lastSpk = visible.length ? visible[visible.length - 1].spk : null;
  const avaSpeaking = lastSpk === 'ava';

  return (
    <div className="live-voice">
      <div className="lv-head">
        <div className="lv-av">CA</div>
        <div className="lv-who">
          <div className="nm">Carla Alvarez</div>
          <div className="sub">Metformin 1000mg BID · 14 months</div>
        </div>
        <div className="lv-timer"><span className="rec-dot" /><CallTimer running={active && idx < W.VOICE_SCRIPT.length} resetKey={resetKey} /></div>
      </div>
      <div className={'lv-wave ' + (avaSpeaking ? 'active' : '')}>
        {Array.from({ length: 40 }).map((_, i) => (
          <div key={i} className="bar" style={{ animationDelay: (i * 40) + 'ms' }} />
        ))}
      </div>
      <div className="lv-transcript" ref={scrollRef}>
        {visible.map((l, i) => (
          <div key={i} className={'lv-line ' + l.spk}>
            <span className="spk">{l.spk === 'ava' ? 'AVA' : l.spk === 'pt' ? 'CARLA' : 'SYS'}</span>
            <span className="t">{l.t}</span>
          </div>
        ))}
        {idx < W.VOICE_SCRIPT.length && lastSpk !== 'sys' && (
          <div className="lv-line typing">
            <span className="spk">{W.VOICE_SCRIPT[idx].spk === 'ava' ? 'AVA' : W.VOICE_SCRIPT[idx].spk === 'pt' ? 'CARLA' : 'SYS'}</span>
            <span className="dots"><i/><i/><i/></span>
          </div>
        )}
      </div>
    </div>
  );
}

/* ── SMS scene ── */

function SmsScene({ active, resetKey }) {
  const idx = W.useAutoAdvance(W.SMS_THREAD, active, resetKey);
  const visible = W.SMS_THREAD.slice(0, idx);
  const scrollRef = useRef(null);
  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [idx]);

  const nextFrom = idx < W.SMS_THREAD.length ? W.SMS_THREAD[idx].from : null;

  return (
    <div className="live-sms">
      <div className="lv-head">
        <div className="lv-av">CA</div>
        <div className="lv-who">
          <div className="nm">Carla Alvarez · SMS</div>
          <div className="sub">Metformin 1000mg BID · 14 months</div>
        </div>
        <div className="lv-timer"><span className="rec-dot" /><span>LIVE</span></div>
      </div>
      <div className="lv-thread" ref={scrollRef}>
        {visible.map((m, i) => {
          if (m.from === 'sys') {
            return <div key={i} className="sms-sys">{m.t}</div>;
          }
          const isPt = m.from === 'pt';
          return (
            <div key={i} className={'sms-turn ' + (isPt ? 'pt' : 'pharm')}>
              <span className="sms-who">{isPt ? 'Carla' : 'Westbrook · Ava'}</span>
              <div className="sms-bubble">{m.t}</div>
            </div>
          );
        })}
        {idx < W.SMS_THREAD.length && nextFrom !== 'sys' && (
          <div className={'sms-turn typing ' + (nextFrom === 'pt' ? 'pt' : 'pharm')}>
            <span className="sms-who">{nextFrom === 'pt' ? 'Carla' : 'Westbrook · Ava'}</span>
            <div className="sms-bubble typing"><i/><i/><i/></div>
          </div>
        )}
      </div>
    </div>
  );
}

/* ── Email scene ── */

function EmailScene({ active, resetKey }) {
  const { stage, itemCount } = W.useEmailChoreography(active, resetKey);

  const total = W.EMAIL_ITEMS.slice(0, itemCount).reduce((s, x) => s + x.price, 0);
  const statusLabel = stage === 0 ? 'Composing' : stage === 1 ? 'Sending' : stage === 2 ? 'Delivered · 2m ago' : stage === 3 ? 'Opened' : 'Read · add to pickup';

  return (
    <div className="live-email">
      <div className="lv-head">
        <div className="lv-av">✉</div>
        <div className="lv-who">
          <div className="nm">Westbrook Pharmacy &lt;rx@westbrookrx.com&gt;</div>
          <div className="sub">To: carla.alvarez@gmail.com</div>
        </div>
        <div className="lv-timer em-status"><span className={'rec-dot ' + (stage >= 2 ? 'ok' : '')} /><span>{statusLabel}</span></div>
      </div>

      <div className={'email-canvas stage-' + stage}>
        <div className="em-banner">
          <h4>Your B12 bundle — reviewed by Dr. Ramirez</h4>
          <p>Following up on your call this morning with Ava.</p>
        </div>
        <div className="em-body">
          <p className="em-lede">Hi Carla, Dr. Ramirez has reviewed your current medications and identified supplements with peer‑reviewed evidence specific to your profile.</p>
          {W.EMAIL_ITEMS.slice(0, itemCount).map((it, i) => (
            <div key={it.name} className="em-row" style={{ animationDelay: (i * 40) + 'ms' }}>
              <div className="em-row-l">
                <strong>{it.name}</strong>
                <small>{it.why}</small>
                <small className="cite">{it.cite}</small>
              </div>
              <div className="em-row-r">${it.price.toFixed(2)}/mo</div>
            </div>
          ))}
          {itemCount < 3 && stage >= 3 && (
            <div className="em-row loading">
              <div className="em-row-l"><span className="shimmer" /><span className="shimmer short" /></div>
              <div className="em-row-r"><span className="shimmer small" /></div>
            </div>
          )}
          {stage >= 4 && (
            <div className="em-totals">
              <div className="em-tot-lbl">Monthly bundle · staged Thursday 4 PM</div>
              <div className="em-tot-amt">${total.toFixed(2)} / mo</div>
              <button className="em-cta">Add to Thursday pickup →</button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

/* ── Counter scene ── */

function CounterScene({ active, resetKey }) {
  const { queueN, dialogIdx } = W.useCounterChoreography(active, resetKey);

  return (
    <div className="live-counter">
      <div className="lv-head">
        <div className="lv-av">🏷</div>
        <div className="lv-who">
          <div className="nm">Westbrook counter · Day 3, 4:40 PM</div>
          <div className="sub">Rx queue · Carla Alvarez</div>
        </div>
        <div className="lv-timer"><span className="rec-dot ok" /><span>AT COUNTER</span></div>
      </div>

      <div className="counter-queue">
        {W.COUNTER_QUEUE.slice(0, queueN).map((r, i) => (
          <div key={i} className={'cq-row cq-' + r.status.toLowerCase()} style={{ animationDelay: (i * 60) + 'ms' }}>
            <span className="cq-status">{r.status}</span>
            <span className="cq-item">{r.item}</span>
            {r.meta && <span className="cq-meta">{r.meta}</span>}
          </div>
        ))}
      </div>

      <div className="counter-dialog">
        <div className="cd-rule" />
        {W.COUNTER_DIALOG.slice(0, dialogIdx).map((l, i) => (
          <div key={i} className={'cd-line cd-' + l.spk}>
            <span className="cd-spk">{l.spk === 'dr' ? 'Dr. Ramirez' : 'Carla'}</span>
            <span className="cd-t">“{l.t}”</span>
          </div>
        ))}
      </div>

      <div className="counter-foot">Pickup recorded · writeback to PMS · D+21 follow‑up scheduled</div>
    </div>
  );
}

/* ── Follow-up scene (reuses voice styling, different script) ── */

function FollowupScene({ active, resetKey }) {
  const idx = W.useAutoAdvance(W.FOLLOWUP_SCRIPT, active, resetKey);
  const visible = W.FOLLOWUP_SCRIPT.slice(0, idx);
  const scrollRef = useRef(null);
  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [idx]);
  const lastSpk = visible.length ? visible[visible.length - 1].spk : null;
  const avaSpeaking = lastSpk === 'ava';

  return (
    <div className="live-voice">
      <div className="lv-head">
        <div className="lv-av">CA</div>
        <div className="lv-who">
          <div className="nm">Carla Alvarez · follow‑up</div>
          <div className="sub">Day 21 · 9:00 AM</div>
        </div>
        <div className="lv-timer"><span className="rec-dot" /><CallTimer running={active && idx < W.FOLLOWUP_SCRIPT.length} resetKey={resetKey} /></div>
      </div>
      <div className={'lv-wave ' + (avaSpeaking ? 'active' : '')}>
        {Array.from({ length: 40 }).map((_, i) => (
          <div key={i} className="bar" style={{ animationDelay: (i * 40) + 'ms' }} />
        ))}
      </div>
      <div className="lv-transcript" ref={scrollRef}>
        {visible.map((l, i) => (
          <div key={i} className={'lv-line ' + l.spk}>
            <span className="spk">{l.spk === 'ava' ? 'AVA' : l.spk === 'pt' ? 'CARLA' : 'SYS'}</span>
            <span className="t">{l.t}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ── Tabbed stage ── */
const CHANNEL_EL = { voice: VoiceScene, sms: SmsScene, email: EmailScene, counter: CounterScene, followup: FollowupScene };

function LiveStage() {
  const [active, setActive] = useState('voice');
  const [reset, setReset] = useState(0);
  const current = W.CHANNEL_META.find(c => c.id === active);
  const Active = CHANNEL_EL[active];

  const pick = (id) => { setActive(id); setReset(r => r + 1); };

  return (
    <div className="live-wrap">
      <div className="ls-tabs">
        {W.CHANNEL_META.map((c, i) => (
          <button
            key={c.id}
            className={'ls-tab ' + (c.id === active ? 'on' : '')}
            onClick={() => pick(c.id)}
          >
            <span className="ls-num">Step 0{i + 1}</span>
            <span className="ls-label">{c.label}</span>
            <span className="ls-sub">{c.when}</span>
            <span className="ls-desc">{c.sub}</span>
          </button>
        ))}
      </div>
      <div className="ls-stage" key={current.id}>
        <div className="ls-head-bar">
          <span className="ls-stamp">{current.label}</span>
          <span className="ls-head-title">{current.when} · {current.sub}</span>
          <button className="ls-replay" onClick={() => setReset(r => r + 1)}>↻ Replay</button>
        </div>
        <Active active={true} resetKey={reset + ':' + active} />
      </div>
    </div>
  );
}

/* ════════════════════════════════════════════════════════════
   3 · Bundle shelf
   ═══════════════════════════════════════════════════════════ */
const WHY_MAP = {
  'Methylcobalamin B12': 'Replaces what metformin depletes.',
  'Alpha‑lipoic acid':    'Calms nerve tingling.',
  'Magnesium glycinate':  'Muscle & sleep support.',
  'Vitamin D3':           'Restores PPI‑blocked absorption.',
  'CoQ10 Ubiquinol':      'Replaces statin‑blocked synthesis.',
  'Omega‑3 EPA':          'Cardiovascular support.',
  'Selenium':             'Supports T4 → T3 conversion.',
};

function BundleShelf() {
  const [ptId, setPtId] = useState('carla');
  const patient = PATIENTS.find(p => p.id === ptId);
  const script = useMemo(() => buildScript(patient), [ptId]);

  return (
    <div className="shelf-wrap">
      <div className="pt-list">
        {PATIENTS.map(p => (
          <button
            key={p.id}
            className={'pt-card ' + (p.id === ptId ? 'on' : '')}
            onClick={() => setPtId(p.id)}
          >
            <span className="pt-n">{p.name}</span>
            <span className="pt-age">{p.age} · {p.city}</span>
            <span className="pt-m">{p.meds.map(m => m.drug).join(' · ')}</span>
          </button>
        ))}
      </div>

      <div className="shelf-stage">
        <div className="pt-summary">
          <span className="mechanism-label">§ Pharmacist‑approved rule · {patient.drugClass}</span>
          <p className="mechanism">{script.mechanism}</p>
        </div>

        <div className="shelf">
          <div className="shelf-row" key={ptId /* re-triggers animation */}>
            {script.bundle.map((b, i) => (
              <div className="jar" key={b.name} style={{ animationDelay: (i * 80) + 'ms' }}>
                <div className="label">
                  <div className="lx-nm">{b.name}</div>
                  <div className="lx-dose">{b.dose}</div>
                  <span className="lx-cite">{b.cite}</span>
                </div>
                <div className="lx-why">{WHY_MAP[b.name] || 'Supports the depletion pattern.'}</div>
              </div>
            ))}
          </div>
        </div>

        <div className="shelf-footer">
          <div className="script-card">
            <div className="sc-head">§ Agent script · deterministic from rule</div>
            {script.lines.slice(0, 5).map((l, i) => (
              <div key={i} className={'sc-line ' + l.spk}>
                <span className="spk">{l.spk === 'ava' ? 'Ava' : 'Pt'}</span>
                <span className="t">“{l.t}”</span>
              </div>
            ))}
          </div>
          <div className="price-card">
            <span className="pc-head">§ Monthly bundle</span>
            <div className="pc-price">${script.price}</div>
            <span className="pc-unit">per month · {script.bundle.length} items</span>
            <p className="pc-note">Pharmacist approved the rule once, by drug class. Agent applies it patient by patient, citing the mechanism on the call.</p>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ────── mount ────── */
const mount = (id, El) => {
  const el = document.getElementById(id);
  if (el) ReactDOM.createRoot(el).render(<El />);
};
mount('retail-receipt', ReceiptTape);
mount('retail-postcards', LiveStage);
mount('retail-shelf', BundleShelf);
