/* journify.ai — HowItWorks: one grey panel held on screen while you scroll, the same component on the homepage,
   /the-sprint and /closed-call-sprint (spec: STEPS, STATIONS and pose() in _ops/2026-10-10-rebrand/loud-design/
   journify-loud.html; rules: journify/brand/README.md, Motion and section 2). HowItWorks({ data, view, link }):
   data is content/homepage.json s6, the only copy of these words; view names one entry of data.views, which
   chooses the stages and rows; link is an optional link under the rows. Every part of the panel reads one number,
   the scroll position; the recording in the canvas plays while the panel is on screen. Under reduced motion the
   recording stands still and the panel still follows the scroll. The DOM work runs in one useEffect. */

const HIW_CSS = `
.hiw-room { position: relative; height: 300vh; margin: 0 auto; max-width: 1176px; padding: 0 16px; }
.hiw-stick { position: sticky; top: calc(var(--nav) + 12px); height: calc(100vh - var(--nav) - 24px); min-height: 660px; overflow: hidden; border-radius: var(--r-block); background: var(--block); color: var(--ink); }
.hiw-cv { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
.hiw-text { position: relative; z-index: 1; padding: clamp(20px, 4vh, 40px) clamp(18px, 4vw, 48px) 0; }
.hiw-intro { margin: 6px 0 0; max-width: 620px; color: var(--ink-2); font-size: 15px; line-height: 1.6; }
.hiw-tabs { display: flex; gap: 22px; margin-top: 14px; border-bottom: 1px solid var(--hairline); }
.hiw-tabs button { font: inherit; font-size: 14px; background: none; border: 0; border-bottom: 2px solid transparent; margin-bottom: -1px; padding: 0 0 8px; color: var(--ink-2); cursor: pointer; white-space: nowrap; }
.hiw-tabs button.is-on { color: var(--ink); font-weight: 500; border-bottom-color: var(--ink); }
.hiw-short { display: none; }
.hiw-grid { display: grid; grid-template-columns: minmax(0, 5fr) minmax(0, 7fr); grid-template-rows: auto 1fr; gap: 0 48px; margin-top: 22px; }
.hiw-lead { grid-column: 1; grid-row: 2; }
.hiw-journey { grid-column: 2; grid-row: 1 / span 2; }
.hiw-days { margin: 0; font-size: 14px; font-weight: 600; color: var(--ink-2); }
.hiw-tag { margin: 2px 0 0; text-wrap: balance; font-size: clamp(21px, 2.6vw, 30px); font-weight: var(--w-heading); font-stretch: var(--stretch-display); line-height: 1.14; letter-spacing: -0.02em; }
.hiw-say { margin: 8px 0 0; color: var(--ink-2); font-size: 15px; line-height: 1.5; }
/* the card at the top of the column (JC, 2026-11-10: "this needs to go all the way to the top"): at Day 0 it carries
   the Before sentence, then the line for the row whose border just lit. Its border is a 2px band of flare, ember and
   oxblood that travels around the rectangle once every 4s, with a blurred copy behind it as the glow, so the eye
   has one still thing to read while the rows move. Reduced motion stops the travel. The card opens no stacking
   context of its own (no z-index), so the glow behind it paints under its white in .hiw-text's context. */
@property --hiw-a { syntax: '<angle>'; inherits: true; initial-value: 0deg; }
.hiw-now { --hiw-a: 0deg; position: relative; grid-column: 1; grid-row: 1; align-self: start; margin: 0 0 16px; padding: 10px 14px; max-width: 420px; color: var(--ink); font-size: 14px; line-height: 1.45; border: 2px solid transparent; border-radius: var(--r-control); background: linear-gradient(var(--ground), var(--ground)) padding-box, conic-gradient(from var(--hiw-a), var(--flare), var(--ember), var(--action), var(--ember), var(--flare)) border-box; animation: hiw-travel 4s linear infinite; }
.hiw-now > span { display: block; transition: opacity 220ms; }   /* only the words fade on a swap: fading the card would make it its own paint layer and put the glow over its white for 220ms (JC, 2026-11-10: "a glare inside the rectangle") */
.hiw-now::before { content: ''; position: absolute; inset: -3px; z-index: -1; border-radius: inherit; background: conic-gradient(from var(--hiw-a), var(--flare), var(--ember), var(--action), var(--ember), var(--flare)); filter: blur(9px); opacity: 0.4; }
@keyframes hiw-travel { to { --hiw-a: 360deg; } }
@media (prefers-reduced-motion: reduce) { .hiw-now { animation: none; } }
.hiw-s0 .hiw-say { display: none; }   /* at Day 0 the card says the Before sentence, so the column does not say it twice */
.hiw-chip { display: inline-flex; align-items: center; max-width: 170px; overflow: hidden; white-space: nowrap; border: 1px solid var(--hairline); border-radius: var(--r-chip); padding: 2px 8px; font-size: 13px; color: var(--ink); background: var(--ground); transition: background 300ms, color 300ms, border-color 300ms; }
.k0 .c0 { background: var(--status-error-bg); color: var(--status-error); border-color: var(--status-error-bg); }
.k0 .c1 { color: var(--status-error); border: 2px solid var(--status-error); border-radius: 2px; }
.k0 .c2 { color: var(--status-error); border: 1px dashed var(--status-error); }
/* folded: the one chip that stays reads the same on every row, the Offer row included, and the grey line moves up
   beside it, so the row is one line tall and uses the width the three chips left (JC, 2026-11-10) */
.k2 .hiw-chip { color: var(--ink); border: 1px solid var(--ink); font-weight: 600; }
.k2 .hiw-state, .k2 .hiw-note { flex: 1 1 160px; }
.hiw-journey { padding: 0 2px; min-width: 0; }
.hiw-st { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; min-height: 42px; padding: 5px 12px; border: 1px solid var(--hairline); border-radius: var(--r-control); margin-top: 5px; background: var(--ground); font-size: 14px; line-height: 1.3; transition: border-color 350ms; }
.hiw-st b { font-weight: 600; flex: none; min-width: 118px; }
.hiw-chips { display: inline-flex; align-items: center; gap: 6px; flex: none; }
.hiw-state, .hiw-note { color: var(--ink-2); font-size: 13px; flex: 1 1 100%; min-width: 0; }
.hiw-st.is-lit { border-color: var(--ember); }
.hiw-st.is-wait { opacity: 0.5; }
.hiw-more { display: inline-block; margin-top: 10px; font-size: 14px; }
@media (max-width: 899px) {
  .hiw-grid { grid-template-columns: minmax(0, 1fr); grid-template-rows: none; gap: 0; margin-top: 12px; }
  .hiw-lead, .hiw-journey, .hiw-now { grid-column: 1; grid-row: auto; }
  .hiw-journey { margin-top: 10px; }
  .hiw-now { margin: 0 0 12px; max-width: none; padding: 8px 12px; font-size: 13px; }
  .hiw-intro, .hiw-say, .hiw-note, .hiw-state { display: none; }
  .hiw-tabs { gap: 18px; }
  .hiw-tabs button { padding: 10px 0 12px; }  /* a 40px tap target */
  .hiw-long { display: none; }
  .hiw-short { display: inline; }
  .hiw-text .j-h2 { font-size: 24px; }
  .hiw-tag { font-size: 20px; }
  /* a phone has no room for a label and three chips on one line, so the chips sit under the label until the row
     folds, and the one chip left then fits beside it (JC, 2026-11-10) */
  .hiw-st { min-height: 30px; padding: 2px 9px; font-size: 12.5px; line-height: 1.2; margin-top: 3px; }
  .hiw-st b { min-width: 100px; }
  .hiw-chip { font-size: 12px; padding: 2px 6px; }
  .hiw-stick { min-height: 620px; height: calc(100svh - var(--nav) - 20px); }
}
/* a phone at least 740px tall has room for the stage sentence too; a shorter one keeps it out so the rows and the
   card fit the 620px panel */
@media (max-width: 899px) and (min-height: 740px) {
  .hiw-say { display: block; margin-top: 6px; font-size: 13px; }
}
`;

function hiwNz(a, b) { const x = Math.sin(a * 12.9898 + b * 78.233) * 43758.5453; return x - Math.floor(x); }
function hiwRamp(v, a, b) { return Math.max(0, Math.min(1, (v - a) / (b - a))); }
function hiwEase(v) { return v * v * (3 - 2 * v); }

function hiwMount(host, data, view, link) {
  const v = data.views[view], reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  const steps = v.stages.map(i => data.steps[i]);
  const room = host, stick = host.querySelector('.hiw-stick'), cv = host.querySelector('.hiw-cv'), ctx = cv.getContext('2d');
  const q = c => host.querySelector(c), tabs = q('.hiw-tabs'), journey = q('.hiw-journey'), grid = q('.hiw-grid');
  const days = q('.hiw-days'), tag = q('.hiw-tag'), say = q('.hiw-say'), now = q('.hiw-now > span');

  /* the offer row, on the views that have one */
  let offerEl = null, chips = [], offerName = null, offerNote = null;
  if (v.offer) {
    /* the same markup as a station row, so the kept chip sits at the same x on every row (JC, 2026-11-10: the Offer
       chip sat 20px left of the others once folded) */
    offerEl = document.createElement('div'); offerEl.className = 'hiw-st hiw-offer k0';
    offerEl.innerHTML = '<b>' + data.labels.offer + '</b><span class="hiw-chips">' + data.offers.map((o, i) =>
      '<span class="hiw-chip c' + i + '"><span>' + o.name + '</span></span>').join('') + '</span><span class="hiw-note"></span>';
    journey.appendChild(offerEl);
    chips = Array.from(offerEl.querySelectorAll('.hiw-chip'));
    offerName = chips[data.tested].querySelector('span'); offerNote = offerEl.querySelector('.hiw-note');
  }
  /* the rows the view chooses; i is the row's place in data.stations, which sets its timing */
  const rows = v.rows.map((i, k) => {
    const s = data.stations[i], el = document.createElement('div');
    /* three objects of the mess that fold into one (JC, 2026-11-10: every row gets objects like the Offer row), then
       one line that explains the stage */
    el.className = 'hiw-st k0'; el.innerHTML = '<b>' + s.label + '</b><span class="hiw-chips">' + (s.chips || []).map((c, j) =>
      '<span class="hiw-chip c' + j + '"><span>' + c + '</span></span>').join('') + '</span><span class="hiw-state"></span>';
    journey.appendChild(el);
    const rchips = Array.from(el.querySelectorAll('.hiw-chip'));
    return { i, k, s, el, rchips, name: rchips[1] ? rchips[1].querySelector('span') : null, shift: (s.shift || [0, 0]).map(x => x * (window.innerWidth < 900 ? 0.5 : 1)) };
  });
  if (link) { const a = document.createElement('a'); a.className = 'j-link-standalone hiw-more'; a.href = link.href; a.textContent = link.label; journey.appendChild(a); }
  /* the Offer row sits after the first offerPlace rows (JC, 2026-11-09: the diagram starts with the calls, and what
     the calls say changes the offer), so the lit order and the page order agree */
  const place = offerEl ? Math.min(data.offerPlace || 0, rows.length) : 0;
  if (offerEl && place > 0) journey.insertBefore(offerEl, rows[place] ? rows[place].el : null);
  const marks = rows.slice(0, place).map(r => r.el).concat(offerEl ? [offerEl] : [], rows.slice(place).map(r => r.el));
  /* when each row folds: the stage it folds in gives the turn, and rows that share a turn fold one after the
     other in the lit order, 0.05 apart, each over 0.13 (JC, 2026-11-10: the calls improve first, then the rest).
     The rows of the first turn start 0.04 before it; the rows of a later turn start 0.02 after it, once the stage
     is on screen. views[].jump lands each tab after its last fold, so a tab never opens on a half-folded row */
  const turnOf = fs => { const ti = v.stages.indexOf(fs) - 1; return ti >= 0 && v.turns[ti] != null ? v.turns[ti] : (ti < 0 && v.stages.length === 1 ? 2 : v.turns[v.turns.length - 1]); };
  const offerItem = { foldStage: 1 };
  const items = rows.slice(0, place).concat(offerEl ? [offerItem] : [], rows.slice(place));
  { const seen = {}; items.forEach(it => {
    if (it.s && v.faded && v.faded.indexOf(it.i) > -1) { it.foldAt = 1e9; return; }   /* a faded row is not this sprint's work and never folds (1e9, not Infinity: Infinity makes the ramp NaN, which reads as folded) */
    const tu = turnOf(it.s ? (it.s.foldStage || 1) : it.foldStage); const o = seen[tu] || 0; seen[tu] = o + 1; it.foldAt = tu + (tu === v.turns[0] ? -0.04 : 0.02) + 0.05 * o; }); }
  const FOLD = 0.13, PAD = window.innerWidth < 900 ? 6 : 8;
  const offerShift = (data.offerShift || [0, 0]).map(x => x * (window.innerWidth < 900 ? 0.5 : 1));
  const place2 = (el, sh, k) => { const l = sh[0] * (1 - k), r = sh[1] * (1 - k); el.style.marginLeft = l.toFixed(2) + '%'; el.style.marginRight = r.toFixed(2) + '%'; el.style.width = (100 - l - r).toFixed(2) + '%'; };
  /* the chip a folded row keeps: one phrase, or one per stage (the Sales calls row says "Every call reviewed" in
     the Booked Sprint and "A date or a clear no" in the Closed one) */
  const afterOf = (r, at) => { const a = r.s.after; if (!Array.isArray(a)) return a; for (let j = at; j >= 0; j--) if (a[j]) return a[j]; return a.filter(Boolean)[0] || ''; };
  /* one line on the left for the row whose border just turned orange (JC, 2026-11-10), in the same order as marks */
  const nows = rows.slice(0, place).map(r => r.s.now).concat(offerEl ? [data.offerNow] : [], rows.slice(place).map(r => r.s.now));
  let nowI = -2, nowT = 0;
  function setNow(i) {
    if (i === nowI) return; nowI = i; clearTimeout(nowT);
    const text = i < 0 ? steps[0].say : (nows[i] || '');
    if (reduce) { now.textContent = text; return; }
    now.style.opacity = '0'; nowT = setTimeout(() => { now.textContent = text; now.style.opacity = '1'; }, 220);
  }
  const stickTop = () => parseFloat(getComputedStyle(stick).top) || 0;
  const span = () => room.offsetHeight - stick.offsetHeight;

  steps.forEach((s, i) => {
    const b = document.createElement('button'); b.type = 'button';
    b.innerHTML = '<span class="hiw-long">' + s.tab + '</span><span class="hiw-short">' + s.short + '</span>';
    b.addEventListener('click', () => {
      const top = room.getBoundingClientRect().top + window.scrollY - stickTop();
      window.scrollTo({ top: top + span() * v.jump[i] / v.reach, behavior: reduce ? 'auto' : 'smooth' });
    });
    tabs.appendChild(b);
  });

  let step = -1;
  function setStep(i) {
    if (i === step) return; step = i; const s = steps[i], at = v.stages[i];
    days.textContent = v.days ? v.days[i] : s.days; tag.textContent = s.tag; say.textContent = s.say; host.classList.toggle('hiw-s0', i === 0);
    Array.from(tabs.children).forEach((b, j) => { b.className = j === i ? 'is-on' : ''; });
    rows.forEach(r => { r.el.querySelector('.hiw-state').textContent = r.s.states[at]; if (r.name && r.el.classList.contains('k2')) r.name.textContent = afterOf(r, at); });
    if (offerNote) offerNote.textContent = data.offerStates ? data.offerStates[at] : (at > 0 ? data.offerAfter.note : '');
  }
  setStep(0); setNow(-1);   /* the card has its Day 0 sentence before the first frame */

  /* every part of the panel reads one number, s, so it moves only while you scroll */
  function pose(s) {
    if (offerEl) {
      const a = hiwEase(hiwRamp(s, 0.06, offerItem.foldAt)), b = hiwEase(hiwRamp(s, offerItem.foldAt, offerItem.foldAt + FOLD));
      [[-3, -2], [2, 5], [-1.5, 0], [2.5, 3]].forEach((c, i) => { if (chips[i]) chips[i].style.transform = 'rotate(' + (c[0] * (1 - a)).toFixed(2) + 'deg) translateY(' + (c[1] * (1 - a)).toFixed(2) + 'px)'; });
      chips.filter((e, i) => i !== data.tested).forEach(e => { e.style.opacity = (1 - b).toFixed(3); e.style.maxWidth = (170 * (1 - b)).toFixed(1) + 'px'; e.style.paddingLeft = e.style.paddingRight = (PAD * (1 - b)).toFixed(1) + 'px'; e.style.borderWidth = b > 0.98 ? '0' : ''; });
      const kk = b < 0.5 ? 'k0' : 'k2';
      if (!offerEl.classList.contains(kk)) {
        offerEl.classList.remove('k0', 'k2'); offerEl.classList.add(kk);
        offerName.textContent = kk === 'k0' ? data.offers[data.tested].name : data.offerAfter.name;   /* folded, the chip says One offer, never one offer type (readers took "Coaching" for the answer, 2026-11-10) */
      }
    }
    if (offerEl) place2(offerEl, offerShift, hiwEase(hiwRamp(s, 0.1, 0.26)));
    rows.forEach(r => {
      if (r.rchips.length) {
        const b = hiwEase(hiwRamp(s, r.foldAt, r.foldAt + FOLD));
        r.rchips.filter((e, j) => j !== 1).forEach(e => { e.style.opacity = (1 - b).toFixed(3); e.style.maxWidth = (170 * (1 - b)).toFixed(1) + 'px'; e.style.paddingLeft = e.style.paddingRight = (PAD * (1 - b)).toFixed(1) + 'px'; e.style.borderWidth = b > 0.98 ? '0' : ''; });
        const kk = b < 0.5 ? 'k0' : 'k2';
        if (!r.el.classList.contains(kk)) { r.el.classList.remove('k0', 'k2'); r.el.classList.add(kk); if (r.name) r.name.textContent = kk === 'k2' ? afterOf(r, v.stages[Math.max(0, step)]) : r.s.chips[1]; }
      }
      const from = v.rowFrom ? v.rowFrom[r.k] : (r.i < 5 ? 0.08 + r.i * 0.03 : 0.52 + (r.i - 5) * 0.05);
      const k = hiwEase(hiwRamp(s, from, from + 0.16));
      /* Before, every row sits out of line on both sides by its own two insets (stations[].shift, left and right,
         in % of the column; JC, 2026-11-10: no row flush to an edge); After, every row spans the column */
      place2(r.el, r.shift, k);
      r.el.classList.toggle('is-wait', v.faded ? v.faded.indexOf(r.i) > -1 : (r.i >= 5 && s >= 0.3 && s < (v.turns[1] || 0.66) - 0.04));
    });
    let li = -1;
    marks.forEach((el, i) => { const lit = s >= (v.litAt ? v.litAt[i] : (i < 6 ? 0.1 + i * 0.075 : (v.turns[1] || 0.66) + (i - 6) * 0.13)); el.classList.toggle('is-lit', lit); if (lit) li = i; });
    setNow(li);
  }

  let W = 0, H = 0, dpr = 1;
  function size() { dpr = Math.min(window.devicePixelRatio || 1, 2); const r = cv.getBoundingClientRect(); W = r.width; H = r.height; cv.width = W * dpr; cv.height = H * dpr; }
  window.addEventListener('resize', size); size();
  let px = -1e4, ptr = 0;
  const onMove = e => { px = e.clientX - cv.getBoundingClientRect().left; ptr = 1; }, onLeave = () => { ptr = 0; };
  stick.addEventListener('pointermove', onMove); stick.addEventListener('pointerleave', onLeave);

  const ox = recRgb('--action'), ember = recRgb('--ember'), base = [205, 201, 197];
  const mix = (a, b, t) => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];
  let sm = 0, last = 0;
  function draw(t, p, ms) {
    const dt = Math.min(0.1, (ms - last) / 1000); last = ms;
    sm = reduce ? p : sm + (p - sm) * Math.min(1, dt * 12); if (Math.abs(p - sm) < 0.0005) sm = p;
    const s = sm * v.reach;
    let i = 0; while (i < v.turns.length && s >= v.turns[i]) i++; setStep(i); pose(s);
    const c = cv.getBoundingClientRect(), floor = H - 16, ceil = grid.getBoundingClientRect().bottom - c.top + 12;
    const cap = Math.max(26, (floor - ceil) / 2), cy = (floor + ceil) / 2;
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, W, H);
    /* Before: uneven and restless, heights glide between random values about 3 times a second, in loose clusters.
       After: one smooth wave passes slowly through all the bars. The height stays the same throughout */
    const gap = W < 620 ? 7 : 10, n = Math.ceil(W / gap), top = cap * 0.72, clock = (reduce ? 1 : t) * 3, tick = Math.floor(clock), fr = hiwEase(clock - tick);
    for (let j = 0; j < n; j++) {
      const x = j * gap + gap / 2, u = j / n, b = hiwEase(hiwRamp(sm, 0.06 + u * 0.62, 0.3 + u * 0.62));
      const fine = hiwNz(j, tick) * (1 - fr) + hiwNz(j, tick + 1) * fr, c6 = Math.floor(j / 6);
      const broad = hiwNz(c6, tick) * (1 - fr) + hiwNz(c6, tick + 1) * fr;
      const chaos = 0.08 + 0.86 * hiwEase(0.6 * broad + 0.4 * fine) * (0.66 + 0.34 * hiwNz(j, 3));
      const calm = 0.5 + 0.3 * Math.sin(u * Math.PI * 6 - t * (reduce ? 0 : 0.9));
      let h2 = (1 - b) * chaos + b * calm;
      if (ptr) { const d = Math.abs(x - px); if (d < 150) h2 = Math.min(1.12, h2 + (1 - d / 150) * (1 - d / 150) * 0.2); }
      const h = Math.max(1.5, top * h2), col = mix(mix(base, ox, Math.min(1, h2 * 1.8) * (0.5 + 0.5 * b) + 0.25 * b), ember, Math.max(0, (h2 - 0.62) * 2.4) * b);
      ctx.fillStyle = 'rgb(' + (col[0] | 0) + ',' + (col[1] | 0) + ',' + (col[2] | 0) + ')'; ctx.fillRect(x - 2, cy - h, 4, h * 2);
    }
  }
  const progress = () => Math.max(0, Math.min(1, (stickTop() - room.getBoundingClientRect().top) / span()));
  let raf = 0;
  function frame(ms) {
    const r = room.getBoundingClientRect();
    if (r.bottom > 0 && r.top < window.innerHeight) draw(ms / 1000, progress(), ms);
    if (!reduce) raf = requestAnimationFrame(frame);
  }
  const still = () => frame(1200);
  if (reduce) { window.addEventListener('scroll', still, { passive: true }); window.addEventListener('resize', still); }
  raf = requestAnimationFrame(frame);
  if (document.fonts && document.fonts.ready) document.fonts.ready.then(() => { size(); if (reduce) still(); });
  return () => {
    cancelAnimationFrame(raf); clearTimeout(nowT); window.removeEventListener('resize', size); window.removeEventListener('scroll', still); window.removeEventListener('resize', still);
    stick.removeEventListener('pointermove', onMove); stick.removeEventListener('pointerleave', onLeave);
    tabs.innerHTML = ''; journey.innerHTML = '';
  };
}

function HowItWorks({ data, view, link }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!ref.current || !data || !data.views) return undefined;
    return hiwMount(ref.current, data, view, link);
  }, [data, view, link]);
  /* a cached homepage.json from before the views existed draws nothing rather than crashing the page */
  if (!data || !data.views) return null;
  const intro = data.views[view].intro;
  return (
    <section id="how-it-works" data-screen-label="How it works" className="hiw-room" ref={ref}>
      <style>{HIW_CSS}</style>
      <div className="hiw-stick">
        <canvas className="hiw-cv" aria-hidden="true"></canvas>
        <div className="hiw-text">
          <h2 className="j-h2">{data.headline}</h2>
          {intro && <p className="hiw-intro">{intro}</p>}
          <div className="hiw-tabs"></div>
          <div className="hiw-grid">
            <p className="hiw-now"><span></span></p>
            <div className="hiw-lead"><p className="hiw-days"></p><p className="hiw-tag"></p><p className="hiw-say"></p></div>
            <div className="hiw-journey"></div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { HowItWorks });
