// Spine — a single continuous golden thread that runs down the right edge of
// the page from section 02 through 05, morphing shape as you scroll:
//   02  chaos squiggle     (market pressure)
//   03  three parallel     (pillars)
//   04  ladder rungs       (performance)
//   05  perfect circle     (capability wheel)
//
// One fixed SVG, 4 path states, crossfaded by scroll progress.

function Spine() {
  const [progress, setProgress] = React.useState(0);     // 0..4 (which section we're in)
  const [stops, setStops] = React.useState(null);        // { y0, y02, y03, y04, y05, y05end }
  const [headY, setHeadY] = React.useState(0.5);         // 0..1 within viewport

  // Measure section tops on mount + resize
  React.useEffect(() => {
    function measure() {
      const s02 = document.getElementById('pressure');
      const s03 = document.getElementById('system');
      const s04 = document.getElementById('ladder');
      const s05 = document.getElementById('capabilities');
      if (!s02 || !s03 || !s04 || !s05) return;
      const off = (el) => el.getBoundingClientRect().top + window.scrollY;
      const next = {
        y02: off(s02),
        y03: off(s03),
        y04: off(s04),
        y05: off(s05),
        y05end: off(s05) + s05.offsetHeight,
      };
      setStops(next);
    }
    measure();
    window.addEventListener('resize', measure);
    // Re-measure once images / layout settle.
    const t1 = setTimeout(measure, 500);
    const t2 = setTimeout(measure, 1500);
    return () => {
      window.removeEventListener('resize', measure);
      clearTimeout(t1); clearTimeout(t2);
    };
  }, []);

  // Track scroll → progress
  React.useEffect(() => {
    if (!stops) return;
    function onScroll() {
      const y = window.scrollY + window.innerHeight * 0.55;
      // Piecewise: 02 → 03 → 04 → 05 → end. Each segment maps to 1.0 of progress.
      let p;
      if (y < stops.y02) p = 0;
      else if (y < stops.y03) p = (y - stops.y02) / (stops.y03 - stops.y02);
      else if (y < stops.y04) p = 1 + (y - stops.y03) / (stops.y04 - stops.y03);
      else if (y < stops.y05) p = 2 + (y - stops.y04) / (stops.y05 - stops.y04);
      else if (y < stops.y05end) p = 3 + (y - stops.y05) / (stops.y05end - stops.y05);
      else p = 4;
      setProgress(p);
      // The head dot tracks scroll position within the viewport (very subtle).
      setHeadY(0.5);
    }
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, [stops]);

  // Show/hide envelope. Hide before 02 and after 05.
  const visible = progress > 0 && progress < 4;

  // Crossfade weights for each of the 4 states (squiggle / pillars / rungs / circle)
  function w(stateIdx) {
    // Triangle peak at stateIdx, zero at ±1 away
    const d = Math.abs(progress - 0.5 - stateIdx);
    return Math.max(0, 1 - d);
  }

  return (
    <div className={"spine-shell" + (visible ? " spine-shell--on" : "")} aria-hidden="true">
      <svg viewBox="0 0 100 800" preserveAspectRatio="none" className="spine-svg">
        <defs>
          <linearGradient id="spine-grad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%"   stopColor="#FFBA00" stopOpacity="0.2"/>
            <stop offset="20%"  stopColor="#FFBA00" stopOpacity="1"/>
            <stop offset="80%"  stopColor="#FFBA00" stopOpacity="1"/>
            <stop offset="100%" stopColor="#FFBA00" stopOpacity="0.2"/>
          </linearGradient>
          <filter id="spine-glow" x="-50%" y="-10%" width="200%" height="120%">
            <feGaussianBlur stdDeviation="2.5" result="b"/>
            <feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
          </filter>
        </defs>

        {/* State A — chaos squiggle (02 Market Pressure) */}
        <path
          d="M 50 0 C 30 60, 70 110, 40 160 S 80 250, 45 320 S 30 420, 55 480 S 80 570, 50 640 S 35 720, 50 800"
          stroke="url(#spine-grad)"
          strokeWidth="2.2"
          fill="none"
          filter="url(#spine-glow)"
          style={{ opacity: w(0), transition: 'opacity 600ms ease' }}
        />

        {/* State B — three parallel pillars (03 OS) */}
        <g style={{ opacity: w(1), transition: 'opacity 600ms ease' }} filter="url(#spine-glow)">
          <path d="M 30 0 L 30 800" stroke="url(#spine-grad)" strokeWidth="2"/>
          <path d="M 50 0 L 50 800" stroke="url(#spine-grad)" strokeWidth="2.4"/>
          <path d="M 70 0 L 70 800" stroke="url(#spine-grad)" strokeWidth="2"/>
        </g>

        {/* State C — ladder rungs (04 Performance Ladder) */}
        <g style={{ opacity: w(2), transition: 'opacity 600ms ease' }} filter="url(#spine-glow)">
          <path d="M 38 0 L 38 800" stroke="url(#spine-grad)" strokeWidth="1.8"/>
          <path d="M 62 0 L 62 800" stroke="url(#spine-grad)" strokeWidth="1.8"/>
          {/* Rungs */}
          {[60, 180, 300, 420, 540, 660].map((y, i) => (
            <line key={i} x1="32" y1={y} x2="68" y2={y} stroke="#FFBA00" strokeWidth="2.4" strokeLinecap="round"/>
          ))}
        </g>

        {/* State D — coiled circle (05 Capability Wheel) */}
        <g style={{ opacity: w(3), transition: 'opacity 600ms ease' }} filter="url(#spine-glow)">
          <path
            d="M 50 50 C 78 50, 92 70, 92 100 C 92 130, 78 150, 50 150
               C 22 150, 8 170, 8 200 C 8 230, 22 250, 50 250
               C 78 250, 92 270, 92 300 C 92 330, 78 350, 50 350
               C 22 350, 8 370, 8 400
               L 8 750"
            stroke="url(#spine-grad)"
            strokeWidth="2.2"
            fill="none"
            strokeDasharray="0 0"
          />
          {/* Final closed loop at the bottom */}
          <circle cx="50" cy="640" r="80" stroke="#FFBA00" strokeWidth="2" fill="none" opacity="0.8"/>
          <circle cx="50" cy="640" r="60" stroke="#FFBA00" strokeWidth="1.2" fill="none" opacity="0.5"/>
          <circle cx="50" cy="640" r="40" stroke="#FFBA00" strokeWidth="0.8" fill="none" opacity="0.3"/>
        </g>
      </svg>

      {/* The "head" — a glowing dot that always sits at the user's eye-line */}
      <div className="spine-head" style={{ top: (headY * 100) + 'vh' }}>
        <div className="spine-head-dot"></div>
        <div className="spine-head-ring"></div>
        <div className="spine-head-label">
          {progress < 1 ? '02 · PRESSURE' :
           progress < 2 ? '03 · SYSTEM'   :
           progress < 3 ? '04 · LADDER'   :
                          '05 · MAP'}
        </div>
      </div>
    </div>
  );
}

window.Spine = Spine;
