"use client";

import { createElement, useEffect, useRef } from "react";
import { gsap, ScrollTrigger, SplitText, prefersReducedMotion } from "./gsap-setup";

type RevealTextProps = {
  children: string;
  /** Element to render. Headings should pass their real level for the outline. */
  as?: "h1" | "h2" | "h3" | "p" | "span" | "div";
  className?: string;
  /** Line-level reveals suit display type; char-level suits short labels. */
  split?: "lines" | "chars";
  delay?: number;
  stagger?: number;
  /** ScrollTrigger start. Ignored when `immediate` is set. */
  start?: string;
  /** Play on mount instead of on scroll — used by the hero after the preloader. */
  immediate?: boolean;
  /** Hold the animation until this flips true (the preloader gate). */
  play?: boolean;
};

/**
 * Scroll- or mount-triggered text reveal built on GSAP SplitText.
 *
 * The full string is rendered as ordinary text on the server, so crawlers and
 * reduced-motion visitors read complete, un-split copy; the split only happens
 * after hydration. `autoSplit` re-splits when the webfont finishes loading,
 * which is what stops lines from being measured against the fallback face and
 * re-wrapping mid-animation.
 */
export default function RevealText({
  children,
  as = "div",
  className,
  split = "lines",
  delay = 0,
  stagger,
  start = "top 85%",
  immediate = false,
  play = true,
}: RevealTextProps) {
  const ref = useRef<HTMLElement>(null);

  useEffect(() => {
    const el = ref.current;
    if (!el || !play) return;
    if (prefersReducedMotion()) {
      gsap.set(el, { opacity: 1 });
      return;
    }

    const byChar = split === "chars";
    const step = stagger ?? (byChar ? 0.018 : 0.09);

    const ctx = gsap.context(() => {
      const instance = SplitText.create(el, {
        type: byChar ? "chars,words,lines" : "lines",
        // Wraps each part in an overflow-hidden element, so the type rises out
        // of a clean edge instead of overlapping whatever sits above it.
        mask: byChar ? "chars" : "lines",
        linesClass: "immersive-split-line",
        autoSplit: true,
        onSplit(self) {
          const targets = byChar ? self.chars : self.lines;
          gsap.set(el, { opacity: 1 });
          return gsap.from(targets, {
            yPercent: 115,
            duration: byChar ? 0.6 : 0.95,
            ease: "power3.out",
            stagger: step,
            delay,
            ...(immediate
              ? {}
              : { scrollTrigger: { trigger: el, start, once: true } }),
          });
        },
      });

      return () => instance.revert();
    }, ref);

    ScrollTrigger.refresh();
    return () => ctx.revert();
  }, [children, split, delay, stagger, start, immediate, play]);

  return createElement(
    as,
    {
      ref,
      className,
      // Hidden so the un-split text does not flash at full size before
      // SplitText measures it. The attribute is what the <noscript> rule in
      // app.tsx targets to put it back when there is no JS to reveal it.
      "data-reveal-text": "",
      style: { opacity: 0 },
      suppressHydrationWarning: true,
    },
    children
  );
}
