/* ============================================================
   TEND, LIVE COMPASS
   The signature interaction. A Compass whose needle eases
   toward a target. Used by the Partnership Path section.
   Built on the canonical renderer (window.TENDCompass).
   ============================================================ */
const { useState: useStateLC, useEffect: useEffectLC, useRef: useRefLC, useCallback: useCallbackLC } = React;

/* Smoothly animate a compass's four energies toward a moving target.
   Returns { ref, setTarget, getVals }. The ref mounts the SVG. */
function useAnimatedCompass(initial, opts = {}) {
  const ref = useRefLC(null);
  const vals = useRefLC({ ...initial });
  const target = useRefLC({ ...initial });
  const raf = useRefLC(null);
  const optsRef = useRefLC(opts);
  optsRef.current = opts;

  const draw = useCallbackLC(() => {
    if (ref.current && window.TENDCompass) {
      const o = optsRef.current;
      ref.current.innerHTML = window.TENDCompass.render({
        ...vals.current,
        size: o.size || 360,
        style: o.style || 'field',
        theme: o.theme || 'light',
        labels: o.labels !== false,
        hints: o.hints !== false,
        idSeed: o.idSeed || 'lc',
      });
    }
  }, []);

  useEffectLC(() => {
    const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const tick = () => {
      const v = vals.current, t = target.current;
      const ease = reduce ? 1 : 0.085;
      let moved = false;
      for (const k of ['aqua', 'coral', 'amber', 'violet']) {
        const d = (t[k] - v[k]);
        if (Math.abs(d) > 0.05) { v[k] += d * ease; moved = true; }
        else v[k] = t[k];
      }
      if (moved) draw();
      raf.current = requestAnimationFrame(tick);
    };
    draw();
    raf.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf.current);
  }, [draw]);

  const setTarget = useCallbackLC((next) => { target.current = { ...target.current, ...next }; }, []);
  return { ref, setTarget, getVals: () => vals.current };
}

/* ---- Cursor-reactive hero compass --------------------------
   Drifts toward the pointer; settles to a base bearing at rest. */
function LiveCompass({ base = { aqua: 72, coral: 40, amber: 26, violet: 48 }, size = 420, style = 'field', theme = 'light', trackSelector }) {
  const { ref, setTarget } = useAnimatedCompass(base, { size, style, theme, idSeed: 'hero', labels: false });
  const wrapRef = useRefLC(null);

  useEffectLC(() => {
    const surface = trackSelector ? document.querySelector(trackSelector) : wrapRef.current;
    if (!surface) return;
    const onMove = (e) => {
      const r = (wrapRef.current || surface).getBoundingClientRect();
      const cx = r.left + r.width / 2, cy = r.top + r.height / 2;
      const dx = Math.max(-1, Math.min(1, (e.clientX - cx) / (window.innerWidth * 0.5)));
      const dy = Math.max(-1, Math.min(1, (e.clientY - cy) / (window.innerHeight * 0.5)));
      const amt = 34;
      setTarget({
        aqua: base.aqua + Math.max(0, -dy) * amt,
        amber: base.amber + Math.max(0, dy) * amt,
        coral: base.coral + Math.max(0, dx) * amt,
        violet: base.violet + Math.max(0, -dx) * amt,
      });
    };
    const onLeave = () => setTarget(base);
    surface.addEventListener('mousemove', onMove);
    surface.addEventListener('mouseleave', onLeave);
    return () => { surface.removeEventListener('mousemove', onMove); surface.removeEventListener('mouseleave', onLeave); };
  }, [base, setTarget, trackSelector]);

  return <div ref={wrapRef} style={{ display: 'inline-flex', lineHeight: 0 }} aria-hidden="true"><div ref={ref} /></div>;
}

/* ---- Six-question widget (no longer on the home page) ---- */
const BEARING_ITEMS = [
  { t: 'Before I commit to a plan, I want to explore the possibilities.', e: 'aqua' },
  { t: 'I push for momentum and drive the team toward the outcome.', e: 'coral' },
  { t: 'I prefer clear structure and dependable routines.', e: 'amber' },
  { t: 'I read how people are feeling before I act.', e: 'violet' },
  { t: 'I change direction readily when a better idea appears.', e: 'aqua' },
  { t: 'I hold the standard and finish what I start.', e: 'amber' },
];
const ENERGY_READ = {
  aqua:  { name: 'Aqua',  who: 'the Imaginative Collaborator', line: 'In these answers you led with openness and curiosity. At work that often shows up as noticing a shift early and asking the question nobody has asked yet.' },
  coral: { name: 'Coral', who: 'the Driving Achiever',        line: 'In these answers you led with drive and warmth. At work that often shows up as getting a stalled group moving and keeping people with you while you do.' },
  amber: { name: 'Amber', who: 'the Practical Organiser',     line: 'In these answers you led with structure and reliability. At work that often shows up as turning a loose idea into a plan people can follow, and keeping to it.' },
  violet:{ name: 'Violet',who: 'the Supportive Harmoniser',   line: 'In these answers you led with care and depth. At work that often shows up as noticing how people are really doing before the agenda moves on.' },
};

function Bearing({ size = 320, onComplete }) {
  const base = { aqua: 26, coral: 26, amber: 26, violet: 26 };
  const { ref, setTarget, getVals } = useAnimatedCompass(base, { size, style: 'field', idSeed: 'bearing' });
  const [i, setI] = useStateLC(0);
  const [scores, setScores] = useStateLC({ aqua: 26, coral: 26, amber: 26, violet: 26 });
  const [done, setDone] = useStateLC(false);

  const answer = (agree) => {
    const item = BEARING_ITEMS[i];
    const next = { ...scores, [item.e]: Math.max(8, Math.min(96, scores[item.e] + agree * 13)) };
    setScores(next);
    setTarget(next);
    if (i + 1 >= BEARING_ITEMS.length) { setTimeout(() => setDone(true), 240); }
    else setI(i + 1);
  };
  const restart = () => { const b = { aqua: 26, coral: 26, amber: 26, violet: 26 }; setScores(b); setTarget(b); setI(0); setDone(false); };

  const top = Object.keys(scores).reduce((a, b) => scores[a] >= scores[b] ? a : b);
  const read = ENERGY_READ[top];

  return (
    <div className="bearing">
      <div className="bearing-compass">
        <div ref={ref} />
        {!done && (
          <div className="bearing-progress" aria-hidden="true">
            {BEARING_ITEMS.map((_, n) => <span key={n} className={'bp-dot' + (n <= i ? ' on' : '')} />)}
          </div>
        )}
      </div>
      <div className="bearing-panel">
        {!done ? (
          <>
            <div className="eyebrow no-rule">Question {i + 1} of {BEARING_ITEMS.length}</div>
            <p className="bearing-stmt">{BEARING_ITEMS[i].t}</p>
            <div className="bearing-scale">
              {[
                ['Strongly disagree', -2], ['Disagree', -1], ['Neutral', 0], ['Agree', 1], ['Strongly agree', 2],
              ].map(([lbl, v]) => (
                <button key={lbl} className="bearing-btn" onClick={() => answer(v)}>
                  <span className="bb-mark" />
                  <span className="bb-lbl">{lbl}</span>
                </button>
              ))}
            </div>
            <p className="caption" style={{ marginTop: 18 }}>Answer the way you usually are at work, on an ordinary day.</p>
          </>
        ) : (
          <div className="bearing-read">
            <div className="eyebrow no-rule" style={{ '--energy-core': `var(--${top}-core)` }}>Your result</div>
            <h3 className="display-m" style={{ color: `var(--${top}-deep)` }}>You led with {read.name} in these answers.</h3>
            <p className="body" style={{ marginTop: 12 }}><span className="serif-italic">{read.who}.</span> {read.line}</p>
            <div className="tag-row" style={{ marginTop: 20 }}>
              <span className="pill" style={{ '--energy-core': `var(--${top}-core)` }}><span className="dot" />{read.name} led</span>
            </div>
            <div style={{ display: 'flex', gap: 12, marginTop: 26, flexWrap: 'wrap' }}>
              <a className="btn btn-accent" href="packages.html#prices" style={{ background: `var(--${top}-deep)`, borderColor: `var(--${top}-deep)` }}>See TEND Heading and TEND Direction</a>
              <button className="btn btn-ghost" onClick={restart}>Answer again</button>
            </div>
            <p className="caption" style={{ marginTop: 18 }}>TEND Heading and TEND Direction read the ten aspects of the Big Five, with checks on how consistently you answered.</p>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { useAnimatedCompass, LiveCompass, Bearing, BEARING_ITEMS, ENERGY_READ });
