'use client';

import { useSyncExternalStore } from 'react';

/**
 * Tracks `prefers-reduced-motion: reduce`. All Executive motion (count-up,
 * draw-in, gauge sweep, carousel, pixel-shift) is gated on the negation of
 * this so the dashboard is fully static for users who ask for it.
 *
 * Implemented with useSyncExternalStore (the canonical pattern for an external
 * media-query source) — no setState-in-effect, SSR-safe (server snapshot =
 * false), tear-free.
 */
const QUERY = '(prefers-reduced-motion: reduce)';

function subscribe(callback: () => void): () => void {
    if (typeof window === 'undefined' || !window.matchMedia) return () => {};
    const mq = window.matchMedia(QUERY);
    mq.addEventListener('change', callback);
    return () => mq.removeEventListener('change', callback);
}

function getSnapshot(): boolean {
    return typeof window !== 'undefined' && !!window.matchMedia && window.matchMedia(QUERY).matches;
}

export function useReducedMotion(): boolean {
    return useSyncExternalStore(subscribe, getSnapshot, () => false);
}
