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

<script setup>
import { onMounted, onBeforeUnmount, ref, watch } from 'vue'
import { useNuxtApp } from '#app'

const props = defineProps({
  rows: { type: Array, default: () => [] },
  series: { type: Array, default: () => [] },
  categoryField: { type: String, default: 'day' },
})

const chartdiv = ref(null)
const { $am5, $am5xy, $am5themes_Animated } = useNuxtApp()

let root = null

const buildChart = () => {
  if (root) {
    root.dispose()
    root = null
  }
  if (!chartdiv.value || !props.rows.length || !props.series.length) return

  root = $am5.Root.new(chartdiv.value)
  root.setThemes([$am5themes_Animated.default.new(root)])

  const chart = root.container.children.push(
    $am5xy.XYChart.new(root, {
      panX: false,
      panY: false,
      wheelX: 'panX',
      wheelY: 'zoomX',
      paddingLeft: 0,
      layout: root.verticalLayout,
    })
  )

  const legend = chart.children.push(
    $am5.Legend.new(root, {
      centerX: $am5.p50,
      x: $am5.p50,
      marginTop: 10,
    })
  )

  const xRenderer = $am5xy.AxisRendererX.new(root, {
    minGridDistance: 30,
    cellStartLocation: 0.1,
    cellEndLocation: 0.9,
  })
  xRenderer.labels.template.setAll({ rotation: -25, centerY: $am5.p50, centerX: $am5.p100 })

  const xAxis = chart.xAxes.push(
    $am5xy.CategoryAxis.new(root, {
      categoryField: props.categoryField,
      renderer: xRenderer,
      tooltip: $am5.Tooltip.new(root, {}),
    })
  )
  xAxis.data.setAll(props.rows)

  const yAxis = chart.yAxes.push(
    $am5xy.ValueAxis.new(root, {
      min: 0,
      renderer: $am5xy.AxisRendererY.new(root, {}),
    })
  )

  for (const name of props.series) {
    const series = chart.series.push(
      $am5xy.ColumnSeries.new(root, {
        name,
        stacked: true,
        xAxis,
        yAxis,
        valueYField: name,
        categoryXField: props.categoryField,
        tooltip: $am5.Tooltip.new(root, {
          labelText: '{name}, {categoryX}: [bold]{valueY}[/]',
        }),
      })
    )
    series.columns.template.setAll({
      tooltipY: $am5.percent(10),
      strokeOpacity: 0,
      width: $am5.percent(85),
    })
    series.data.setAll(props.rows)
    legend.data.push(series)
  }

  chart.set('cursor', $am5xy.XYCursor.new(root, { behavior: 'none' }))
  chart.appear(800, 100)
}

onMounted(buildChart)
onBeforeUnmount(() => {
  if (root) {
    root.dispose()
    root = null
  }
})

watch(
  () => [props.rows, props.series],
  () => buildChart(),
  { deep: true }
)
</script>
