"use client";
import { useRef, type ReactNode } from "react";

export function TiltCard({
  children,
  href,
  maxDeg = 4,
  className = "",
}: {
  children: ReactNode;
  href?: string;
  maxDeg?: number;
  className?: string;
}) {
  const ref = useRef<HTMLDivElement>(null);

  function onMove(e: React.MouseEvent<HTMLDivElement>) {
    const el = ref.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    const cx = rect.width / 2;
    const cy = rect.height / 2;
    const rx = ((y - cy) / cy) * -maxDeg;
    const ry = ((x - cx) / cx) * maxDeg;
    el.style.setProperty("--rx", `${rx.toFixed(2)}deg`);
    el.style.setProperty("--ry", `${ry.toFixed(2)}deg`);
    el.style.setProperty("--mx", `${(x / rect.width) * 100}%`);
    el.style.setProperty("--my", `${(y / rect.height) * 100}%`);
  }
  function onLeave() {
    const el = ref.current;
    if (!el) return;
    el.style.setProperty("--rx", `0deg`);
    el.style.setProperty("--ry", `0deg`);
  }

  return (
    <div
      ref={ref}
      onMouseMove={onMove}
      onMouseLeave={onLeave}
      className={`tilt-card relative overflow-hidden ${className}`}
      data-cursor="hover"
    >
      <div className="tilt-shine" />
      {href ? (
        <a href={href} className="block">
          {children}
        </a>
      ) : (
        children
      )}
    </div>
  );
}
