/**
 * Card glare effect — cursor-tracking spotlight on .card and .template-card elements.
 *
 * Uses a single document-level mousemove listener (event delegation) and
 * CSS custom properties (--glare-x, --glare-y) to position a radial gradient
 * overlay via the ::after pseudo-element defined in cards.css.
 */

const CARD_SEL = '.card, .template-card';

let _active: Element | null = null;   // currently illuminated card element
let _cachedRect: DOMRect | null = null; // cached bounding rect for current card

function _onMove(e) {
    const card = e.target.closest(CARD_SEL);

    if (card && !card.classList.contains('add-device-card')) {
        if (_active !== card) {
            if (_active) _active.classList.remove('card-glare');
            card.classList.add('card-glare');
            _active = card;
            _cachedRect = card.getBoundingClientRect();
        }

        const x = e.clientX - _cachedRect!.left;
        const y = e.clientY - _cachedRect!.top;
        card.style.setProperty('--glare-x', `${x}px`);
        card.style.setProperty('--glare-y', `${y}px`);
    } else if (_active) {
        _active.classList.remove('card-glare');
        _active = null;
        _cachedRect = null;
    }
}

function _onLeave() {
    if (_active) {
        _active.classList.remove('card-glare');
        _active = null;
        _cachedRect = null;
    }
}

export function initCardGlare() {
    document.addEventListener('mousemove', _onMove, { passive: true });
    document.addEventListener('mouseleave', _onLeave);
}
