"use client";

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

/**
 * 3D pointer-tilt: the card rotates in perspective toward the cursor with a
 * moving sheen, giving every grid a physical, dimensional feel.
 * Fine pointers only; inert under reduced motion.
 */
export default function TiltCard({
  children,
  className = "",
  max = 6,
}: {
  children: ReactNode;
  className?: string;
  max?: number;
}) {
  const ref = useRef<HTMLDivElement>(null);
  const sheen = useRef<HTMLDivElement>(null);
  const raf = useRef(0);

  const ok = () =>
    typeof window !== "undefined" &&
    window.matchMedia("(pointer: fine)").matches &&
    !window.matchMedia("(prefers-reduced-motion: reduce)").matches;

  const move = (e: React.PointerEvent) => {
    if (!ok()) return;
    const el = ref.current;
    if (!el) return;
    const r = el.getBoundingClientRect();
    const px = (e.clientX - r.left) / r.width;
    const py = (e.clientY - r.top) / r.height;
    cancelAnimationFrame(raf.current);
    raf.current = requestAnimationFrame(() => {
      el.style.transform = `perspective(950px) rotateX(${(0.5 - py) * max}deg) rotateY(${(px - 0.5) * max}deg) translateZ(0)`;
      if (sheen.current) {
        sheen.current.style.opacity = "1";
        sheen.current.style.background = `radial-gradient(420px circle at ${px * 100}% ${py * 100}%, rgba(127,184,240,0.14), transparent 55%)`;
      }
    });
  };

  const leave = () => {
    const el = ref.current;
    if (!el) return;
    cancelAnimationFrame(raf.current);
    el.style.transform = "";
    if (sheen.current) sheen.current.style.opacity = "0";
  };

  return (
    <div
      ref={ref}
      onPointerMove={move}
      onPointerLeave={leave}
      className={`relative transition-transform duration-300 ease-out ${className}`}
    >
      {children}
      <div
        ref={sheen}
        className="pointer-events-none absolute inset-0 rounded-xl opacity-0 transition-opacity duration-300"
        aria-hidden
      />
    </div>
  );
}
