import { useCallback, useLayoutEffect, useState } from 'react'

type Orientation = "portrait" | "landscape"

function getOrientation(): Orientation {
	if (
		window.screen.orientation &&
		Object.prototype.hasOwnProperty.call(window, 'onorientationchange')
	) {
		return window.screen.orientation.type.includes('portrait') ? 'portrait' : 'landscape'
	}
	if (
		Object.prototype.hasOwnProperty.call(window, 'orientation')
	) {
		return Math.abs(window.orientation) !== 90 ? 'portrait' : 'landscape'

	}
	return window.innerHeight / window.innerWidth > 1 ? "portrait" : "landscape"
}

export interface Size {
	width: number
	height: number
	orientation: Orientation
}

export function useSize():Size {
	const [width, setWidth] = useState<number>(document.documentElement.clientWidth)
	const [height, setHeight] = useState<number>(document.documentElement.clientHeight)
	const [orientation, setOrientation] = useState<Orientation>(getOrientation())

	const resizeListener = useCallback(() => {
		setWidth(document.documentElement.clientWidth)
		setHeight(document.documentElement.clientHeight)
	}, [])

	const orientationListener =useCallback( () => {
		setOrientation(getOrientation())
	},[])

	useLayoutEffect(() => {
		window.addEventListener('resize', resizeListener)
		window.addEventListener('orientationchange', orientationListener)

		return () => {
			window.removeEventListener('resize', resizeListener)
			window.removeEventListener('orientationchange', orientationListener)
		}
	})

	return {
		width,
		height,
		orientation
	}
}
