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

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

const useSVGDimensions = (
  targetRef: RefObject<SVGGElement>,
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  dependencies: any[] = []
) => {
  const getDimensions = useCallback(
    () => ({
      width: targetRef.current ? targetRef.current.getBBox().width : 0,
      height: targetRef.current ? targetRef.current.getBBox().height : 0,
    }),
    // 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 useSVGDimensions
