/**
 * useReducedMotion — WCAG 2.1 AA (spec 115).
 *
 * Returns true when the user's OS/browser preference is "reduce motion".
 * Subscribes to live changes so the component re-renders if the user
 * toggles the preference without a page reload.
 *
 * SSR-safe: returns false on the server (no window.matchMedia available).
 *
 * Used by Spinner and Toast for *static-replacement* fallbacks — CSS
 * `motion-reduce:animate-none` alone is insufficient when a component
 * needs to render a different element tree under reduced motion.
 */
import { useState, useEffect } from 'react'

const QUERY = '(prefers-reduced-motion: reduce)'

export function useReducedMotion(): boolean {
  const [reducedMotion, setReducedMotion] = useState<boolean>(() => {
    // SSR guard — window is not available during server rendering
    if (typeof window === 'undefined') return false
    return window.matchMedia(QUERY).matches
  })

  useEffect(() => {
    if (typeof window === 'undefined') return

    const mql = window.matchMedia(QUERY)

    const handleChange = (e: MediaQueryListEvent) => {
      setReducedMotion(e.matches)
    }

    // addEventListener is the modern API (addListener is deprecated)
    mql.addEventListener('change', handleChange)
    return () => {
      mql.removeEventListener('change', handleChange)
    }
  }, [])

  return reducedMotion
}
