import { useEffect, useState } from 'react'

import { useIsMounted } from './useIsMounted'

/**
 * Tells if the media query matches.
 */
export function useMediaQuery(media: string): boolean {
  const isMounted = useIsMounted()
  const [matches, setMatches] = useState((typeof window === 'object' && window.matchMedia?.(media).matches) || false)

  // https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia
  useEffect(() => {
    const mediaQuery = window.matchMedia?.(media)
    const listener = (event: MediaQueryListEvent) => setMatches(event.matches)

    mediaQuery?.addEventListener?.('change', listener)
    return () => {
      mediaQuery?.removeEventListener?.('change', listener)
    }
  }, [media, setMatches])

  if (!isMounted) {
    return false
  }

  return matches
}
