"use client";

import Link from "next/link";
import { useRef, type ReactNode } from "react";

type Props = {
  href: string;
  children: ReactNode;
  variant?: "solid" | "ghost";
  className?: string;
};

/** Magnetic CTA: eases a few px toward the cursor on hover; gold underline sweep on ghost. */
export default function MagneticButton({
  href,
  children,
  variant = "solid",
  className = "",
}: Props) {
  const ref = useRef<HTMLAnchorElement>(null);

  const onMove = (e: React.MouseEvent) => {
    const el = ref.current;
    if (!el) return;
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    const r = el.getBoundingClientRect();
    const dx = e.clientX - (r.left + r.width / 2);
    const dy = e.clientY - (r.top + r.height / 2);
    el.style.transform = `translate(${dx * 0.18}px, ${dy * 0.3}px)`;
  };

  const onLeave = () => {
    const el = ref.current;
    if (el) el.style.transform = "translate(0, 0)";
  };

  const base =
    "inline-flex items-center gap-3 font-mono text-[0.72rem] uppercase tracking-[0.22em] transition-colors duration-300 will-change-transform";
  const styles =
    variant === "solid"
      ? "bg-gold text-obsidian px-7 py-4 hover:bg-amber"
      : "text-ivory px-1 py-4 btn-underline hover:text-gold";

  return (
    <Link
      ref={ref}
      href={href}
      onMouseMove={onMove}
      onMouseLeave={onLeave}
      className={`${base} ${styles} ${className}`}
      style={{ transition: "transform 0.35s cubic-bezier(0.22,1,0.36,1), color 0.3s, background-color 0.3s" }}
    >
      {children}
    </Link>
  );
}