"use client";

import { useEffect, useRef, useState } from "react";
import { cn } from "@/lib/cn";

interface RevealProps {
  children: React.ReactNode;
  className?: string;
  /** Stagger, in ms, for items revealed as a group. */
  delay?: number;
}

/** If the observer never fires, show the content anyway. */
const FAILSAFE_MS = 4000;

/**
 * Fades content up as it scrolls into view.
 *
 * Visible is the default state — it is what the server renders and what a client
 * with no JS keeps. Content is only hidden once the browser has confirmed it sits
 * below the fold and an observer is watching it, and a timer reveals it even if that
 * observer never fires. An animation must not be able to strand the page's content,
 * which is the whole substance of this page.
 */
export function Reveal({ children, className, delay = 0 }: RevealProps) {
  const ref = useRef<HTMLDivElement>(null);
  const [hidden, setHidden] = useState(false);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;

    // Anything already on screen stays on screen: no flash, nothing to lose.
    if (el.getBoundingClientRect().top < window.innerHeight * 0.92) return;

    setHidden(true);
    const show = () => setHidden(false);

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          show();
          observer.disconnect();
        }
      },
      { rootMargin: "0px 0px -8% 0px" }
    );
    observer.observe(el);

    const failsafe = setTimeout(show, FAILSAFE_MS);
    return () => {
      observer.disconnect();
      clearTimeout(failsafe);
    };
  }, []);

  return (
    <div
      ref={ref}
      style={{ transitionDelay: `${delay}ms` }}
      className={cn("reveal", hidden && "reveal-hidden", className)}
    >
      {children}
    </div>
  );
}
