import {
  useEffect,
  useState,
  useMemo,
} from 'react'

export const useMediaQuery = (query: string) => {
  const mediaQuery = useMemo(() => matchMedia(query), [query])
  const [queryMatches, setQueryMatches] = useState(mediaQuery.matches)

  useEffect(() => {
    const listener = (event: MediaQueryListEvent) => {
      setQueryMatches(event.matches)
    }

    try {
      // Chrome & Firefox & Safari version >= 14
      mediaQuery.addEventListener('change', listener)
    } catch {
      // Safari
      mediaQuery.addListener(listener)
    }

    return () => {
      try {
        // Chrome & Firefox & Safari version >= 14
        mediaQuery.removeEventListener('change', listener)
      } catch {
        // Safari
        mediaQuery.removeListener(listener)
      }
    }
  }, [mediaQuery])

  return queryMatches
}
