"use client";
import { cn } from "~/lib/utils";
import { motion, useInView } from "framer-motion";
import * as React from "react";

type TextStaggeredFadeProps = {
  text: string;
  className?: string;
  hide?: boolean;
};

export const StaggeredFade: React.FC<TextStaggeredFadeProps> = ({
  text,
  className = "",
  hide = false,
}) => {
  const variants = {
    hidden: { opacity: 0 },
    show: (i: number) => ({
      y: 0,
      opacity: 1,
      transition: { delay: i * 0.07 },
    }),
  };

  const letters = text.split("");
  const ref = React.useRef(null);
  const isInView = useInView(ref, { once: true });

  return (
    <motion.h2
      ref={ref}
      initial="hidden"
      animate={isInView ? (!hide ? "show" : "hidden") : ""}
      variants={variants}
      viewport={{ once: true }}
      className={cn(
        "text-center text-xl font-bold tracking-tighter md:leading-[4rem]",
        className,
      )}
    >
      {letters.map((word, i) => (
        <motion.span key={`${word}-${i}`} variants={variants} custom={i}>
          {word}
        </motion.span>
      ))}
    </motion.h2>
  );
};
