// Reusable bits

function Reveal({ children, delay = 0, as: As = "div", className = "", style = {} }) {
  const ref = React.useRef(null);
  const playedRef = React.useRef(false);

  React.useEffect(() => {
    const el = ref.current;
    if (!el || playedRef.current) return;

    const reduced = typeof window !== "undefined"
      && window.matchMedia
      && window.matchMedia("(prefers-reduced-motion: reduce)").matches;

    const play = () => {
      if (playedRef.current) return;
      playedRef.current = true;
      if (reduced) {
        el.style.opacity = "1";
        return;
      }
      // Web Animations API — bypasses CSS-transition flake entirely
      el.animate(
        [
          { opacity: 0, transform: "translateY(16px)" },
          { opacity: 1, transform: "translateY(0)" },
        ],
        {
          duration: 700,
          delay,
          easing: "cubic-bezier(0.2, 0.6, 0.2, 1)",
          fill: "forwards",
        }
      );
    };

    const rect = el.getBoundingClientRect();
    const inView = rect.top < window.innerHeight * 0.95 && rect.bottom > 0;
    if (inView) {
      requestAnimationFrame(play);
      return;
    }

    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          play();
          io.disconnect();
        }
      });
    }, { threshold: 0.12, rootMargin: "0px 0px -8% 0px" });
    io.observe(el);
    return () => io.disconnect();
  }, [delay]);

  return (
    <As ref={ref} className={className} style={{ opacity: 0, ...style }}>
      {children}
    </As>
  );
}

function Eyebrow({ children, color }) {
  return (
    <div className="eyebrow" style={{ display: "flex", alignItems: "center", gap: 10 }}>
      <span style={{
        width: 18, height: 1, background: color || "var(--orange)", display: "inline-block"
      }} />
      <span>{children}</span>
    </div>
  );
}

function SectionTitle({ pre, italic, post, size = 88 }) {
  return (
    <h2 style={{
      fontSize: size,
      lineHeight: 1.02,
      letterSpacing: "-0.025em",
      fontWeight: 500,
      maxWidth: 14 + "ch",
    }}>
      {pre}{" "}
      <span className="serif-italic" style={{ color: "var(--orange-deep)" }}>{italic}</span>
      {post}
    </h2>
  );
}

function Arrow({ size = 14 }) {
  return (
    <svg className="arrow" width={size} height={size} viewBox="0 0 14 14" fill="none">
      <path d="M2 7h10M8 3l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

window.Reveal = Reveal;
window.Eyebrow = Eyebrow;
window.SectionTitle = SectionTitle;
window.Arrow = Arrow;
