<template>
  <div ref="root" class="chart-box" />
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, shallowRef, watch } from 'vue'
import type { ECharts, EChartsOption } from 'echarts'

const props = defineProps<{
  option: EChartsOption
}>()

const root = ref<HTMLDivElement>()
const chart = shallowRef<ECharts>()
let echartsApi: typeof import('echarts') | null = null

async function ensureChart() {
  if (!root.value) return
  if (!echartsApi) {
    echartsApi = await import('echarts')
  }
  if (!chart.value) {
    chart.value = echartsApi.init(root.value)
  }
}

async function render() {
  await ensureChart()
  chart.value?.setOption(props.option, { notMerge: true })
}

function handleResize() {
  chart.value?.resize()
}

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

watch(() => props.option, render, { deep: true })

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  chart.value?.dispose()
})
</script>
