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

export const colors = {
  blue: '#1e90ff',
  cyan: '#22d3ee',
  green: '#22c55e',
  purple: '#8b5cf6',
  warn: '#f59e0b',
  danger: '#ef4444'
}

export const style = {
  axisLine: { lineStyle: { color: 'rgba(148,163,184,0.45)' } },
  axisLabel: { color: '#a8b7d8', fontSize: 12 },
  splitLine: { lineStyle: { color: 'rgba(30,64,175,0.55)', type: 'dashed' } },
  legendText: { color: '#e5f0ff', fontSize: 12 }
}

export function animateCount(el: HTMLElement | null, target: number, suffix: string, duration: number) {
  if (!el) return
  const start = 0
  const t0 = performance.now()
  const step = (t: number) => {
    const p = Math.min(1, (t - t0) / duration)
    const v = start + (target - start) * p
    const out = Number.isInteger(target) ? Math.round(v) : Math.round(v * 10) / 10
    el.textContent = suffix ? `${out}${suffix}` : `${out}`
    if (p < 1) requestAnimationFrame(step)
  }
  requestAnimationFrame(step)
}

export function useChart(domId: string) {
  let chart: echarts.ECharts | null = null

  const init = () => {
    const el = document.getElementById(domId)
    if (!el) return null
    chart = echarts.init(el, 'dark', { renderer: 'canvas' })
    return chart
  }

  const resize = () => {
    chart?.resize()
  }

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

  onUnmounted(() => {
    window.removeEventListener('resize', resize)
    chart?.dispose()
  })

  return {
    init,
    resize,
    instance: () => chart
  }
}
