// source: https://www.react-graph-gallery.com/pie-plot

import type { DependencyList, RefObject } from 'react'
import { useCallback, useEffect, useLayoutEffect, useState } from 'react'

const useDimensions = (
  targetRef: RefObject<HTMLDivElement | null>,
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  dependencies: DependencyList = []
) => {
  const getDimensions = useCallback(
    () => ({
      width: targetRef.current ? targetRef.current.offsetWidth : 0,
      height: targetRef.current ? targetRef.current.offsetHeight : 0,
    }),
    // eslint-disable-next-line react-compiler/react-compiler
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [targetRef, ...dependencies]
  )

  const [dimensions, setDimensions] = useState(getDimensions)

  const handleResize = useCallback(() => {
    setDimensions(getDimensions())
  }, [getDimensions])

  useEffect(() => {
    window.addEventListener('resize', handleResize)
    return () => {
      window.removeEventListener('resize', handleResize)
    }
  }, [handleResize])

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

  return dimensions
}

export default useDimensions
