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

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

const props = defineProps({
  data: {
    type: Object,
    default: () => ({})
  },
  title: {
    type: String,
    default: ''
  }
});

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

let root = null;

const createChart = () => {
  if (root) {
    root.dispose();
  }

  root = $am5.Root.new(chartdiv.value);

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

  let chart = root.container.children.push($am5xy.XYChart.new(root, {
    panX: false,
    panY: false,
    wheelX: "none",
    wheelY: "none",
    layout: root.verticalLayout
  }));

  // Prepare data - convert object to array and sort by count descending
  const entries = Object.entries(props.data);
  const chartData = entries
    .map(([org, count]) => ({
      category: org,
      value: count
    }))
    .sort((a, b) => b.value - a.value);

  // Create Y-axis (categories - horizontal bar means categories on Y)
  let yAxis = chart.yAxes.push($am5xy.CategoryAxis.new(root, {
    categoryField: "category",
    renderer: $am5xy.AxisRendererY.new(root, {
      inversed: true,
      cellStartLocation: 0.1,
      cellEndLocation: 0.9,
      minGridDistance: 20
    })
  }));

  yAxis.data.setAll(chartData);

  // Create X-axis (values)
  let xAxis = chart.xAxes.push($am5xy.ValueAxis.new(root, {
    renderer: $am5xy.AxisRendererX.new(root, {}),
    min: 0
  }));

  // Create series
  let series = chart.series.push($am5xy.ColumnSeries.new(root, {
    name: "Orders",
    xAxis: xAxis,
    yAxis: yAxis,
    valueXField: "value",
    categoryYField: "category",
    sequencedInterpolation: true
  }));

  series.columns.template.setAll({
    cornerRadiusTR: 5,
    cornerRadiusBR: 5,
    strokeOpacity: 0,
    tooltipText: "{category}: [bold]{valueX}[/]"
  });

  // Add gradient colors
  series.columns.template.adapters.add("fill", function(fill, target) {
    return chart.get("colors").getIndex(series.columns.indexOf(target));
  });

  series.columns.template.adapters.add("stroke", function(stroke, target) {
    return chart.get("colors").getIndex(series.columns.indexOf(target));
  });

  // Add value labels inside the bars on the left
  series.bullets.push(function() {
    return $am5.Bullet.new(root, {
      locationX: 0,
      sprite: $am5.Label.new(root, {
        text: "{valueX}",
        fill: $am5.color(0xffffff),
        centerY: $am5.p50,
        centerX: $am5.p0,
        paddingLeft: 10,
        populateText: true,
        fontWeight: "bold"
      })
    });
  });

  series.data.setAll(chartData);
  series.appear(1000);
  chart.appear(1000, 100);
};

onMounted(() => {
  if (Object.keys(props.data).length > 0) {
    createChart();
  }
});

watch(() => props.data, (newData) => {
  if (Object.keys(newData).length > 0) {
    createChart();
  }
}, { deep: true });

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