<script>
	import Button from './Button.svelte';
	import Progress from '$lib/components/Progress.svelte';
	import { downloadBlenderVersion } from '$lib/download.js';
	import { onMount } from 'svelte';
	import Popup from '$lib/components/Popup.svelte';

	let { release, installedVersions = [], downloadTasks } = $props();
	let linkIndex = $state(0);
	let selectedLink = $derived(release.links[linkIndex]);

	let installed = $derived(installedVersions.some((v) => v.version === selectedLink.version));

	async function handleDownload() {
		let result = await downloadBlenderVersion(selectedLink);
		if (result.success) {
			popup?.pop('Blender ' + selectedLink.version + ' has been installed', 2000);
		}
	}

	let percent = $derived(
		downloadTasks.find((task) => task.version === selectedLink.version)?.percent ?? 0
	);
	let downloading = $derived(percent > 0 && !installed);
	let unzipping = $derived(percent === 100 && !installed);
	onMount(() => {
		linkIndex = release.links.length - 1;
	});
	let popup = $state();
</script>

<Popup bind:this={popup}></Popup>
<div class="download" class:full-width={downloading || installed}>
	<div class="selectVersion {downloading}">
		<select class:disabled={downloading && !installed} bind:value={linkIndex}>
			{#each release.links as link, i (link.version)}
				<option value={i} selected={i === linkIndex}>{link.version}</option>
			{/each}
		</select>
	</div>

	<div class="progress" class:downloading={downloading || installed}>
		<Progress {unzipping} percent={installed ? 100 : percent} {installed}></Progress>
	</div>

	<Button
		disabled={installed}
		color={downloading ? 'accent' : 'black'}
		onclick={() => {
			if (downloading) {
				return;
			}
			downloading = true;
			handleDownload();
		}}>{installed ? 'Installed' : downloading ? 'Cancel' : 'Download'}</Button
	>
</div>

<style>
	.download {
		box-sizing: border-box;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		align-content: center;
		background-color: var(--light);
		padding: 0.5rem 0.5rem;
		border-radius: 0.5rem;
		width: 20rem;
		transition: width 0.3s ease;
	}

	.download.full-width {
		width: 100%;
	}
	.selectVersion {
		box-sizing: border-box;
		width: 5.5rem;
		min-width: 5.5rem;
	}
	.progress {
		flex: 1;
		opacity: 0;
	}
	.progress.downloading {
		opacity: 1;
	}
	select {
		cursor: pointer;
		background-color: none;
		outline: unset;
		border: none;
		background: none;
		appearance: none;
		-webkit-appearance: none;
		-moz-appearance: none;
		border-radius: 0;
		font-family: var(--font);
		font-size: 1rem;
		padding: 0.5rem 0.5rem;
		border-radius: 0.2rem;
		transition: color 0.3s ease;
		font-variant-numeric: tabular-nums;
	}
	select:hover {
		outline: 2px solid var(--accent);
	}
	select.disabled {
		color: var(--accent);
		pointer-events: none;
	}
</style>
