import { onMounted, onBeforeUnmount, ref } from 'vue'

export function useChartResize(chartInstance) {
    let isDestroyed = false
    const handleResize = () => {
        if (isDestroyed || !chartInstance.value) {
            return
        }
        try {
            chartInstance.value.resize()
        } catch (error) {
            console.error('Error resizing chart:', error)
        }
    }

    const initResizeListener = () => {
        window.addEventListener('resize', handleResize)
    }

    const removeResizeListener = () => {
        window.removeEventListener('resize', handleResize)
        isDestroyed = true
    }

    onMounted(() => {
        initResizeListener()
    })

    onBeforeUnmount(() => {
        removeResizeListener()
    })

    return { handleResize, initResizeListener, removeResizeListener }
}