"use client";

import { useEffect, useRef } from "react";

/**
 * A faint glow that follows the pointer across a card.
 *
 * Drop it as the last child of any positioned element carrying Tailwind's
 * `group` class — it finds its own parent, so the card itself can stay a
 * server component and needs no props threaded through it:
 *
 *     <Link className="group relative …">
 *       …
 *       <Spotlight />
 *     </Link>
 *
 * The paint lives in `.spotlight` (globals.css); this only writes the pointer
 * position. Nothing runs until the pointer is actually over the card, and the
 * effect is disabled on touch screens, where `:hover` would keep it lit.
 */
export function Spotlight() {
  const ref = useRef<HTMLSpanElement>(null);

  useEffect(() => {
    const card = ref.current?.parentElement;
    if (!card || !window.matchMedia("(hover: hover)").matches) return;

    const onMove = (event: PointerEvent) => {
      const rect = card.getBoundingClientRect();
      card.style.setProperty("--spot-x", `${event.clientX - rect.left}px`);
      card.style.setProperty("--spot-y", `${event.clientY - rect.top}px`);
    };

    card.addEventListener("pointermove", onMove);
    return () => card.removeEventListener("pointermove", onMove);
  }, []);

  return <span ref={ref} aria-hidden className="spotlight" />;
}
