import { onMounted, onUnmounted, ref } from 'vue'
import * as echarts from 'echarts'

const chartInstances: Map<string, echarts.ECharts> = new Map()
let instanceCounter = 0

export const windowSize = ref({
  width: window.innerWidth,
  height: window.innerHeight,
})

export function addChartInstance(chart: echarts.ECharts) {
  const id = `chart_${instanceCounter++}`
  chartInstances.set(id, chart)
  return id
}

export function removeChartInstance(id: string) {
  const chart = chartInstances.get(id)
  if (chart) {
    chartInstances.delete(id)
    try {
      chart.dispose()
    } catch (error) {
      console.warn('Chart dispose failed:', error)
    }
  }
}

export function safeInitChart(dom: HTMLElement): echarts.ECharts {
  const existing = echarts.getInstanceByDom(dom)
  if (existing) {
    echarts.dispose(dom)
  }
  return echarts.init(dom)
}

export function useResponsiveLayout() {
  const handleResize = () => {
    windowSize.value = {
      width: window.innerWidth,
      height: window.innerHeight,
    }

    requestAnimationFrame(() => {
      chartInstances.forEach((chart, id) => {
        try {
          if (chart.getDom()) {
            chart.resize()
          } else {
            console.warn(`Chart ${id} 已被销毁或 DOM 不存在，跳过 resize`)
          }
        } catch (error) {
          console.warn(`Chart resize failed for ${id}:`, error)
        }
      })
    })
  }

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

  onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
    chartInstances.forEach((chart) => {
      try {
        chart.dispose()
      } catch (error) {
        console.warn('Chart dispose failed during cleanup:', error)
      }
    })
    chartInstances.clear()
  })

  return { windowSize }
}
