<script>
	import {
		deleteVersion,
		launchBlenderVersion,
		toggleFavourite,
		registerVersion,
		selectVersion
	} from '$lib/library';
	import Button from '$lib/components/Button.svelte';
	import Menu from '$lib/components/Menu.svelte';
	import MenuItem from '$lib/components/MenuItem.svelte';

	import { show } from '$lib/components/Dialog.svelte';
	import { notify } from '$lib/notification.js';

	let { version, selectedVersion } = $props();

	let selected = $derived(version.version === selectedVersion?.version);

	async function handleDelete() {
		const prompt = await show({
			title: 'Delete',
			message: `This will remove Blender ${version.version} and all associated files from your system.`,
			buttons: ['Cancel', 'Continue'],
			type: 'warning'
		});
		if (prompt == 'Continue') {
			const result = await deleteVersion(version);
			if (result.success) {
				notify(result.message, 3000);
			} else {
				notify(result.message, 4000);
			}
		}
	}

	async function handleDefault() {
		const prompt = await show({
			title: 'Set as Default',
			message: `This will make Blender ${version.version} the default version on your system.`,
			buttons: ['Cancel', 'Continue'],
			type: 'info'
		});
		if (prompt == 'Continue') {
			notify('Version ' + version.version + ' is now the default on your system', 1500);
			registerVersion(version);
		}
	}
</script>
<div
	role="button"
	tabindex="0"
	onkeydown={() => {}}
	onclick={async () => {
		await selectVersion(version);
	}}
	ondblclick={async () => {
		console.log('double click', version);
		await launchBlenderVersion(version);
	}}
	id="card"
	class:selected
>
	<Button style="iconbutton" onclick={() => toggleFavourite(version)}
		><svg
			xmlns="http://www.w3.org/2000/svg"
			width="16"
			height="16"
			class="fav-btn {version.favourite ? 'fav' : ''}"
			viewBox="0 0 16 16"
		>
			<path
				d="M2 2v13.5a.5.5 0 0 0 .74.439L8 13.069l5.26 2.87A.5.5 0 0 0 14 15.5V2a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2"
			/>
		</svg>
	</Button>
	{version.version}
	<Menu>
		{#snippet children({ close })}
			<MenuItem
				onclick={async () => {
					await handleDelete();
					close();
				}}>Delete</MenuItem
			>
			<MenuItem
				onclick={async () => {
					await handleDefault();
					close();
				}}>Default</MenuItem
			>
		{/snippet}
	</Menu>
</div>

<style>
	#card {
		display: flex;
		flex-direction: row;
		position: relative;
		justify-content: space-between;
		width: 100%;
		min-width: 170px;
		max-width: 200px;
		border-radius: 5px;
		background-color: var(--light);
		padding: 1rem;
		display: flex;
		align-items: center;
		align-content: center;
		justify-content: space-between;
	}
	#card.selected {
		background-color: var(--light-accent);
	}
	#card:hover {
		outline: 2px solid var(--accent);
		outline-offset: -2px;
	}
	.fav-btn:hover {
		fill: var(--accent);
	}
	.fav-btn.fav {
		fill: var(--accent);
	}
</style>
