"use client";

import { ReactElement, useRef, useEffect } from "react";

interface Props {
  step: number;
  boundry: number;
  className?: string;
  children: ReactElement;
}

export function InteractiveContainer({
  step,
  boundry,
  className,
  children,
}: Props) {
  const divRef = useRef<HTMLDivElement>(null);

  const handleMouseMove = (e: MouseEvent) => {
    if (!divRef.current) return;

    const cursorX = e.clientX;
    const cursorY = e.clientY;

    const rect = divRef.current.getBoundingClientRect();
    const halfWidth = rect.width / 2;
    const halfHeight = rect.height / 2;

    const centerX = rect.left + halfWidth;
    const centerY = rect.top + halfHeight;

    const normalizedX = (cursorX - centerX) / halfWidth;
    const normalizedY = (cursorY - centerY) / halfHeight;

    const divX = Math.max(Math.min(normalizedX * step, boundry), -boundry);
    const divY = Math.max(Math.min(normalizedY * step, boundry), -boundry);

    divRef.current.style.transform = `perspective(1000px) translate3d(${divX}px, ${divY}px, 0px)`;
  };

  useEffect(() => {
    window.addEventListener("mousemove", handleMouseMove);
    return () => window.removeEventListener("mousemove", handleMouseMove);
  }, [divRef.current]);

  return (
    <div
      ref={divRef}
      className={`transition-transform duration-1000 ease-out ${className}`}
    >
      {children}
    </div>
  );
}
