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

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

// Helper function to properly split text including emojis
const splitTextWithEmojis = (text: string): string[] => {
	// Use Intl.Segmenter if available (modern browsers)
	if (typeof Intl !== "undefined" && Intl.Segmenter) {
		const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
		return Array.from(segmenter.segment(text), (segment) => segment.segment);
	}

	return Array.from(
		text.matchAll(
			/\p{Extended_Pictographic}|\p{Emoji_Component}|\p{Emoji_Modifier}|\p{Emoji_Modifier_Base}|\p{Emoji_Presentation}|./gu,
		),
	).map((match) => match[0]);
};

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

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

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