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

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

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