import { useInView } from "motion/react";
import { useRef, useEffect, useState } from "react";

export default function TypingEffect({ text = 'Typing Effect', speed = 0.1 }: { text: string, speed?: number }) {
    const ref = useRef<HTMLHeadingElement>(null);
    const isInView = useInView(ref, { once: true });
    const [visibleChars, setVisibleChars] = useState(0);
    
    // Split text into lines
    const lines = text.split('\n');
    
    useEffect(() => {
        if (!isInView) return;
        
        let currentIndex = 0;
        const totalChars = text.replace(/\n/g, '').length;
        
        const interval = setInterval(() => {
            if (currentIndex < totalChars) {
                currentIndex++;
                setVisibleChars(currentIndex);
            } else {
                clearInterval(interval);
            }
        }, speed * 1000);
        
        return () => clearInterval(interval);
    }, [isInView, text, speed]);
    
    // Build visible text based on visible characters
    let charsProcessed = 0;
    const visibleLines: string[] = [];
    
    for (const line of lines) {
        const lineLength = line.length;
        if (charsProcessed + lineLength <= visibleChars) {
            // Full line is visible
            visibleLines.push(line);
            charsProcessed += lineLength;
        } else {
            // Partial line
            const remainingChars = visibleChars - charsProcessed;
            if (remainingChars > 0) {
                visibleLines.push(line.slice(0, remainingChars));
            }
            break;
        }
    }

    return (
        <div className="relative max-h-full h-full overflow-hidden">
            <h2
                ref={ref}
                className="text-sm text-left font-mono text-base-content/70 tracking-tighter absolute bottom-0"
            >
                {visibleLines.map((line, index) => (
                    <div key={index}>
                        {line}
                        {index < visibleLines.length - 1 && <br />}
                    </div>
                ))}
            </h2>
        </div>
    );
}