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

/**
 * Custom hook for sliding number animations
 * Detects direction of change and provides digit-level animation data
 *
 * @example
 * ```tsx
 * const { displayValue, direction, digits } = useSlidingNumber({
 *   value: count,
 *   enabled: true,
 *   formatNumber: (n) => n.toFixed(2)
 * });
 *
 * return (
 *   <div>
 *     {digits.map((digit, i) => (
 *       <motion.span
 *         key={i}
 *         animate={{ y: digit.isChanging ? [10, 0] : 0 }}
 *       >
 *         {digit.value}
 *       </motion.span>
 *     ))}
 *   </div>
 * );
 * ```
 */
const defaultFormatNumber = (n) => n.toString();
const useSlidingNumber = ({ value, enabled = true, formatNumber = defaultFormatNumber, }) => {
    const [displayValue, setDisplayValue] = useState(formatNumber(value));
    const [direction, setDirection] = useState(0);
    const prevValueRef = useRef(value);
    useEffect(() => {
        const prevValue = prevValueRef.current;
        const newDisplayValue = formatNumber(value);
        // Determine direction
        if (value > prevValue) {
            setDirection(1);
        }
        else if (value < prevValue) {
            setDirection(-1);
        }
        else {
            setDirection(0);
        }
        setDisplayValue(newDisplayValue);
        prevValueRef.current = value;
    }, [value, formatNumber]);
    // Split display value into individual digits for animation
    const digits = useMemo(() => displayValue.split('').map((char, index) => {
        // Check if this digit changed from previous value
        const prevDisplay = formatNumber(prevValueRef.current);
        const isChanging = enabled && prevDisplay[index] !== char;
        return {
            value: char,
            isChanging,
        };
    }), [displayValue, enabled, formatNumber]);
    return {
        displayValue,
        direction,
        digits,
    };
};

export { useSlidingNumber };
