import { useSyncExternalStore } from 'react';

const REDUCED_MOTION_QUERY = '(prefers-reduced-motion: reduce)';

function subscribe(onChange: () => void): () => void {
    const query = window.matchMedia(REDUCED_MOTION_QUERY);
    query.addEventListener('change', onChange);

    return () => query.removeEventListener('change', onChange);
}

/**
 * Whether the visitor asked their system to keep motion to a minimum.
 *
 * Reads `false` on the server so the markup Inertia sends matches what the
 * browser paints first; the real value lands on hydration.
 */
export function usePrefersReducedMotion(): boolean {
    return useSyncExternalStore(
        subscribe,
        () => window.matchMedia(REDUCED_MOTION_QUERY).matches,
        () => false,
    );
}
