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

// IntersectionObserver hook for scroll-triggered reveals
const useReveal = (options = {}) => {
  const ref = useRef(null);
  const [inView, setInView] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const obs = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            setInView(true);
            obs.disconnect();
          }
        });
      },
      { threshold: 0.12, rootMargin: "0px 0px -8% 0px", ...options }
    );
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);
  return [ref, inView];
};

const Reveal = ({ children, stagger = false, as: Tag = "div", className = "", style = {}, ...rest }) => {
  const [ref, inView] = useReveal();
  const cls = [stagger ? "reveal-stagger" : "reveal", inView ? "is-in" : "", className].filter(Boolean).join(" ");
  return (
    <Tag ref={ref} className={cls} style={style} {...rest}>
      {children}
    </Tag>
  );
};

window.Reveal = Reveal;
window.useReveal = useReveal;
