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

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

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

onMounted(() => {
  let root = $am5.Root.new(chartdiv.value);

  root.setThemes([
    $am5themes_Animated.default.new(root)
  ]);

  let chart = root.container.children.push($am5xy.XYChart.new(root, {
    panX: true,
    panY: true,
    wheelX: "panX",
    wheelY: "zoomX",
    pinchZoomX: true
  }));

  let cursor = chart.set("cursor", $am5xy.XYCursor.new(root, {}));
  cursor.lineY.set("visible", false);

  let xAxis = chart.xAxes.push($am5xy.CategoryAxis.new(root, {
    categoryField: "category",
    renderer: $am5xy.AxisRendererX.new(root, { minGridDistance: 30 })
  }));

  let yAxis = chart.yAxes.push($am5xy.ValueAxis.new(root, {
    renderer: $am5xy.AxisRendererY.new(root, {})
  }));

  let series = chart.series.push($am5xy.ColumnSeries.new(root, {
    name: "Series 1",
    xAxis: xAxis,
    yAxis: yAxis,
    valueYField: "value",
    categoryXField: "category"
  }));

  series.columns.template.setAll({
    tooltipText: "{category}: [bold]{valueY}[/]"
  });

  series.data.setAll([
    { category: "One", value: 50 },
    { category: "Two", value: 70 },
    { category: "Three", value: 100 }
  ]);

  xAxis.data.setAll([
    { category: "One" },
    { category: "Two" },
    { category: "Three" }
  ]);

  onBeforeUnmount(() => {
    root.dispose();
  });
});
</script>
