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

function useMouseTracking({ containerRef, enabled = true, stiffness = 150, damping = 25, maxOffset = 6, }) {
    const shouldReduceMotion = useReducedMotion();
    const rawX = useMotionValue(0);
    const rawY = useMotionValue(0);
    const x = useSpring(rawX, { stiffness, damping });
    const y = useSpring(rawY, { stiffness, damping });
    const handleMouseMove = useCallback((e) => {
        const el = containerRef.current;
        if (!el)
            return;
        const rect = el.getBoundingClientRect();
        const centerX = rect.left + rect.width / 2;
        const centerY = rect.top + rect.height / 2;
        // Normalize to -1..1 range based on distance from center
        const nx = Math.max(-1, Math.min(1, (e.clientX - centerX) / (rect.width / 2)));
        const ny = Math.max(-1, Math.min(1, (e.clientY - centerY) / (rect.height / 2)));
        rawX.set(nx * maxOffset);
        rawY.set(ny * maxOffset);
    }, [containerRef, rawX, rawY, maxOffset]);
    useEffect(() => {
        if (!enabled || shouldReduceMotion) {
            rawX.set(0);
            rawY.set(0);
            return;
        }
        window.addEventListener('mousemove', handleMouseMove);
        return () => window.removeEventListener('mousemove', handleMouseMove);
    }, [enabled, shouldReduceMotion, handleMouseMove, rawX, rawY]);
    return { x, y };
}

export { useMouseTracking };
