'use client';

import React, { useEffect, useRef } from 'react';
import { motion, useInView, useAnimation, Variants } from 'framer-motion';

interface RevealProps {
  children: React.ReactNode;
  width?: 'fit-content' | '100%';
  delay?: number;
  className?: string;
  direction?: 'up' | 'down' | 'left' | 'right' | 'none';
  scale?: number;
  blur?: boolean;
}

export const Reveal: React.FC<RevealProps> = ({
  children,
  width = 'fit-content',
  delay = 0.25,
  className = "",
  direction = 'up',
  scale = 1,
  blur = false
}) => {
  const ref = useRef(null);
  const isInView = useInView(ref, { once: true, margin: "-10%" });
  const mainControls = useAnimation();

  useEffect(() => {
    if (isInView) {
      mainControls.start("visible");
    }
  }, [isInView, mainControls]);

  const getDirectionOffset = () => {
    switch (direction) {
      case 'up': return { y: 20 };
      case 'down': return { y: -20 };
      case 'left': return { x: 20 };
      case 'right': return { x: -20 };
      default: return {};
    }
  };

  const variants: Variants = {
    hidden: {
      opacity: 0,
      ...getDirectionOffset(),
      scale: scale !== 1 ? scale : 0.99,
      rotateX: direction === 'up' ? 2 : direction === 'down' ? -2 : 0,
      rotateY: direction === 'left' ? -2 : direction === 'right' ? 2 : 0,
    },
    visible: {
      opacity: 1,
      y: 0,
      x: 0,
      scale: 1,
      rotateX: 0,
      rotateY: 0,
    },
  };

  return (
    <div
      ref={ref}
      style={{
        position: "relative",
        width,
        perspective: "1000px"
      }}
      className={className}
    >
      <motion.div
        variants={variants}
        initial="hidden"
        animate={mainControls}
        style={{ transformStyle: "preserve-3d" }}
        transition={{
          duration: 0.8,
          delay: delay,
          type: "spring",
          stiffness: 70,
          damping: 24,
          mass: 1,
          opacity: { duration: 0.5, ease: [0.16, 1, 0.3, 1] }
        }}
      >
        {children}
      </motion.div>
    </div>
  );
};
