// useActivePhase — scroll + click + keyboard driver for PipelineAnatomy.
// - Sticky-section scroll: phase advances as the user scrolls through section.
// - Click: jump to phase (smooth scroll within the section).
// - Keyboard: arrow keys move between phases when section is focused.
// - Reduced motion: no autoplay; plain tab click.

function useActivePhase({ sectionRef, phaseCount }) {
  const { React } = window;
  const { useState, useEffect, useCallback } = React;
  const [active, setActive] = useState(0);
  const [selectedAgent, setSelectedAgent] = useState(null);
  const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  useEffect(() => {
    if (reduce) return;
    const onScroll = () => {
      const el = sectionRef.current; if (!el) return;
      const rect = el.getBoundingClientRect();
      const vh = window.innerHeight;
      // progress: 0 when top of section hits top, 1 when bottom of section hits bottom
      const total = el.offsetHeight - vh;
      const scrolled = Math.max(0, -rect.top);
      const p = Math.max(0, Math.min(1, total > 0 ? scrolled / total : 0));
      const idx = Math.min(phaseCount - 1, Math.floor(p * phaseCount));
      setActive(idx);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
    };
  }, [sectionRef, phaseCount, reduce]);

  const jumpTo = useCallback((idx) => {
    setActive(idx); setSelectedAgent(null);
    const el = sectionRef.current; if (!el || reduce) return;
    const vh = window.innerHeight;
    const total = el.offsetHeight - vh;
    const target = el.offsetTop + (idx / phaseCount) * total + 4;
    window.scrollTo({ top: target, behavior: 'smooth' });
  }, [sectionRef, phaseCount, reduce]);

  useEffect(() => {
    const onKey = (e) => {
      if (!document.activeElement || !document.activeElement.closest('[data-pipeline]')) return;
      if (e.key === 'ArrowRight') { e.preventDefault(); jumpTo(Math.min(phaseCount - 1, active + 1)); }
      if (e.key === 'ArrowLeft')  { e.preventDefault(); jumpTo(Math.max(0, active - 1)); }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [active, jumpTo, phaseCount]);

  return { active, setActive: jumpTo, selectedAgent, setSelectedAgent, reduce };
}
window.useActivePhase = useActivePhase;
