import {useEffect, useLayoutEffect, useRef, useState} from "react"

const useDimension = () => {

    const RESET_TIMEOUT = 300
    let movement_timer: number|undefined = undefined
    const targetRef = useRef<HTMLDivElement|undefined>()
    const [dimensions, setDimensions] = useState({ width:0, height: 0 })

    useEffect(() => {
        window.addEventListener('resize', ()=>{
            clearInterval(movement_timer)
            // @ts-expect-error setTimeout defined in var
            movement_timer = setTimeout(testDimensions, RESET_TIMEOUT)
        })
    })

    useLayoutEffect(() => {
        testDimensions()
    }, [])

    const testDimensions = () => {
        if (targetRef.current) {
            setDimensions({
                width: targetRef.current.offsetWidth,
                height: targetRef.current.offsetHeight
            })
        }
    }

    return {
        targetRef,
        dimensions,
    }
}

export default useDimension
