<script>
	import Chart from '../../components/Chart.svelte';
	import { onMount } from 'svelte';
	import { authentication } from '../store.js';
	import { fade } from 'svelte/transition';

	let authToken;
	let data = {};
	let isLoading = true;

	onMount(() => {
		return authentication.subscribe(async ({ token }) => {
			if (token) {
				authToken = token;
				await fetchPortfolio();
			}
		});
	});

	async function fetchPortfolio() {
		try {
			const response = await fetch(`${import.meta.env.VITE_STOCKS_HOST}/api/portfolios`, {
				headers: {
					Authorization: `Bearer ${authToken}`
				}
			});

			if (!response.ok) {
				const error = await response.json();
				throw new Error(error.message || 'Unknown error');
			}

			const portfolio = await response.json();

			if (portfolio?.length) {
				data = portfolio[0];
				data.stocks = data.stocks.sort((a, b) => a.total - b.total);
			}
		} catch (error) {
			console.error('Failed to fetch portfolio:', error);
			alert(`Error: ${error.message}`);
		} finally {
			isLoading = false;
		}
	}
</script>

<svelte:head>
	<title>Insights</title>
	<meta name="description" content="Insights" />
</svelte:head>

{#if isLoading}
	<div in:fade>Loading...</div>
{:else}
	<div in:fade>
		<Chart {data} />
	</div>
{/if}
