import { useRef } from 'react';
import type { CSSProperties, ElementType } from 'react';
import { useScene } from '@/site/hooks/use-scene';

type TextRevealProps = {
    text: string;
    as?: ElementType;
    /** Viewport fraction where the first word starts to light up. */
    start?: number;
    /** Viewport fraction where the last word is fully lit. */
    end?: number;
    className?: string;
};

/**
 * A statement whose words light up one after another as it scrolls through
 * the viewport. The text is ordinary, fully readable content: without
 * motion every word is simply at full opacity.
 */
export function TextReveal({
    text,
    as: Tag = 'p',
    start = 0.88,
    end = 0.38,
    className,
}: TextRevealProps) {
    const ref = useRef<HTMLElement>(null);
    const words = text.split(/\s+/).filter(Boolean);

    useScene(ref, { mode: 'view', start, end });

    return (
        <Tag
            ref={ref}
            data-scene="view"
            data-text-reveal=""
            className={className}
            style={{ '--words': words.length } as CSSProperties}
        >
            {words.map((word, index) => (
                <span key={index} style={{ '--i': index } as CSSProperties}>
                    {word}
                    {index < words.length - 1 ? ' ' : ''}
                </span>
            ))}
        </Tag>
    );
}
