<template>
  <div class="system-token-treemap">
    <div ref="chartElement" class="chart-body" role="img" :aria-label="ariaLabel"></div>
  </div>
</template>

<script setup>
import { computed, shallowRef } from 'vue'
import { TreemapChart } from 'echarts/charts'
import { TooltipComponent } from 'echarts/components'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'

import { useEcharts } from '../../composables/useEcharts.js'
import { resolveCssColor, useThemeColors } from '../../composables/useThemeColors.js'

use([TooltipComponent, TreemapChart, CanvasRenderer])

const props = defineProps({
  items: { type: Array, required: true }
})

const chartElement = shallowRef(null)
const themeColors = useThemeColors()
const normalizedItems = computed(() =>
  props.items.map((item) => ({
    ...item,
    value: Number(item.tokens || item.value || 0),
    resolvedColor: resolveCssColor(item.color, themeColors.value.chartPrimary)
  }))
)
const ariaLabel = computed(() =>
  normalizedItems.value.map((item) => `${item.name}${formatTokens(item.value)}，占比${item.share}%`).join('；')
)

const chartOptions = computed(() => ({
  backgroundColor: 'transparent',
  animation: true,
  animationDuration: 760,
  animationEasing: 'cubicOut',
  tooltip: {
    trigger: 'item',
    confine: true,
    appendToBody: true,
    backgroundColor: 'rgba(255, 255, 255, 0.98)',
    borderColor: 'rgba(148, 163, 184, 0.24)',
    borderWidth: 1,
    padding: [9, 10],
    textStyle: {
      color: '#334155',
      fontSize: 12,
      fontWeight: 700
    },
    extraCssText: 'border-radius:4px;box-shadow:0 12px 28px rgba(15,23,42,.12);',
    formatter: (params) => `${params.marker}${params.name}<br/>${formatTokens(params.value)} · ${params.data?.share || 0}%`
  },
  series: [
    {
      type: 'treemap',
      roam: false,
      nodeClick: false,
      breadcrumb: { show: false },
      top: 4,
      right: 4,
      bottom: 4,
      left: 4,
      visibleMin: 300,
      leafDepth: 1,
      label: {
        show: true,
        color: '#ffffff',
        fontSize: 12,
        fontWeight: 800,
        lineHeight: 16,
        formatter: (params) => `${params.name}\n${formatTokens(params.value)}`
      },
      itemStyle: {
        borderColor: '#ffffff',
        borderWidth: 3,
        borderRadius: 4,
        gapWidth: 3
      },
      upperLabel: { show: false },
      data: normalizedItems.value.map((item) => ({
        name: item.name,
        value: item.value,
        share: item.share,
        itemStyle: { color: item.resolvedColor }
      }))
    }
  ]
}))

useEcharts(chartElement, chartOptions)

function formatTokens(value) {
  const number = Number(value || 0)
  if (number >= 1_000_000) return `${(number / 1_000_000).toFixed(1)}M tokens`
  if (number >= 1_000) return `${(number / 1_000).toFixed(1)}K tokens`
  return `${Math.round(number)} tokens`
}
</script>

<style scoped>
.system-token-treemap {
  height: 268px;
}

.chart-body {
  width: 100%;
  height: 100%;
}
</style>
