// useScrollSequence — drives a progress value 0..1 based on scroll-into-view
// of a sectionRef, or manual scrubber override. State A/B/C is derived.
//
// A: 0.00 – 0.18
// B: 0.18 – 0.48
// C: 0.48 – 1.00

function useScrollSequence({ sectionRef }) {
  const { React } = window;
  const { useEffect, useState, useRef, useCallback } = React;
  const [progress, setProgress] = useState(0);
  const [manual, setManual] = useState(null); // null = drive from scroll
  const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  useEffect(() => {
    if (manual !== null) return;
    if (reduce) { setProgress(1); return; }
    const onScroll = () => {
      const el = sectionRef.current; if (!el) return;
      const rect = el.getBoundingClientRect();
      const vh = window.innerHeight;
      const total = el.offsetHeight - vh;
      if (total <= 0) { setProgress(0); return; }
      const scrolled = Math.max(0, -rect.top);
      setProgress(Math.max(0, Math.min(1, scrolled / total)));
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
    };
  }, [sectionRef, manual, reduce]);

  const p = manual !== null ? manual : progress;
  const state = p < 0.18 ? 'A' : p < 0.48 ? 'B' : 'C';

  // Within-state progress (0..1 inside A/B/C)
  let localP;
  if      (state === 'A') localP = p / 0.18;
  else if (state === 'B') localP = (p - 0.18) / (0.48 - 0.18);
  else                    localP = (p - 0.48) / (1   - 0.48);
  localP = Math.max(0, Math.min(1, localP));

  const scrub = useCallback((v) => setManual(v), []);
  const clearScrub = useCallback(() => setManual(null), []);

  return { progress: p, state, localP, scrub, clearScrub, isManual: manual !== null, reduce };
}
window.useScrollSequence = useScrollSequence;
