/* global React */
const { useEffect, useRef, useState } = React;

window.useReveal = function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("in");
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.12, rootMargin: "0px 0px -8% 0px" }
    );
    el.querySelectorAll(".reveal").forEach((n) => io.observe(n));
    return () => io.disconnect();
  }, []);
  return ref;
};

window.useScrollExperience = function useScrollExperience() {
  useEffect(() => {
    let frame = 0;
    const update = () => {
      frame = 0;
      const max = Math.max(1, document.documentElement.scrollHeight - window.innerHeight);
      const progress = Math.min(1, Math.max(0, window.scrollY / max));
      document.documentElement.style.setProperty("--scroll", progress.toFixed(4));
      document.documentElement.style.setProperty("--hero-shift", `${Math.round(window.scrollY * 0.08)}px`);
    };
    const onScroll = () => {
      if (!frame) frame = requestAnimationFrame(update);
    };
    update();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      if (frame) cancelAnimationFrame(frame);
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
    };
  }, []);
};

window.SectionHead = function SectionHead({ num, title, titleEm, meta }) {
  return (
    <header className="section__head">
      <div className="section__num">{num}</div>
      <h2 className="section__title reveal">
        {title}{titleEm && <> <em>{titleEm}</em></>}
      </h2>
      {meta && <div className="section__meta">{meta}</div>}
    </header>
  );
};

window.useClock = function useClock() {
  const [t, setT] = useState(() => new Date());
  useEffect(() => {
    const id = setInterval(() => setT(new Date()), 1000);
    return () => clearInterval(id);
  }, []);
  return t;
};
