// Shared scroll-progress hook for narrative-immersive sections.
// Returns 0–1 progress as the user scrolls a section through the viewport,
// where 0 = top edge of section just hit bottom of viewport,
// and 1 = bottom edge of section just left top of viewport.

function useScrollProgress(ref, opts = {}) {
  const [progress, setProgress] = React.useState(0);
  const { stickyMode = true } = opts;

  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let raf = 0;

    const measure = () => {
      raf = 0;
      const rect = el.getBoundingClientRect();
      const vh = window.innerHeight;
      let p;
      if (stickyMode) {
        // Progress through a tall section that contains a sticky child.
        // Range: section top reaches 0 → section bottom reaches vh
        const start = -rect.top;
        const total = rect.height - vh;
        p = total > 0 ? start / total : 0;
      } else {
        // Symmetric reveal: bottom-of-viewport entry → top-of-viewport exit
        const start = vh - rect.top;
        const total = vh + rect.height;
        p = start / total;
      }
      const clamped = Math.max(0, Math.min(1, p));
      setProgress(clamped);
    };

    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(measure);
    };

    measure();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      if (raf) cancelAnimationFrame(raf);
    };
  }, [ref, stickyMode]);

  return progress;
}

// Linear interpolation
function lerp(a, b, t) { return a + (b - a) * t; }

// Map x from [a,b] to [0,1], clamped
function norm(x, a, b) {
  if (b === a) return 0;
  const t = (x - a) / (b - a);
  return Math.max(0, Math.min(1, t));
}

// Easings
const ease = {
  out: (t) => 1 - Math.pow(1 - t, 3),
  inOut: (t) => t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2,
  outQuart: (t) => 1 - Math.pow(1 - t, 4),
};

window.useScrollProgress = useScrollProgress;
window.lerp = lerp;
window.norm = norm;
window.ease = ease;
