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

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

const props = defineProps({
  // Array of rows: [{ month: 'Jan', <country>: n, ... }, ...]
  rows: { type: Array, default: () => [] },
  // Array of country names — one line series each.
  series: { type: Array, default: () => [] },
  categoryField: { type: String, default: 'month' },
})

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

// Distinct, readable palette reused from the Shipments-by-Org page.
const palette = [
  0x3b82f6, 0x10b981, 0xf59e0b, 0xef4444, 0x8b5cf6,
  0xec4899, 0x06b6d4, 0xf97316, 0x84cc16, 0x6366f1,
  0x14b8a6, 0xeab308, 0x0ea5e9, 0xd946ef, 0x22c55e,
  0xfb7185, 0xa855f7, 0x65a30d, 0xf43f5e, 0x0891b2,
]

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: 'none',
      wheelY: 'none',
      pinchZoomX: false,
      paddingLeft: 10,
      layout: root.verticalLayout,
    })
  )

  const cursor = chart.set('cursor', $am5xy.XYCursor.new(root, { behavior: 'none' }))
  cursor.lineY.set('visible', false)

  const legend = chart.children.push(
    $am5.Legend.new(root, {
      centerX: $am5.p50,
      x: $am5.p50,
      marginTop: 10,
      useDefaultMarker: true,
    })
  )
  legend.labels.template.setAll({ fontSize: 12 })

  const xAxis = chart.xAxes.push(
    $am5xy.CategoryAxis.new(root, {
      categoryField: props.categoryField,
      renderer: $am5xy.AxisRendererX.new(root, { minGridDistance: 30 }),
      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, {}),
    })
  )

  props.series.forEach((name, index) => {
    const color = $am5.color(palette[index % palette.length])

    const series = chart.series.push(
      $am5xy.LineSeries.new(root, {
        name,
        xAxis,
        yAxis,
        valueYField: name,
        categoryXField: props.categoryField,
        stroke: color,
        fill: color,
        tooltip: $am5.Tooltip.new(root, {
          labelText: '{name}, {categoryX}: [bold]{valueY}[/]',
        }),
      })
    )

    series.strokes.template.setAll({ strokeWidth: 2 })
    series.bullets.push(function () {
      return $am5.Bullet.new(root, {
        sprite: $am5.Circle.new(root, {
          radius: 3,
          fill: series.get('fill'),
        }),
      })
    })

    series.data.setAll(props.rows)
    legend.data.push(series)
  })

  chart.appear(800, 100)
}

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

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