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

// Hero-Mouse-Tilt: Die ganze Section kippt ganz subtil basierend auf
// Maus-Position (max ±2°). GPU-beschleunigt (CSS-Variablen + transform).
// Auf Touch-Devices deaktiviert.

export function HeroTilt({ children, className = "" }: { children: ReactNode; className?: string }) {
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const touch = window.matchMedia("(pointer: coarse)").matches;
    if (reduce || touch) return;

    function onMove(e: MouseEvent) {
      const r = el!.getBoundingClientRect();
      const x = ((e.clientX - r.left) / r.width - 0.5) * 4;  // ±2°
      const y = ((e.clientY - r.top) / r.height - 0.5) * -4; // ±2° invertiert
      el!.style.setProperty("--hero-rx", `${y.toFixed(2)}deg`);
      el!.style.setProperty("--hero-ry", `${x.toFixed(2)}deg`);
    }
    function onLeave() {
      el!.style.setProperty("--hero-rx", `0deg`);
      el!.style.setProperty("--hero-ry", `0deg`);
    }
    window.addEventListener("mousemove", onMove, { passive: true });
    document.addEventListener("mouseleave", onLeave);
    return () => {
      window.removeEventListener("mousemove", onMove);
      document.removeEventListener("mouseleave", onLeave);
    };
  }, []);

  return (
    <div
      ref={ref}
      className={className}
      style={{
        transform: "perspective(1200px) rotateX(var(--hero-rx, 0deg)) rotateY(var(--hero-ry, 0deg))",
        transition: "transform 600ms cubic-bezier(0.16, 1, 0.3, 1)",
        willChange: "transform",
        transformStyle: "preserve-3d",
      }}
    >
      {children}
    </div>
  );
}
