"use client";
import { useRef, useCallback } from "react";
import { useMotionValue, useSpring, useTransform } from "framer-motion";

export function useMouseTilt(intensity = 7) {
  const ref = useRef<HTMLDivElement>(null);

  const rawX = useMotionValue(0);
  const rawY = useMotionValue(0);

  const cfg = { stiffness: 300, damping: 28, mass: 0.6 };
  const rotateX = useSpring(useTransform(rawY, [-0.5, 0.5], [ intensity, -intensity]), cfg);
  const rotateY = useSpring(useTransform(rawX, [-0.5, 0.5], [-intensity,  intensity]), cfg);
  const glareX  = useSpring(useTransform(rawX, [-0.5, 0.5], [0, 100]), cfg);
  const glareY  = useSpring(useTransform(rawY, [-0.5, 0.5], [0, 100]), cfg);

  const onMouseMove = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
    if (!ref.current) return;
    const { left, top, width, height } = ref.current.getBoundingClientRect();
    rawX.set((e.clientX - left) / width  - 0.5);
    rawY.set((e.clientY - top)  / height - 0.5);
  }, [rawX, rawY]);

  const onMouseLeave = useCallback(() => {
    rawX.set(0);
    rawY.set(0);
  }, [rawX, rawY]);

  return { ref, rotateX, rotateY, glareX, glareY, onMouseMove, onMouseLeave };
}
