/* journify.ai — Sally: the mushroom in the corner, one offer (spec: _ops/2026-10-10-rebrand/loud-design/
   journify-loud.html; rules: journify/brand/README.md section 1, Sally). She stays still and nods for about 3
   seconds every 9 seconds, and on mouse-over; reduced motion keeps her still. Her bubble opens by itself at
   the top (openAtTop) and when the last section (lastSection, an id) comes on screen, never on a phone, and
   a click on her opens or closes it from then on. Under 900px (the page's one breakpoint since 2026-11-10; 760px
   before) she is 60px wide and shows only once the visitor
   has scrolled 80% of a screen, so she never covers the hero buttons (JC, 2026-11-08). The drawing is the file images/logos/sally.svg, a copy of
   journify/brand/logo/sally.svg. Words: content/nav.json sally. */

const SALLY_CSS = `
.sally { position: fixed; z-index: 15; right: max(12px, env(safe-area-inset-right, 0px)); bottom: calc(12px + env(safe-area-inset-bottom, 0px)); display: flex; align-items: flex-end; gap: 6px; pointer-events: none; }
.sally-bubble { pointer-events: auto; width: 216px; background: var(--card); color: var(--ink); border: 1px solid var(--hairline); border-radius: var(--r-card); padding: 12px 14px; font-size: 15px; line-height: 1.35; margin-bottom: 20px; transition: opacity 250ms, visibility 250ms; }
.sally-bubble p { margin: 0; }
.sally-bubble .j-cta { height: 36px; padding: 0 12px; font-size: 14px; margin-top: 10px; }
.sally-bubble.is-off { opacity: 0; visibility: hidden; pointer-events: none; }
.sally-btn { pointer-events: auto; background: none; border: 0; padding: 0; cursor: pointer; width: clamp(86px, 9vw, 104px); aspect-ratio: 220 / 232; flex: none; }
.sally-btn svg { display: block; width: 100%; height: auto; overflow: visible; }
.sally.is-away { visibility: hidden; opacity: 0; }
@media (max-width: 899px) {
  .sally { transition: opacity 250ms, visibility 250ms; }
  .sally-btn { width: 60px; }
}
@media (prefers-reduced-motion: no-preference) {
  .sally-btn { transition: transform 200ms; }
  .sally-btn:hover { transform: translateY(-4px) rotate(-2deg); }
}
@media (prefers-reduced-motion: reduce) { .sally-bubble { transition: none; } }
@media print { .sally { display: none; } }
`;

function Sally({ openAtTop, lastSection }) {
  const [words, setWords] = React.useState(null);
  const [open, setOpen] = React.useState(false);
  const [away, setAway] = React.useState(false);
  const clicked = React.useRef(false), host = React.useRef(null);

  React.useEffect(() => {
    fetch('/content/nav.json').then(r => r.json()).then(d => setWords(d.sally));
  }, []);

  /* the bubble follows the page until the first click */
  React.useEffect(() => {
    const check = () => {
      setAway(window.innerWidth < 900 && window.scrollY < window.innerHeight * 0.8);
      if (clicked.current) return;
      const last = document.getElementById(lastSection);
      setOpen(window.innerWidth >= 900 && ((openAtTop && window.scrollY < window.innerHeight * 0.5) || (!!last && last.getBoundingClientRect().top < window.innerHeight * 0.7)));
    };
    check();
    window.addEventListener('scroll', check, { passive: true });
    window.addEventListener('resize', check);
    return () => { window.removeEventListener('scroll', check); window.removeEventListener('resize', check); };
  }, [openAtTop, lastSection, words]);

  /* the nod: rotates the group sally-head and slides sally-glasses down her nose */
  React.useEffect(() => {
    if (!words) return undefined;
    let raf = 0, gone = false, t0 = 0;
    const btn = host.current, restart = () => { t0 = performance.now() / 1000; };
    fetch('/images/logos/sally.svg').then(r => r.text()).then(svg => {
      if (gone) return;
      btn.innerHTML = svg;
      btn.querySelector('svg').setAttribute('viewBox', '0 0 220 232');
      btn.querySelector('svg').setAttribute('aria-hidden', 'true');
      if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
      const head = btn.querySelector('#sally-head'), glass = btn.querySelector('#sally-glasses');
      btn.addEventListener('pointerenter', restart);
      const frame = ms => {
        const t = ms / 1000 - t0, ph = t % 9, env = ph < 3.4 ? Math.sin(Math.PI * ph / 3.4) : 0;
        head.setAttribute('transform', 'rotate(' + (Math.sin(t * 7) * 4 * Math.min(1, env * 3)).toFixed(2) + ' 110 216)');
        glass.setAttribute('transform', 'translate(0 ' + (Math.min(1, env * 1.7) * 11).toFixed(1) + ')');
        raf = requestAnimationFrame(frame);
      };
      raf = requestAnimationFrame(frame);
    });
    return () => { gone = true; cancelAnimationFrame(raf); btn.removeEventListener('pointerenter', restart); };
  }, [words]);

  if (!words) return null;
  return (
    <div className={'sally' + (away ? ' is-away' : '')}>
      <style>{SALLY_CSS}</style>
      <div className={'sally-bubble' + (open ? '' : ' is-off')}>
        <p>{words.line}</p>
        <a className="j-cta j-cta--warm" href={words.cta.href}>{words.cta.label}</a>
      </div>
      <button ref={host} type="button" className="sally-btn" aria-label={words.toggle} aria-expanded={open}
        onClick={() => { clicked.current = true; setOpen(o => !o); }} />
    </div>
  );
}

Object.assign(window, { Sally });
