<script lang="ts">
	import { onMount } from 'svelte';
	let { url, dismiss } = $props();

	let visible = $state(false);
	let progress = $state(0);
	let filename = $state('');
	onMount(async () => {
		if (!url) return;

		try {
			visible = true;

			const response = await fetch(url);
			if (!response.ok) throw new Error('Download failed');

			const contentDisposition: string = response?.headers?.get('content-disposition');
			filename = contentDisposition.split('filename=')[1];
			const contentLength: number = Number(response?.headers?.get('content-length'));
			const reader = response?.body?.getReader();
			const chunks: Uint8Array[] = [];
			let receivedLength = 0;

			while (true) {
				const { done, value }: ReadableStreamReadResult<Uint8Array> = await reader.read();
				if (done) break;
				if (value) {
					chunks.push(value);
					receivedLength += value.length;
					progress = Math.round((receivedLength / contentLength) * 100);
				}
			}

			const blob = new Blob(chunks);
			const downloadUrl = URL.createObjectURL(blob);

			const a = document.createElement('a');
			a.href = downloadUrl;
			a.download = filename;
			a.click();

			URL.revokeObjectURL(downloadUrl);

			setTimeout(() => {
				visible = false;
			}, 1500); // auto-dismiss
		} catch (err) {
			console.error(err);
			visible = false;
		}
	});
</script>

{#if visible}
	<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-sm font-mono">
		<div class="w-[90%] max-w-sm rounded-2xl border border-green-400 bg-[#000f00] p-6 text-green-300 shadow-2xl text-sm">
			<p class="mb-2 text-center text-cyan-300">
				Downloading <span class="text-green-400 font-semibold">{filename}</span>
			</p>
			<div class="w-full h-4 rounded-md bg-black border border-green-500 overflow-hidden">
				<div
					class="h-full bg-gradient-to-r from-green-400 to-green-600 transition-all duration-300"
					style="width: {progress}%"
				/>
			</div>
			<p class="mt-2 text-center text-pink-400">{progress}%</p>
		</div>
	</div>
{/if}
