import { useRef, useCallback, useEffect } from 'react';
import { useMotionValue, useSpring } from 'motion/react';

/**
 * Returns a MotionValue representing eyelid close amount (0 = open, 1 = closed).
 * Fires periodic natural blinks when enabled.
 */
function useBlink({ enabled = true, minInterval = 2000, maxInterval = 5000, } = {}) {
    const raw = useMotionValue(0);
    const blink = useSpring(raw, { stiffness: 600, damping: 30 });
    const timeoutRef = useRef(undefined);
    const doBlink = useCallback(() => {
        // Close eyes
        raw.set(1);
        // Open after 120ms
        setTimeout(() => raw.set(0), 120);
    }, [raw]);
    const scheduleNext = useCallback(() => {
        const delay = minInterval + Math.random() * (maxInterval - minInterval);
        timeoutRef.current = setTimeout(() => {
            if (enabled) {
                doBlink();
                scheduleNext();
            }
        }, delay);
    }, [enabled, minInterval, maxInterval, doBlink]);
    useEffect(() => {
        if (!enabled) {
            raw.set(0);
            return;
        }
        scheduleNext();
        return () => {
            if (timeoutRef.current)
                clearTimeout(timeoutRef.current);
        };
    }, [enabled, scheduleNext, raw]);
    return blink;
}

export { useBlink };
