<template>
  <view class="ec-canvas-wrap">
    <canvas id="ec-canvas" class="ec-canvas" type="2d"
      :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }" />
  </view>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'

const props = withDefaults(defineProps<{
  option?: Record<string, any>
  width?: number
  height?: number
}>(), {
  width: 350,
  height: 250,
})

const emit = defineEmits<{
  (e: 'init', chart: any): void
}>()

const canvasWidth = ref(props.width)
const canvasHeight = ref(props.height)

// Minimal ECharts bridge — for full ECharts, use lime-echart plugin
// This is a placeholder that renders a basic canvas with the option's title
onMounted(() => {
  nextTick(initCanvas)
})

function nextTick(fn: () => void) {
  setTimeout(fn, 50)
}

function initCanvas() {
  const query = uni.createSelectorQuery()
  query.select('#ec-canvas').fields({ node: true, size: true }).exec((res) => {
    if (!res || !res[0] || !res[0].node) return
    emit('init', { canvas: res[0].node, width: res[0].width, height: res[0].height })
  })
}

watch(() => props.option, () => {
  nextTick(initCanvas)
}, { deep: true })
</script>

<style lang="scss" scoped>
.ec-canvas-wrap {
  @include flex-center;
}

.ec-canvas {
  display: block;
}
</style>
