const { useEffect: useFX } = React;

function ScrollProgress() {
  useFX(() => {
    const bar = document.getElementById("scroll-progress");
    if (!bar) return;
    const fn = () => {
      const max = document.body.scrollHeight - window.innerHeight;
      bar.style.width = max > 0 ? (window.scrollY / max * 100) + "%" : "0%";
    };
    window.addEventListener("scroll", fn, { passive: true });
    return () => window.removeEventListener("scroll", fn);
  }, []);
  return null;
}

function ScrollReveal() {
  useFX(() => {
    const SEL = ".sr-fade,.sr-clip,.sr-skew,.sr-left,.sr-right,.sr-scale,.sr-blur,.sr-line,[data-stagger-parent]";
    const THRESHOLD = 0.92;

    const check = () => {
      const vh = window.innerHeight;
      document.querySelectorAll(SEL).forEach(el => {
        if (el.classList.contains("in")) return;
        const { top } = el.getBoundingClientRect();
        if (top < vh * THRESHOLD) {
          el.classList.add("in");
          if (el.hasAttribute("data-stagger-parent")) {
            el.querySelectorAll("[data-stagger],[data-stagger-h]").forEach((c, i) => {
              setTimeout(() => c.classList.add("in"), i * 90);
            });
          }
        }
      });
    };

    // run immediately + on every scroll + on resize
    const t = setTimeout(check, 100);
    window.addEventListener("scroll", check, { passive: true });
    window.addEventListener("resize", check, { passive: true });

    return () => {
      clearTimeout(t);
      window.removeEventListener("scroll", check);
      window.removeEventListener("resize", check);
    };
  }, []);
  return null;
}

function HeroParallax() {
  useFX(() => {
    const img = document.querySelector("#top img");
    if (!img) return;
    const fn = () => { img.style.transform = `translateY(${window.scrollY * 0.28}px)`; };
    window.addEventListener("scroll", fn, { passive: true });
    return () => window.removeEventListener("scroll", fn);
  }, []);
  return null;
}

function SectionTracker() {
  useFX(() => {
    const label = document.getElementById("section-label");
    if (!label) return;
    const sections = () => document.querySelectorAll("[data-screen-label]");
    const fn = () => {
      let cur = "";
      sections().forEach(s => {
        if (s.getBoundingClientRect().top < window.innerHeight * 0.6) cur = s.dataset.screenLabel;
      });
      if (cur && label.textContent !== cur) {
        label.style.opacity = "0";
        label.style.transform = "translateY(6px)";
        setTimeout(() => {
          label.textContent = cur;
          label.style.opacity = "1";
          label.style.transform = "translateY(0)";
        }, 180);
      }
    };
    window.addEventListener("scroll", fn, { passive: true });
    setTimeout(fn, 600);
    return () => window.removeEventListener("scroll", fn);
  }, []);
  return null;
}

function AnimatedNumber({ target, suffix = "", duration = 1400 }) {
  const [val, setVal] = React.useState(0);
  const ref = React.useRef(null);
  const started = React.useRef(false);
  useFX(() => {
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting && !started.current) {
        started.current = true;
        const t0 = performance.now();
        const tick = now => {
          const t = Math.min((now - t0) / duration, 1);
          setVal(Math.round((1 - Math.pow(1 - t, 4)) * target));
          if (t < 1) requestAnimationFrame(tick);
        };
        requestAnimationFrame(tick);
      }
    }, { threshold: 0.5 });
    if (ref.current) io.observe(ref.current);
    return () => io.disconnect();
  }, [target, duration]);
  return <span ref={ref} className="tnum">{val}{suffix}</span>;
}

window.ScrollProgress = ScrollProgress;
window.ScrollReveal = ScrollReveal;
window.HeroParallax = HeroParallax;
window.SectionTracker = SectionTracker;
window.AnimatedNumber = AnimatedNumber;
