import {
  type MotionValue,
  useScroll,
  useSpring,
  useTransform,
} from "framer-motion";

import { defaultSpring } from "@/helpers/animation";

function useParallax(
  target: React.RefObject<HTMLElement>,
  distance: string | number,
  smooth: boolean = false,
): MotionValue {
  const { scrollYProgress: nativeScrollYProgress } = useScroll({
    target,
    offset: ["start start", "end start"],
  });
  const springYProgress = useSpring(nativeScrollYProgress, defaultSpring);
  const scrollYProgress = smooth ? springYProgress : nativeScrollYProgress;
  return useTransform(
    scrollYProgress,
    [0, 1],
    [typeof distance === "number" ? 0 : "0%", distance],
  );
}

export default useParallax;
