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

export function useResizeObserver(elementRef: Ref<HTMLElement | undefined>) {
	const width = ref(0)
	const height = ref(0)
	let resizeObserver: ResizeObserver | null = null

	onMounted(() => {
		if (elementRef.value) {
			resizeObserver = new ResizeObserver((entries) => {
				for (const entry of entries) {
					width.value = entry.contentRect.width
					height.value = entry.contentRect.height
				}
			})
			resizeObserver.observe(elementRef.value)
			width.value = elementRef.value.clientWidth
			height.value = elementRef.value.clientHeight
		}
	})

	onUnmounted(() => {
		if (resizeObserver) {
			resizeObserver.disconnect()
			resizeObserver = null
		}
	})

	return {
		width,
		height
	}
}
