<style>
	.icon {
		@apply text-gray-400;
		@apply text-right;
		@apply cursor-pointer;
	}

	.icon.active,
	.icon:hover {
		@apply text-red-500;
	}
</style>

<script lang="ts">
	import { page } from '$app/stores';
	import Trash from '$lib/icons/Trash.svelte';
	import Panel from '$lib/components/ui/Panel.svelte';
	import Button from '$lib/components/ui/Button.svelte';
	import { clickOutside } from '$lib/helpers/clickOutside.js';
	const { adminMode, prediction, predictionRemove } = $page.data;

	let active = false;
	export let item;

	function remove() {
		predictionRemove(item);
		if (adminMode) {
			const section = $prediction.sections.find((s) => s.id === item.section);
			section.items = section.items.filter((i) => i !== item);
			prediction.set($prediction);
		}
	}
	function onClick(e) {
		e.stopPropagation();
		e.preventDefault();
		if (!item.variables.some((v) => v.value?.length > 0)) {
			remove();
			return;
		}
		active = true;
	}

	function onConfirm(e) {
		e.stopPropagation();
		active = false;
		remove();
	}

	function cancel() {
		active = false;
	}
</script>

<div
	class="relative flex h-8 w-8 items-center justify-center"
	on:click={onClick}
	use:clickOutside
	on:click_outside={cancel}
>
	<span class:active class="icon">
		<Trash />
	</span>
	{#if active}
		<Panel padding="p-1" class="absolute right-0 top-8 w-64 border border-gray-100 bg-white">
			<Button variant="danger" size="sm" fullWidth={true} on:click={onConfirm}
				>Löschen bestätigen</Button
			>
		</Panel>
	{/if}
</div>
