import { useState } from 'react'
import { useIsomorphicLayoutEffect } from 'framer-motion'

export const useOrientation = () => {
  const [isPortrait, setIsPortrait] = useState(false)

  function handleChange(e: MediaQueryListEvent) {
    setIsPortrait(e.matches)
  }

  useIsomorphicLayoutEffect(() => {
    setIsPortrait(window.matchMedia('(orientation: portrait)').matches)
    window.matchMedia('(orientation: portrait)').addEventListener('change', handleChange)
    return () => window.matchMedia('(orientation: portrait)').removeEventListener('change', handleChange)
  }, [])

  return {
    isPortrait,
    isLandscape: !isPortrait,
    orientation: isPortrait ? 'portrait' : 'landscape',
  }
}
