<!--
  Reusable ECharts wrapper for resource time-series.

  Uses ECharts' tree-shakeable core import so only the modules we need
  ship to the browser. The component creates one chart per mount, reuses
  it via setOption, and disposes on unmount. ResizeObserver keeps the
  canvas size in sync with its container.
-->
<script lang="ts">
	import { onDestroy, onMount } from 'svelte';
	import * as echarts from 'echarts/core';
	import { LineChart } from 'echarts/charts';
	import {
		GridComponent,
		TooltipComponent,
		TitleComponent,
		DatasetComponent,
		LegendComponent
	} from 'echarts/components';
	import { CanvasRenderer } from 'echarts/renderers';
	import type { EChartsOption } from 'echarts';

	echarts.use([
		LineChart,
		GridComponent,
		TooltipComponent,
		TitleComponent,
		DatasetComponent,
		LegendComponent,
		CanvasRenderer
	]);

	interface Props {
		option: EChartsOption;
		height?: string;
		ariaLabel?: string;
	}

	const { option, height = '160px', ariaLabel = 'Resource chart' }: Props = $props();

	let container: HTMLDivElement | undefined = $state();
	let chart: echarts.ECharts | null = null;
	let resizeObs: ResizeObserver | null = null;

	onMount(() => {
		if (!container) return;
		chart = echarts.init(container, null, { renderer: 'canvas' });
		chart.setOption(option);

		resizeObs = new ResizeObserver(() => chart?.resize());
		resizeObs.observe(container);
	});

	$effect(() => {
		if (chart) {
			chart.setOption(option, { notMerge: false, lazyUpdate: true });
		}
	});

	onDestroy(() => {
		resizeObs?.disconnect();
		chart?.dispose();
		chart = null;
	});
</script>

<div
	bind:this={container}
	role="img"
	aria-label={ariaLabel}
	style="height: {height}; width: 100%;"
></div>
