import { useEffect } from 'react';

const RIPPLE_SELECTOR = [
    'button',
    '[role="button"]',
    'a[href]',
    '[data-slot="button"]',
    '[data-slot="sidebar-menu-button"]',
    '[data-slot="sidebar-menu-sub-button"]',
    '[data-slot="sidebar-menu-action"]',
    '[data-slot="sidebar-group-action"]',
    '[data-slot="sidebar-rail"]',
].join(',');

export function GlobalRippleEffect() {
    useEffect(() => {
        const handlePointerDown = (event: PointerEvent) => {
            if (!event.isPrimary) {
                return;
            }

            if (event.pointerType === 'mouse' && event.button !== 0) {
                return;
            }

            const target = event.target;
            if (!(target instanceof Element)) {
                return;
            }

            const host = target.closest<HTMLElement>(RIPPLE_SELECTOR);
            if (!host) {
                return;
            }

            if (host.dataset.ripple === 'off' || host.closest('[data-ripple-skip="true"]')) {
                return;
            }

            const isDisabled =
                host.matches(':disabled') ||
                host.getAttribute('aria-disabled') === 'true' ||
                host.getAttribute('data-disabled') === 'true';
            if (isDisabled) {
                return;
            }

            host.classList.add('ui-ripple-host');

            const rect = host.getBoundingClientRect();
            const size = Math.max(rect.width, rect.height) * 1.35;
            const ripple = document.createElement('span');
            ripple.className = 'ui-global-ripple';
            ripple.style.width = `${size}px`;
            ripple.style.height = `${size}px`;
            ripple.style.left = `${event.clientX - rect.left - size / 2}px`;
            ripple.style.top = `${event.clientY - rect.top - size / 2}px`;

            host.appendChild(ripple);

            ripple.addEventListener(
                'animationend',
                () => {
                    ripple.remove();
                },
                { once: true },
            );
        };

        document.addEventListener('pointerdown', handlePointerDown, true);

        return () => {
            document.removeEventListener('pointerdown', handlePointerDown, true);
        };
    }, []);

    return null;
}

