import { useEffect, useState } from '@wordpress/element'

const MOBILE_MAX_WIDTH = 768

export const useIsMobileViewport = (maxWidth = MOBILE_MAX_WIDTH): boolean => {
	const query = `(max-width: ${maxWidth}px)`

	const [isMobile, setIsMobile] = useState(() => {
		if (typeof window === 'undefined') {
			return false
		}
		return window.matchMedia(query).matches
	})

	useEffect(() => {
		const mediaQuery = window.matchMedia(query)
		const onChange = () => setIsMobile(mediaQuery.matches)

		onChange()
		mediaQuery.addEventListener('change', onChange)
		return () => mediaQuery.removeEventListener('change', onChange)
	}, [query])

	return isMobile
}
