"use client";

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

type Props = {
  children: ReactNode;
  /** Pixels travelled by the end of `range`. Positive = drifts down. */
  distance?: number;
  /** Pixels of page scroll over which the movement happens. */
  range?: number;
  className?: string;
};

/**
 * Slow drift on a hero background as the page scrolls away from it.
 *
 * Reads the raw page scroll rather than measuring its own position: this is
 * only ever used at the top of a document, and measuring an element that is
 * itself being transformed feeds its own output back into the input.
 */
export function Parallax({
  children,
  distance = 90,
  range = 700,
  className,
}: Props) {
  const reduced = useReducedMotion();
  const { scrollY } = useScroll();
  const y = useTransform(scrollY, [0, range], [0, distance], { clamp: true });

  if (reduced) {
    return <div className={className}>{children}</div>;
  }

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