// Hooks de animação ao scroll
const { useState, useEffect, useRef } = React;

const useReveal = (threshold = 0.15) => {
  const ref = React.useRef(null);
  const [shown, setShown] = React.useState(false);
  React.useEffect(() => {
    if (!ref.current) return;
    const obs = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            setShown(true);
            obs.disconnect();
          }
        });
      },
      { threshold }
    );
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, [threshold]);
  return [ref, shown];
};

const Reveal = ({ children, delay = 0, y = 24, className = "", as: Tag = "div", style = {}, ...rest }) => {
  const [ref, shown] = useReveal();
  return (
    <Tag
      ref={ref}
      className={className}
      style={{
        opacity: shown ? 1 : 0,
        transform: shown ? "translateY(0)" : `translateY(${y}px)`,
        transition: `opacity 1.2s cubic-bezier(.22,.61,.36,1) ${delay}ms, transform 1.2s cubic-bezier(.22,.61,.36,1) ${delay}ms`,
        ...style,
      }}
      {...rest}
    >
      {children}
    </Tag>
  );
};

// RiseIn — máscara: o conteúdo nasce abaixo da linha e sobe até a posição final.
// Usa overflow:hidden no wrapper + translateY(110%→0) no filho.
const RiseIn = ({ children, delay = 0, duration = 1100, className = "", as: Tag = "span", style = {}, innerStyle = {}, ...rest }) => {
  const [ref, shown] = useReveal();
  return (
    <Tag
      ref={ref}
      className={className}
      style={{
        display: "inline-block",
        overflow: "hidden",
        verticalAlign: "bottom",
        ...style,
      }}
      {...rest}
    >
      <span style={{
        display: "inline-block",
        transform: shown ? "translateY(0)" : "translateY(110%)",
        transition: `transform ${duration}ms cubic-bezier(.22,.61,.36,1) ${delay}ms`,
        willChange: "transform",
        ...innerStyle,
      }}>
        {children}
      </span>
    </Tag>
  );
};

const useParallax = (factor = 0.15) => {
  const ref = React.useRef(null);
  React.useEffect(() => {
    let raf = null;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        if (ref.current) {
          const rect = ref.current.getBoundingClientRect();
          const center = rect.top + rect.height / 2;
          const off = (window.innerHeight / 2 - center) * factor;
          ref.current.style.transform = `translate3d(0, ${off}px, 0)`;
        }
        raf = null;
      });
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, [factor]);
  return ref;
};

window.useReveal = useReveal;
window.Reveal = Reveal;
window.RiseIn = RiseIn;
window.useParallax = useParallax;
