import { useState, useEffect, useRef } from 'react';

/**
 * 模拟打字机效果的 Hook
 * @param text 目标文本
 * @param speed 打字速度 (ms)
 * @returns 当前展示的文本
 */
export const useTypewriter = (text: string, speed: number = 20) => {
    const [displayedText, setDisplayedText] = useState('');
    const timerRef = useRef<NodeJS.Timeout>();
    const indexRef = useRef(0);

    useEffect(() => {
        // 重置状态
        setDisplayedText('');
        indexRef.current = 0;

        if (timerRef.current) clearInterval(timerRef.current);

        if (!text) return;

        timerRef.current = setInterval(() => {
            if (indexRef.current < text.length) {
                setDisplayedText((prev) => prev + text.charAt(indexRef.current));
                indexRef.current += 1;
            } else {
                clearInterval(timerRef.current);
            }
        }, speed);

        return () => clearInterval(timerRef.current);
    }, [text, speed]);

    return displayedText;
};
