<script>
	import CurrentPositionChart from '../../components/CurrentPositionChart.svelte';
	import { onMount } from 'svelte';
	import { authentication } from '../store.js';
	import { fade } from 'svelte/transition';
	import { goto } from '$app/navigation';
	import { getRequest } from '../../utils/api.js';

	let authToken;
	let data = {};
	let isLoading = true;
	let currency = 'USD';
	let total = 0;
	// Removed chartKey

	onMount(() => {
		return authentication.subscribe(async (auth) => {
			if (!auth || !auth.token) {
				await goto('/login');
			} else {
				authToken = auth.token;
				await fetchPortfolio();
			}
		});
	});

	async function fetchPortfolio() {
		try {
			const response = await getRequest(
				`${import.meta.env.VITE_STOCKS_HOST}/api/portfolios?currency=${currency}`,
				{},
				authToken
			);

			if (response.ok) {
				const portfolio = await response.json();
				if (portfolio?.length) {
					data = {
						...portfolio[0],
						stocks: [...portfolio[0].stocks].sort((a, b) => a.total - b.total)
					};
					total = portfolio[0].totalValue;
				} else {
					data = {};
					total = 0;
				}
			} else {
				const error = await response.json();
				console.error('Failed to find portfolio info:', error);
				data = {};
				total = 0;
			}
		} catch (error) {
			console.error('Failed to fetch insights:', error);
			await goto('/logout');
		} finally {
			isLoading = false;
		}
	}

	function updateCurrency(event) {
		currency = event.target.value;
		isLoading = true;
		fetchPortfolio();
	}
</script>

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

{#if isLoading}
	<div in:fade>Loading...</div>
{:else}
	<div in:fade>
		<select class="form-control order-select" on:change={updateCurrency} value={currency}>
			<option value="BRL">BRL</option>
			<option value="EUR">EUR</option>
			<option value="USD" selected>USD</option>
		</select>

		<CurrentPositionChart {data} {currency} {total} />
	</div>
{/if}