import { useEffect, useState } from 'react'

/**
 * A utility hook that returns whether the window is focused or not.
 */
export function useWindowFocus(): boolean {
  // NOTE: We track the focus of the window because you can trigger
  //       scroll without triggering "mouseenter" event on Mac when another window is in focus.
  const [isWindowFocused, setIsWindowFocused] = useState<boolean>(true)

  useEffect(() => {
    const handleWindowFocus = () => {
      setIsWindowFocused(true)
    }

    const handleWindowBlur = () => {
      setIsWindowFocused(false)
    }

    window.addEventListener('focus', handleWindowFocus)
    window.addEventListener('blur', handleWindowBlur)

    return () => {
      window.removeEventListener('focus', handleWindowFocus)
      window.removeEventListener('blur', handleWindowBlur)
    }
  }, [])

  return isWindowFocused
}
