import { onMounted, onUnmounted, ref } from 'vue'

export function useDevice() {
	const innerWidth = ref(0)
	const isMobile = ref(false)
	const scrollY = ref(0)
	const scrollX = ref(0)
	const innerHeight = ref(0)

	// Scroll direction tracking
	const scrollDirY = ref<'up' | 'down' | null>(null)
	const scrollDirX = ref<'left' | 'right' | null>(null)
	const prevScrollY = ref(0)
	const prevScrollX = ref(0)

	function updateDeviceInfo() {
		// Store previous scroll positions
		prevScrollY.value = scrollY.value
		prevScrollX.value = scrollX.value

		// Update current values
		innerWidth.value = window.innerWidth
		isMobile.value = window.innerWidth < 768
		scrollY.value = window.scrollY
		scrollX.value = window.scrollX
		innerHeight.value = window.innerHeight

		// Determine scroll directions with threshold
		const scrollThreshold = 10

		if (scrollY.value > prevScrollY.value + scrollThreshold) {
			scrollDirY.value = 'down'
		} else if (scrollY.value < prevScrollY.value - scrollThreshold) {
			scrollDirY.value = 'up'
		}

		if (scrollX.value > prevScrollX.value + scrollThreshold) {
			scrollDirX.value = 'right'
		} else if (scrollX.value < prevScrollX.value - scrollThreshold) {
			scrollDirX.value = 'left'
		}
	}

	onMounted(() => {
		window.addEventListener('resize', updateDeviceInfo)
		window.addEventListener('scroll', updateDeviceInfo)
		updateDeviceInfo()
	})

	onUnmounted(() => {
		window.removeEventListener('resize', updateDeviceInfo)
		window.removeEventListener('scroll', updateDeviceInfo)
	})

	return {
		innerWidth,
		isMobile,
		scrollY,
		scrollX,
		innerHeight,
		dirY: scrollDirY,
		dirX: scrollDirX,
	}
}
