"use client";

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

interface ScrollRevealProps {
  children: ReactNode;
  className?: string;
  direction?: "up" | "down" | "left" | "right";
  delay?: number;
  distance?: number;
}

export function ScrollReveal({
  children,
  className = "",
  direction = "up",
  delay = 0,
  distance = 50,
}: ScrollRevealProps) {
  const ref = useRef<HTMLDivElement>(null);
  const { scrollYProgress } = useScroll({
    target: ref,
    offset: ["start end", "end start"],
  });

  const springConfig = { stiffness: 100, damping: 30, mass: 0.5 };
  const smoothProgress = useSpring(scrollYProgress, springConfig);

  const directions = {
    up: { initial: distance, animate: 0 },
    down: { initial: -distance, animate: 0 },
    left: { initial: distance, animate: 0 },
    right: { initial: -distance, animate: 0 },
  };

  const { initial, animate } = directions[direction];
  const isVertical = direction === "up" || direction === "down";

  const y = useTransform(
    smoothProgress,
    [0, 1],
    isVertical ? [initial, animate] : [0, 0]
  );
  const x = useTransform(
    smoothProgress,
    [0, 1],
    !isVertical ? [initial, animate] : [0, 0]
  );
  const opacity = useTransform(smoothProgress, [0, 0.3, 0.7, 1], [0, 1, 1, 0.8]);
  const scale = useTransform(smoothProgress, [0, 0.5, 1], [0.9, 1, 0.98]);

  return (
    <motion.div
      ref={ref}
      style={{ y, x, opacity, scale }}
      className={className}
      initial={{ opacity: 0, y: isVertical ? initial : 0, x: !isVertical ? initial : 0 }}
      whileInView={{ opacity: 1, y: 0, x: 0 }}
      viewport={{ once: false, margin: "-100px" }}
      transition={{ duration: 0.8, delay, ease: [0.16, 1, 0.3, 1] }}
    >
      {children}
    </motion.div>
  );
}






