import { useCallback, useRef } from 'react';
import { useOnEnter } from '@/site/hooks/use-in-view';
import { motionEnabled } from '@/site/lib/scroll-engine';

type CounterProps = {
    value: number;
    /** Count-up duration in milliseconds. */
    duration?: number;
    className?: string;
};

/**
 * Counts up to `value` the first time it scrolls into view. The server
 * renders the final number, so it is correct without JavaScript; the
 * animation writes to the DOM node directly (no React renders per frame).
 */
export function Counter({ value, duration = 1400, className }: CounterProps) {
    const ref = useRef<HTMLSpanElement>(null);

    const run = useCallback(() => {
        const el = ref.current;

        if (!el || !motionEnabled()) {
            return;
        }

        const started = performance.now();

        const tick = (now: number) => {
            const t = Math.min(1, (now - started) / duration);
            const eased = 1 - Math.pow(1 - t, 4);

            el.textContent = String(Math.round(value * eased));

            if (t < 1) {
                requestAnimationFrame(tick);
            }
        };

        requestAnimationFrame(tick);
    }, [value, duration]);

    useOnEnter(ref, run);

    return (
        <span ref={ref} className={className}>
            {value}
        </span>
    );
}
