import { useRef } from 'react';
import type { PointerEvent, ReactNode } from 'react';
import { cx } from '@/site/lib/cx';
import { motionEnabled } from '@/site/lib/scroll-engine';

type TiltProps = {
    children: ReactNode;
    /** Largest tilt in degrees, reached at the edges of the card. */
    max?: number;
    className?: string;
};

/**
 * Lets a card lean towards the mouse pointer, with a soft light that follows
 * it. Mouse only (touch and pen are left alone) and only while motion is on.
 * The values are written to the element as CSS variables — see `.tilt` in
 * site.css — so moving the pointer never renders React.
 */
export function Tilt({ children, max = 6, className }: TiltProps) {
    const ref = useRef<HTMLDivElement>(null);
    const box = useRef<DOMRect | null>(null);

    const onPointerEnter = (event: PointerEvent<HTMLDivElement>) => {
        box.current =
            event.pointerType === 'mouse' && motionEnabled()
                ? event.currentTarget.getBoundingClientRect()
                : null;
    };

    const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
        const el = ref.current;
        const rect = box.current;

        if (!el || !rect) {
            return;
        }

        const x = (event.clientX - rect.left) / rect.width - 0.5;
        const y = (event.clientY - rect.top) / rect.height - 0.5;

        el.style.setProperty('--tilt-x', `${(-y * max).toFixed(2)}deg`);
        el.style.setProperty('--tilt-y', `${(x * max).toFixed(2)}deg`);
        el.style.setProperty('--glare-x', `${(x * 100).toFixed(1)}%`);
        el.style.setProperty('--glare-y', `${(y * 100).toFixed(1)}%`);
    };

    const onPointerLeave = () => {
        const el = ref.current;

        box.current = null;

        for (const name of ['--tilt-x', '--tilt-y', '--glare-x', '--glare-y']) {
            el?.style.removeProperty(name);
        }
    };

    return (
        <div
            ref={ref}
            className={cx('tilt', className)}
            onPointerEnter={onPointerEnter}
            onPointerMove={onPointerMove}
            onPointerLeave={onPointerLeave}
        >
            {children}
            <span aria-hidden="true" className="tilt-glare" />
        </div>
    );
}
