"use client"

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

export const CountUp = ({ start = 0, end, step = 1, duration = 2000 }) => {
    const [count, setCount] = useState(start);
    const countUpRef = useRef(null);
    const [isVisible, setIsVisible] = useState(false);

    useEffect(() => {
        const observer = new IntersectionObserver(
            ([entry]) => {
                if (entry.isIntersecting) {
                    setIsVisible(true);
                    observer.unobserve(entry.target);
                }
            },
            { threshold: 0.5 } // وقتی حداقل ۵۰٪ کامپوننت در viewport بود، فعال شود
        );

        if (countUpRef.current) {
            observer.observe(countUpRef.current);
        }

        return () => {
            if (countUpRef.current) {
                observer.unobserve(countUpRef.current);
            }
        };
    }, []);

    useEffect(() => {
        if (!isVisible) return;

        let animationFrame;
        let startTime;

        const totalSteps = Math.abs(end - start) / step;
        const stepDuration = duration / totalSteps;

        const animate = (timestamp) => {
            if (!startTime) startTime = timestamp;
            const progress = timestamp - startTime;
            const stepsCompleted = Math.floor(progress / stepDuration);
            const nextValue = start + (stepsCompleted * step * (start < end ? 1 : -1));

            if ((start < end && nextValue >= end) || (start > end && nextValue <= end)) {
                setCount(end);
            } else {
                setCount(nextValue);
                animationFrame = requestAnimationFrame(animate);
            }
        };

        animationFrame = requestAnimationFrame(animate);

        return () => {
            if (animationFrame) {
                cancelAnimationFrame(animationFrame);
            }
        };
    }, [isVisible, start, end, step, duration]);

    return <span ref={countUpRef}>{count.toLocaleString()}</span>;
};