"use client";

import { useRef, type ReactNode } from "react";
import { motion, useScroll, useTransform, type MotionValue } from "framer-motion";

interface ParallaxProps {
  children: ReactNode;
  /** how far the element moves at the end of its scroll range, in % of its own height */
  range?: number;
  className?: string;
}

/**
 * Scroll-linked vertical parallax wrapper.
 * Element drifts upward as it enters the viewport.
 */
export function Parallax({ children, range = 12, className }: ParallaxProps) {
  const ref = useRef<HTMLDivElement>(null);
  const { scrollYProgress } = useScroll({
    target: ref,
    offset: ["start end", "end start"],
  });
  const y = useTransform(scrollYProgress, [0, 1], [`${range}%`, `-${range}%`]);

  return (
    <motion.div ref={ref} style={{ y }} className={className}>
      {children}
    </motion.div>
  );
}

/** Scroll-linked subtle scale-in. */
export function useParallax(value: MotionValue<number>, distance: number) {
  return useTransform(value, [0, 1], [-distance, distance]);
}
