"use client";
import { motion, useSpring, useMotionValue, useTransform } from "framer-motion";
import { ReactNode, useRef, useCallback } from "react";
import { useMotionContext } from "./MotionProvider";

interface TiltCardProps {
  children: ReactNode;
  className?: string;
  style?: React.CSSProperties;
  intensity?: number;
  onClick?: React.MouseEventHandler<HTMLDivElement>;
}

export function TiltCard({
  children,
  className,
  style,
  intensity = 6,
  onClick,
}: TiltCardProps) {
  const { reducedMotion } = useMotionContext();
  const ref = useRef<HTMLDivElement>(null);

  const rawX = useMotionValue(0);
  const rawY = useMotionValue(0);
  const scale = useMotionValue(1);

  const cfg = { stiffness: 300, damping: 26, mass: 0.5 };
  const rotateX = useSpring(useTransform(rawY, [-0.5, 0.5], [ intensity, -intensity]), cfg);
  const rotateY = useSpring(useTransform(rawX, [-0.5, 0.5], [-intensity,  intensity]), cfg);
  const smoothScale = useSpring(scale, { stiffness: 400, damping: 30 });

  const onMouseMove = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
    if (!ref.current || reducedMotion) return;
    const { left, top, width, height } = ref.current.getBoundingClientRect();
    rawX.set((e.clientX - left) / width  - 0.5);
    rawY.set((e.clientY - top)  / height - 0.5);
  }, [rawX, rawY, reducedMotion]);

  const onMouseEnter = useCallback(() => { scale.set(1.02); }, [scale]);
  const onMouseLeave = useCallback(() => {
    rawX.set(0); rawY.set(0); scale.set(1);
  }, [rawX, rawY, scale]);

  const onMouseDown = useCallback(() => { scale.set(0.985); }, [scale]);
  const onMouseUp   = useCallback(() => { scale.set(1.02);  }, [scale]);

  if (reducedMotion) {
    return (
      <div className={className} style={style} onClick={onClick}>
        {children}
      </div>
    );
  }

  return (
    <motion.div
      ref={ref}
      className={className}
      style={{
        ...style,
        rotateX,
        rotateY,
        scale: smoothScale,
        transformStyle: "preserve-3d",
        transformPerspective: 800,
        willChange: "transform",
      }}
      onMouseMove={onMouseMove}
      onMouseEnter={onMouseEnter}
      onMouseLeave={onMouseLeave}
      onMouseDown={onMouseDown}
      onMouseUp={onMouseUp}
      onClick={onClick}
    >
      {children}
    </motion.div>
  );
}
