<script lang="ts">
	import { Chart } from 'chart.js';
	import { onMount } from 'svelte';

	function updateGraph() {
		getTrendingSymbols().then((trendingSymbols) => {
			const labels = trendingSymbols.map((d) => d.longName);

			const datasets = [
				{
					label: '50 day performance',
					data: trendingSymbols.map((ts) => ts.fiftyDayAverageChange),
					backgroundColor: 'green'
				},
				{
					label: '52 week performance',
					data: trendingSymbols.map((ts) => ts.fiftyTwoWeekLowChange),
					backgroundColor: 'orange'
				}
			];

			const data = { labels, datasets };

			// @ts-ignore
			new Chart(document.getElementById('graph'), {
				type: 'bar',
				data: data,
				options: {
					indexAxis: 'y',
					elements: {
						bar: {
							borderWidth: 2
						}
					},
					responsive: true,
					plugins: {
						legend: {
							position: 'bottom'
						}
					}
				}
			});
		});
	}

	async function getTrendingSymbols() {
		const trendingRes = await fetch('/stocksapi/trendingSymbols');
		if (!trendingRes.ok) {
			throw new Error('Failed to fetch trending symbols');
		}
		const trendingJson = await trendingRes.json();

		const { quotes } = trendingJson;

		const trendingSymbols = await Promise.all(
			quotes.map(async (quote: any) => {
				const quoteRes = await fetch(`/stocksapi/quote?query=${quote.symbol}`);
				const quoteJson = await quoteRes.json();
				return quoteJson;
			})
		);

		return trendingSymbols;
	}

	onMount(() => {
		updateGraph();
	});
</script>

<h2>Tendances</h2>
<canvas id="graph"></canvas>

<style>
	h2 {
		font-weight: bold;
		color: var(--text-lime);
		font-size: 24px;
	}

	#graph {
		max-height: 40vh;
		max-width: 40vw;
	}
</style>
