"use client";

import * as React from "react";
import { motion, useMotionValue, useReducedMotion, useSpring, useTransform } from "motion/react";
import { cn } from "@/lib/utils";

/**
 * Card that leans towards the pointer and lifts, with a moving highlight.
 * Inert on touch devices and under reduced motion so it never fights
 * scrolling. The motion hooks live in an inner component so the outer one can
 * switch between the plain and the animated version without changing its
 * own hook order.
 */
export function TiltCard({ children, className, max = 7, glow = true }: { children: React.ReactNode; className?: string; max?: number; glow?: boolean }) {
  const reduced = useReducedMotion();
  const [enabled, setEnabled] = React.useState(false);
  React.useEffect(() => {
    setEnabled(!reduced && window.matchMedia("(hover: hover) and (pointer: fine)").matches);
  }, [reduced]);
  if (!enabled) return <div className={className}>{children}</div>;
  return (
    <div className={cn("tilt-scene", className)}>
      <Tilt max={max} glow={glow}>
        {children}
      </Tilt>
    </div>
  );
}

function Tilt({ children, max, glow }: { children: React.ReactNode; max: number; glow: boolean }) {
  const px = useMotionValue(0.5);
  const py = useMotionValue(0.5);
  const rx = useSpring(useTransform(py, [0, 1], [max, -max]), { stiffness: 260, damping: 22 });
  const ry = useSpring(useTransform(px, [0, 1], [-max, max]), { stiffness: 260, damping: 22 });
  const glowBg = useTransform([px, py], ([x, y]) => `radial-gradient(240px circle at ${(x as number) * 100}% ${(y as number) * 100}%, color-mix(in oklab, var(--color-primary) 14%, transparent), transparent 60%)`);
  const onMove = (e: React.MouseEvent<HTMLDivElement>) => {
    const r = e.currentTarget.getBoundingClientRect();
    px.set((e.clientX - r.left) / r.width);
    py.set((e.clientY - r.top) / r.height);
  };
  const reset = () => {
    px.set(0.5);
    py.set(0.5);
  };
  return (
    <motion.div className="tilt-card group/tilt relative h-full" style={{ rotateX: rx, rotateY: ry }} onMouseMove={onMove} onMouseLeave={reset} whileHover={{ scale: 1.015, transition: { type: "spring", stiffness: 300, damping: 22 } }}>
      {children}
      {glow ? <motion.span aria-hidden className="pointer-events-none absolute inset-0 rounded-[inherit] opacity-0 transition-opacity duration-300 group-hover/tilt:opacity-100" style={{ background: glowBg }} /> : null}
    </motion.div>
  );
}
