<template>
  <div ref="chartdiv" style="width: 100%; height: 300px;"></div>
</template>

<script setup>
const props = defineProps({
  data: {
    type: Object,
    default: () => ({})
  },
  title: {
    type: String,
    default: 'Pie Chart'
  }
})

const chartdiv = ref(null)
let root = null
let chart = null

const { $am5, $am5percent, $am5themes_Animated } = useNuxtApp()

const createChart = () => {
  if (!chartdiv.value || !$am5) return

  // Clean up existing chart
  if (root) {
    root.dispose()
  }

  // Create root element
  root = $am5.Root.new(chartdiv.value)

  // Set themes
  root.setThemes([
    $am5themes_Animated.default.new(root)
  ])

  // Create chart
  chart = root.container.children.push($am5percent.PieChart.new(root, {
    layout: root.verticalLayout,
    innerRadius: $am5.percent(50)
  }))

  // Create series
  const series = chart.series.push($am5percent.PieSeries.new(root, {
    valueField: "value",
    categoryField: "category",
    alignLabels: false
  }))

  series.labels.template.setAll({
    textType: "circular",
    centerX: 0,
    centerY: 0,
    text: "{categoryShort}: {value}",
    fontSize: 12
  })

  // Helper function to shorten organization names
  const shortenOrgName = (name) => {
    if (!name || name.length <= 8) return name

    // Try to get initials from multi-word names
    const words = name.split(/[\s-_]+/)
    if (words.length > 1) {
      return words.map(word => word.charAt(0).toUpperCase()).join('')
    }

    // For single words, truncate and add ellipsis
    return name.substring(0, 6) + '...'
  }

  // Transform data for amCharts
  const chartData = Object.entries(props.data).map(([org, count]) => ({
    category: org,
    categoryShort: shortenOrgName(org),
    value: count
  }))

  // Set data
  series.data.setAll(chartData)

  // Create legend
  const legend = chart.children.push($am5.Legend.new(root, {
    centerX: $am5.percent(50),
    x: $am5.percent(50),
    marginTop: 15,
    marginBottom: 15
  }))

  legend.data.setAll(series.dataItems)
}

onMounted(() => {
  nextTick(() => {
    createChart()
  })
})

onUnmounted(() => {
  if (root) {
    root.dispose()
  }
})

watch(() => props.data, () => {
  if (chart) {
    createChart()
  }
}, { deep: true })
</script>
