<script>
	import { getCurrentWindow } from '@tauri-apps/api/window';
	import { onMount } from 'svelte';
	import { addTemplateFile } from '$lib/file_utils';
	import Popup from '$lib/components/Popup.svelte';
	let dragging = $state(false);
	let hasBlend = $state(false);
	let dropzoneEl = $state(null);

	let { version } = $props();

	let successPopup;
	let errorPopup;

	onMount(() => {
		const win = getCurrentWindow();
		let unlisten = () => {};

		win
			.onDragDropEvent((event) => {
				if (!dropzoneEl) return;

				const payload = event.payload;

				if (payload.type === 'enter') {
					hasBlend = payload.paths.some((p) => p.endsWith('.blend'));
					if (!hasBlend) return;
				}

				if (payload.type === 'leave') {
					dragging = false;
					return;
				}

				// 'enter', 'over', and 'drop' all have position data
				const rect = dropzoneEl.getBoundingClientRect();
				const scale = window.devicePixelRatio || 1;
				const cssX = payload.position.x / scale;
				const cssY = payload.position.y / scale;

				const isInside =
					cssX >= rect.left && cssX <= rect.right && cssY >= rect.top && cssY <= rect.bottom;

				if (payload.type === 'over') {
					dragging = hasBlend && isInside;
				} else if (payload.type === 'enter') {
					dragging = isInside;
				} else if (payload.type === 'drop') {
					dragging = false;
					if (hasBlend && isInside) {
						const blendFiles = payload.paths.filter((p) => p.endsWith('.blend'));
						if (blendFiles.length > 0) {
							console.log('Dropped Blender files:', blendFiles);
							blendFiles.forEach(async (file) => {
								if (version) {
									const result = await addTemplateFile(version, file);
									if (result.success) {
										successPopup.pop(result.message, 3000);
									} else {
										errorPopup.pop(result.message, 4000);
									}
								}
							});
						}
					}
				}
			})
			.then((fn) => {
				unlisten = fn;
			});

		return () => unlisten();
	});
</script>

<div class="dropzone" class:dragging bind:this={dropzoneEl}>Drop Blender Files</div>

<Popup bind:this={successPopup} type="confirm" />
<Popup bind:this={errorPopup} type="error" />

<style>
	.dropzone {
		height: 3rem;

		width: 100%;
		border-color: var(--light-accent);
		border-width: 3px;
		border-style: solid;
		border-radius: 5px;
		margin-top: 1rem;
		display: flex;
		box-sizing: border-box;
		align-items: center;
		justify-content: center;
		color: var(--light-accent);
		transition:
			border-color 0.15s,
			color 0.15s;
		cursor: pointer;
		transition: 0.2s ease-in-out;
	}

	.dropzone.dragging {
		height: 5rem;

		border-color: var(--accent);
		color: var(--accent);
	}
</style>
