import { useEffect, useRef } from 'react';
import { motionEnabled } from '@/site/lib/scroll-engine';

/**
 * A soft light that follows the mouse over the dark section it is placed
 * in and lifts the hairline grid under it (`.spot` in site.css). The same
 * pointer position is handed to the drawings of the section — every
 * element marked `data-pointer` — as `--mx` / `--my` (-1…1), so their
 * layers lean with the mouse.
 *
 * Mouse only, and only while motion is on; the values are written to the
 * elements directly, once per frame, so moving the pointer never renders
 * React. Purely decorative: without it the section is unchanged.
 */
export function Spotlight() {
    const ref = useRef<HTMLDivElement>(null);

    useEffect(() => {
        const spot = ref.current;
        const host = spot?.parentElement;

        if (
            !spot ||
            !host ||
            !motionEnabled() ||
            !window.matchMedia('(hover: hover) and (pointer: fine)').matches
        ) {
            return;
        }

        let frame = 0;
        let x = 0;
        let y = 0;
        let targets: HTMLElement[] | null = null;

        const paint = () => {
            frame = 0;

            const rect = host.getBoundingClientRect();
            const sx = x - rect.left;
            const sy = y - rect.top;

            targets ??= Array.from(
                host.querySelectorAll<HTMLElement>('[data-pointer]'),
            );

            spot.style.setProperty('--sx', `${sx.toFixed(1)}px`);
            spot.style.setProperty('--sy', `${sy.toFixed(1)}px`);
            spot.setAttribute('data-on', '');

            const mx = ((sx / rect.width - 0.5) * 2).toFixed(3);
            const my = ((sy / rect.height - 0.5) * 2).toFixed(3);

            for (const target of targets) {
                target.style.setProperty('--mx', mx);
                target.style.setProperty('--my', my);
            }
        };

        const move = (event: PointerEvent) => {
            if (event.pointerType !== 'mouse') {
                return;
            }

            x = event.clientX;
            y = event.clientY;

            if (frame === 0) {
                frame = requestAnimationFrame(paint);
            }
        };

        // The light goes out and the drawings ease back to rest.
        const leave = () => {
            spot.removeAttribute('data-on');

            for (const target of targets ?? []) {
                target.style.removeProperty('--mx');
                target.style.removeProperty('--my');
            }
        };

        host.addEventListener('pointermove', move, { passive: true });
        host.addEventListener('pointerleave', leave);

        return () => {
            host.removeEventListener('pointermove', move);
            host.removeEventListener('pointerleave', leave);
            cancelAnimationFrame(frame);
        };
    }, []);

    return (
        <div ref={ref} aria-hidden="true" className="spot">
            <div className="spot-lens">
                <div className="spot-glow" />
                <div className="spot-grid" />
            </div>
        </div>
    );
}
