<script>
	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 { deleteTemplate } from '$lib/library';

	import { launchBlenderVersion } from '$lib/library';
	import { notify } from '$lib/notification.js';
	let { template, version } = $props();
	let templateName = $derived(
		template
			.split('/')
			.pop()
			.replace('.blend', '')
			.replace(/\b\w/g, (c) => c.toUpperCase())
	);

	/**
	 * Handles the deletion of a template.
	 *
	 * @param {string} template - The template file path to delete.
	 */
	async function handleDelete(template) {
		const prompt = await show({
			title: 'Delete Template',
			message: `This will delete the "${templateName}" template.`,
			buttons: ['Cancel', 'Continue'],
			type: 'warning'
		});
		if (prompt == 'Continue') {
			const result = await deleteTemplate(version, template);
			if (result.success) {
				notify(result.message, 3000);
			} else {
				notify(result.message, 4000);
			}
		}
	}
</script>

{#if template == null}
	<div id="base-card">
		<Button fill={true} color="accent" onclick={() => launchBlenderVersion(version)}
			>Launch Base</Button
		>
	</div>
{:else}
	<div id="template-card">
		<div class="leftmenu">
			<Menu>
				<MenuItem onclick={() => handleDelete(template)}>Delete</MenuItem>
			</Menu>
			{templateName}
		</div>
		<Button style="small" onclick={() => launchBlenderVersion(version, template)}>→</Button>
	</div>
{/if}

<style>
	#base-card {
		margin-bottom: 1rem;
	}
	#template-card {
		height: 3rem;
		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 0.5rem 1rem;
		border-radius: 0.5rem;
		width: 100%;
		transition: width 0.3s ease;
		margin-bottom: 1rem;
	}
	.leftmenu {
		display: flex;
		flex-direction: row;
		align-items: center;
		gap: 1rem;
	}
</style>
