/* journify.ai — HeroCall: the homepage hero's call card (rebrand chunk 4, from
   _ops/2026-10-10-rebrand/prototype-hero/hero.js; spec: _ops/2026-10-10-rebrand/specs/homepage-hero.md).
   HeroCall({ call }) draws one card that plays two calls, "Last call" and "Next call": two tabs at its top
   choose a call; the call's title under them; a round play button beside a full-width recording. It plays
   by itself once, when 40% of it is on screen. Each exchange (your question, the buyer's answer) fades in
   at the TOP of the card and the older ones slide down; a verdict chip fades in beside the line it
   describes; then the card turns to the next call. The play button pauses, resumes and replays. A tab
   shows its call finished. Reduced motion draws the last call finished, hides the play button and keeps
   the tabs. No words in this file: they all come from content/homepage.json s1.call.
   The DOM work runs in one useEffect, the prototype's mechanism unchanged; window.__hero exposes it for
   the checks in _ops/2026-10-10-rebrand/prototype-hero/measure/. */

const HC_PITCH = 6.67;       /* px from one bar to the next */
const HC_NOTE_DELAY = 1100;  /* ms from a pair's arrival to its chip: the 600 ms fade, then half a second */
const HC_TURN_FADE = 650;    /* ms the last call's lines take to fade out before the card turns */
const HC_TURN_GAP = 1300;    /* ms from the turn to the next call's first line */
const HC_ICON_PLAY = '<svg viewBox="0 0 12 12" aria-hidden="true"><path d="M3 1.5v9l8-4.5z" fill="currentColor"/></svg>';
const HC_ICON_PAUSE = '<svg viewBox="0 0 12 12" aria-hidden="true"><rect x="2" y="1.5" width="3" height="9" rx="0.5" fill="currentColor"/><rect x="7" y="1.5" width="3" height="9" rx="0.5" fill="currentColor"/></svg>';

function hcEl(tag, cls, html) { const e = document.createElement(tag); if (cls) e.className = cls; if (html != null) e.innerHTML = html; return e; }
function hcEsc(s) { return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;'); }
const hcPairMs = (pace, p) => pace.base + pace.perChar * (p.q.length + p.a.length);

/* one call's recording, as wide as the player. The rule in components/Recording.jsx: tone "wrong" is uneven bars,
   seeded per call, grey into oxblood; tone "right" is the calm wave, oxblood into ember, at the same height. The
   fill shows on the played bars: .hc-grey rect sets the unplayed ones to the hairline grey */
function hcBarsSvg(width, seed, tone) {
  const n = Math.max(1, Math.floor(width / HC_PITCH)); let s = seed, out = '';
  for (let i = 0; i < n; i++) {
    s = (s * 9301 + 49297) % 233280; const r = s / 233280;
    const env = 0.3 + 0.7 * Math.abs(Math.sin((i + seed) / 5)) * (0.6 + 0.4 * Math.sin((i + seed) / 13));
    const h = tone === 'right' ? Math.round(30 * (0.5 + 0.3 * Math.sin(i / n * Math.PI * 6))) : Math.max(3, Math.round(30 * env * (0.5 + 0.5 * r)));
    const fill = tone === 'right' ? recHeat(h, 24) : recCold(h, 24);
    out += '<rect x="' + (i * HC_PITCH + 1.2).toFixed(1) + '" y="' + ((30 - h) / 2).toFixed(1) + '" width="' + (HC_PITCH - 2.4).toFixed(1) + '" height="' + h + '" rx="1" fill="' + fill + '"/>';
  }
  return '<svg width="' + width + '" height="30" viewBox="0 0 ' + width + ' 30" aria-hidden="true">' + out + '</svg>';
}
function hcLineHtml(who, text, key, note) {
  return '<div class="hc-ln' + (key ? ' is-key' : '') + '"><div class="hc-who">' + hcEsc(who) + '</div>' +
    '<div class="hc-row"><div class="hc-text">' + hcEsc(text) + '</div>' + (note ? '<span class="hc-note">' + hcEsc(note) + '</span>' : '') + '</div></div>';
}
function hcPairHtml(call, p) {
  const sp = call.speakers;
  return '<span class="hc-at">' + hcEsc(p.at) + '</span><div>' + hcLineHtml(sp.you, p.q, p.keyQ, p.qNote) + hcLineHtml(sp.buyer, p.a, p.keyA, p.aNote) + '</div>';
}
/* the schedule, in ms from the start of the play */
function hcSchedule(call) {
  const pace = call.pace, steps = [], acts = []; let t = 400;
  call.acts.forEach((act, k) => {
    if (k > 0) { t += pace.turnHold; steps.push({ t, turn: k }); t += HC_TURN_GAP; }
    const start = t;
    steps.push({ t: start, actStart: k });
    act.pairs.forEach(p => { steps.push({ t, pair: p }); t += hcPairMs(pace, p); });
    acts.push({ start, end: t });
  });
  steps.push({ t: t + 300, done: true });
  return { steps, acts, total: t + 300 + 800 };
}

/* builds the card inside col and runs it; returns a teardown */
function hcMount(col, call) {
  const reduce = window.matchMedia('(prefers-reduced-motion: reduce)');
  const plan = hcSchedule(call), controls = call.controls || {};
  const card = hcEl('div', 'hc is-act0 tone-' + call.acts[0].tone);
  card.innerHTML =
    '<div class="hc-tabs" role="group" aria-label="' + hcEsc(controls.group || '') + '">' + call.acts.map((a, k) => '<button type="button" class="hc-tab" data-act="' + k + '" aria-pressed="false">' + hcEsc(a.tab) + '</button>').join('') + '</div>' +
    '<div class="hc-titles">' + call.acts.map((a, k) => '<div class="hc-ta hc-ta' + k + '"' + (k ? ' aria-hidden="true"' : '') + '><div class="hc-title">' + hcEsc(a.title) + '</div>' + (a.sub ? '<div class="hc-asub">' + hcEsc(a.sub) + '</div>' : '') + '</div>').join('') + '</div>' +
    '<div class="hc-player"><button type="button" class="hc-play" aria-label="' + hcEsc(controls.play || '') + '">' + HC_ICON_PLAY + '</button>' +
    '<div class="hc-wave" aria-hidden="true"><div class="hc-bars hc-grey"></div><div class="hc-played"><div class="hc-bars"></div></div><i class="hc-playhead"></i></div></div>' +
    '<div class="hc-lines"><div class="hc-list"></div></div>';
  col.appendChild(card);

  const wave = card.querySelector('.hc-wave'), bars = card.querySelectorAll('.hc-bars'), played = card.querySelector('.hc-played'), head = card.querySelector('.hc-playhead');
  const list = card.querySelector('.hc-list'), titles = card.querySelector('.hc-titles');
  const playBtn = card.querySelector('.hc-play'), tabs = Array.from(card.querySelectorAll('.hc-tab'));
  let timers = [], state = 'idle', startedAt = 0, elapsed = 0, curAct = 0, drawn = '', pendingTurn = null, frac = 0;

  function drawBars(k) {
    const w = Math.round(wave.clientWidth), key = k + ':' + w;
    if (!w || drawn === key) return; drawn = key;
    const svg = hcBarsSvg(w, 5 + k * 97, call.acts[k].tone);
    bars.forEach(b => { b.innerHTML = svg; b.style.width = w + 'px'; });
  }
  function setProgress(f, ms) {
    frac = f; const w = wave.clientWidth;
    const tr = ms ? ms + 'ms linear' : '';
    played.style.transition = ms ? 'clip-path ' + tr : 'none';
    head.style.transition = ms ? 'transform ' + tr : 'none';
    played.style.clipPath = 'inset(0 ' + ((1 - f) * 100).toFixed(3) + '% 0 0)';
    head.style.transform = 'translateX(' + (f * w).toFixed(1) + 'px)';
  }
  function liveProgress() { const w = wave.clientWidth || 1; return Math.max(0, Math.min(1, new DOMMatrixReadOnly(getComputedStyle(head).transform).m41 / w)); }
  function fitTitles(instant) {
    const t = titles.querySelector('.hc-ta' + curAct); if (!t) return;
    if (instant) titles.style.transition = 'none';
    titles.style.height = t.offsetHeight + 'px';
    if (instant) { void titles.offsetWidth; titles.style.transition = ''; }
  }
  function setAct(k, instant) {
    curAct = k;
    card.className = card.className.replace(/\bis-act\d+\b/g, '').replace(/\btone-\w+\b/g, '').trim() + ' is-act' + k + ' tone-' + call.acts[k].tone;
    card.querySelectorAll('.hc-ta').forEach((t, i) => { if (i === k) t.removeAttribute('aria-hidden'); else t.setAttribute('aria-hidden', 'true'); });
    tabs.forEach((b, i) => { b.classList.toggle('is-on', i === k); b.setAttribute('aria-pressed', i === k ? 'true' : 'false'); });
    fitTitles(instant);
  }
  function setButton() {
    const on = state === 'playing';
    playBtn.innerHTML = on ? HC_ICON_PAUSE : HC_ICON_PLAY;
    playBtn.setAttribute('aria-label', on ? (controls.pause || '') : (controls.play || ''));
  }
  function clearTimers() { timers.forEach(clearTimeout); timers = []; }
  function addPair(p) {
    const now = list.querySelector('.is-now'); if (now) now.classList.remove('is-now');
    const olds = Array.from(list.children);
    const pair = hcEl('div', 'hc-pair', hcPairHtml(call, p));
    list.insertBefore(pair, list.firstChild);
    const h = pair.offsetHeight + 14;
    olds.forEach(o => { o.style.transition = 'none'; o.style.transform = 'translateY(-' + h + 'px)'; });
    requestAnimationFrame(() => requestAnimationFrame(() => {
      olds.forEach(o => { o.style.transition = ''; o.style.transform = 'translateY(0)'; });
      pair.classList.add('is-in', 'is-now');
    }));
    timers.push(setTimeout(() => pair.classList.add('is-noted'), HC_NOTE_DELAY));
  }
  function turn(k) { list.classList.add('is-out'); pendingTurn = k; timers.push(setTimeout(finishTurn, HC_TURN_FADE)); }
  function finishTurn() { if (pendingTurn == null) return; const k = pendingTurn; pendingTurn = null; list.innerHTML = ''; setAct(k); drawBars(k); setProgress(0, 0); list.classList.remove('is-out'); }
  function actStart(k) {
    drawBars(k); setProgress(0, 0); void wave.offsetWidth;
    const a = plan.acts[k]; setProgress(1, a.end - a.start);
  }
  function finish() { const now = list.querySelector('.is-now'); if (now) now.classList.remove('is-now'); card.classList.add('is-done'); state = 'done'; setButton(); }
  function run(from) {
    startedAt = performance.now() - from;
    plan.steps.forEach(s => {
      if (s.t < from) return;
      const d = s.t - from;
      if (s.actStart != null) timers.push(setTimeout(() => actStart(s.actStart), d));
      else if (s.pair) timers.push(setTimeout(() => addPair(s.pair), d));
      else if (s.turn != null) timers.push(setTimeout(() => turn(s.turn), d));
      else timers.push(setTimeout(finish, d));
    });
  }
  function play() {
    clearTimers(); pendingTurn = null;
    card.classList.remove('is-done'); list.innerHTML = ''; list.classList.remove('is-out');
    setAct(0); drawBars(0); setProgress(0, 0);
    state = 'playing'; setButton(); run(0);
  }
  function pause() {
    if (state !== 'playing') return;
    elapsed = performance.now() - startedAt; clearTimers(); finishTurn();
    list.querySelectorAll('.hc-pair').forEach(p => p.classList.add('is-noted'));
    setProgress(liveProgress(), 0);
    state = 'paused'; setButton();
  }
  function resume() {
    if (state !== 'paused') return;
    state = 'playing'; setButton();
    const a = plan.acts[curAct];
    if (elapsed >= a.start && elapsed < a.end) setProgress(1, a.end - elapsed);
    run(elapsed);
  }
  function showFinished(k) {
    clearTimers(); pendingTurn = null;
    if (k == null) k = call.acts.length - 1;
    list.classList.remove('is-out'); list.innerHTML = ''; setAct(k); drawBars(k);
    call.acts[k].pairs.slice().reverse().forEach(p => list.appendChild(hcEl('div', 'hc-pair is-in is-noted', hcPairHtml(call, p))));
    setProgress(1, 0);
    card.classList.add('is-done'); state = 'done'; setButton();
  }
  playBtn.addEventListener('click', () => { awayPaused = false; if (state === 'playing') pause(); else if (state === 'paused') resume(); else play(); });
  tabs.forEach((b, i) => b.addEventListener('click', () => showFinished(i)));

  /* the card grows with each exchange; the row under it moves down with the lines (JC, 2026-11-09: the held
     height left white space under the card while the call played) */
  function onResize() {
    fitTitles(true);
    const live = state === 'playing' ? null : frac;
    drawn = ''; drawBars(curAct);
    if (live != null) setProgress(live, 0);
  }
  col.parentElement.style.position = 'relative';
  let rt = 0; const onWinResize = () => { clearTimeout(rt); rt = setTimeout(onResize, 150); };
  window.addEventListener('resize', onWinResize);
  if (document.fonts && document.fonts.ready) document.fonts.ready.then(onResize);

  setAct(0, true); drawBars(0); setProgress(0, 0);
  let io = null, offIo = null, awayPaused = false;
  /* reduced motion draws the next call finished; the other calls' exchanges are added as text only (clipped
     off screen, read by screen readers), so the page's snapshot carries both calls (JC, 2026-11-08) */
  function addStaticActs() {
    call.acts.slice(0, -1).forEach(act => {
      const s = hcEl('div', 'hc-static');
      s.appendChild(hcEl('div', 'hc-static-tab', hcEsc(act.tab)));
      act.pairs.forEach(p => s.appendChild(hcEl('div', 'hc-pair is-in is-noted', hcPairHtml(call, p))));
      card.appendChild(s);
    });
  }
  if (reduce.matches || !('IntersectionObserver' in window)) { card.classList.add('no-motion'); showFinished(); addStaticActs(); }
  else {
    io = new IntersectionObserver(entries => { entries.forEach(e => { if (e.isIntersecting && state === 'idle') { io.disconnect(); const go = () => timers.push(setTimeout(() => { if (state === 'idle') play(); }, 500)); if (document.fonts && document.fonts.ready) document.fonts.ready.then(go); else go(); } }); }, { threshold: 0.4 });
    io.observe(card);
    /* the call pauses when less than half the card is on screen and goes on when it comes back, so a visitor reading the
       sections below is not pushed down by exchanges arriving above them (JC, 2026-11-09). A pause the visitor
       made with the button stays a pause. */
    offIo = new IntersectionObserver(entries => { entries.forEach(e => {
      const away = !e.isIntersecting || e.intersectionRatio < 0.5;   /* less than half the card on screen: the visitor is reading the next block */
      if (away && state === 'playing') { pause(); awayPaused = true; }
      else if (!away && awayPaused && state === 'paused') { awayPaused = false; resume(); }
    }); }, { threshold: [0, 0.5] });
    offIo.observe(card);
  }
  if (!window.__hero) window.__hero = { play, pause, resume, showFinished, plan, card, state: () => state };   /* the first card on the page (the hero's) keeps the handle; the close card mounts the same component later */
  return () => { clearTimers(); clearTimeout(rt); window.removeEventListener('resize', onWinResize); if (io) io.disconnect(); if (offIo) offIo.disconnect(); card.remove(); };
}

const HC_CSS = `
.hero-card { margin-top: 62px; max-width: 760px; }
.hc { --chip-col: 196px; position: relative; background: var(--card); border: 1px solid var(--hairline); border-radius: var(--r-card); padding: 18px; font-size: 14px; line-height: 20px; color: var(--ink); display: flex; flex-direction: column; gap: 12px; }
.hc-tabs { display: flex; gap: 24px; border-bottom: 1px solid var(--hairline); margin: -4px 0 2px; }
.hc-tab { background: none; border: 0; border-bottom: 2px solid transparent; margin-bottom: -1px; padding: 6px 0 10px; font-family: inherit; font-size: 14px; line-height: 20px; font-weight: 500; color: var(--ink-2); cursor: pointer; transition: color var(--t-micro) var(--ease), border-color var(--t-micro) var(--ease); }
.hc-tab:hover { color: var(--ink); }
.hc-tab.is-on { color: var(--ink); border-bottom-color: var(--ink); }
.hc-titles { display: grid; min-width: 0; overflow: hidden; transition: height var(--t-fade) var(--ease); }
.hc-ta { grid-area: 1 / 1; align-self: start; opacity: 0; transition: opacity var(--t-fade) var(--ease); }
.hc.is-act0 .hc-ta0, .hc.is-act1 .hc-ta1 { opacity: 1; }
.hc-title { font-weight: 600; font-size: 15px; line-height: 21px; }
.hc-asub { margin-top: 2px; font-size: 13px; line-height: 18px; color: var(--ink-2); }
.hc-player { display: grid; grid-template-columns: 36px minmax(0, 1fr); gap: 14px; align-items: center; margin-bottom: 8px; }
.hc-play { width: 36px; height: 36px; border-radius: 50%; border: 0; padding: 0; background: var(--ink); color: #FFFFFF; display: grid; place-items: center; cursor: pointer; }
.hc-play:focus:not(:focus-visible) { outline: none; }
.hc-play svg { width: 12px; height: 12px; display: block; }
.hc.no-motion .hc-player { grid-template-columns: minmax(0, 1fr); }
.hc.no-motion .hc-play { display: none; }
.hc-wave { position: relative; height: 30px; }
.hc-bars { position: absolute; left: 0; top: 0; height: 30px; }
.hc-bars svg { display: block; height: 30px; }
.hc-grey rect { fill: var(--hairline); }
.hc-played { position: absolute; inset: 0; clip-path: inset(0 100% 0 0); will-change: clip-path; }
.hc-playhead { position: absolute; left: -1px; top: -3px; bottom: -3px; width: 2px; background: var(--ink); will-change: transform; }
.hc-lines { border-top: 1px solid var(--hairline); padding-top: 14px; }
.hc-list { display: flex; flex-direction: column; gap: 14px; transition: opacity var(--t-fade) var(--ease); }
.hc-list.is-out { opacity: 0; }
.hc-static { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; }
.hc-pair { position: relative; z-index: 1; background: var(--card); display: grid; grid-template-columns: 56px minmax(0, 1fr); gap: 8px; opacity: 0; transition: opacity var(--t-fade) var(--ease), transform var(--t-fade) var(--ease), color var(--t-std) var(--ease); }
.hc-pair.is-in { opacity: 1; }
.hc-at { font-family: var(--font-text); font-size: 13px; line-height: 20px; color: var(--ink-2); transition: color var(--t-std) var(--ease); }
.hc-ln + .hc-ln { margin-top: 6px; }
.hc-who { font-size: 13px; line-height: 18px; color: var(--ink-2); transition: color var(--t-std) var(--ease); }
.hc-ln.is-key .hc-text { font-weight: 600; }
.hc-row { display: grid; grid-template-columns: minmax(0, 1fr) var(--chip-col); gap: 4px 16px; align-items: start; }
.hc-note { justify-self: start; font-size: 13px; line-height: 18px; font-weight: 500; padding: 1px 9px; border-radius: var(--r-chip); white-space: nowrap; opacity: 0; transition: opacity var(--t-fade) var(--ease); }
.hc.tone-wrong .hc-note { color: var(--status-error); background: var(--status-error-bg); }
.hc.tone-right .hc-note { color: var(--status-ok); background: var(--status-ok-bg); }
.hc-pair.is-noted .hc-note { opacity: 1; }
@media (max-width: 899px) {
  .hero-card { margin-top: 57px; max-width: none; }
  .hc { padding: 16px; }
  .hc-row { grid-template-columns: 1fr; }
}
`;

function HeroCall({ call }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!ref.current || !call) return undefined;
    return hcMount(ref.current, call);
  }, [call]);
  return (
    <React.Fragment>
      <style>{HC_CSS}</style>
      <div className="hero-card" ref={ref}></div>
    </React.Fragment>
  );
}

Object.assign(window, { HeroCall });
