<script lang="ts">
	import { browser } from '$app/environment';
	import { onDestroy, onMount } from 'svelte';

	function randomInRange(min: number, max: number) {
		return Math.random() * (max - min) + min;
	}

	let i = 0;
	let confettiCanvas: HTMLCanvasElement;

	let f: number;
	onDestroy(() => {
		if (browser) {
			cancelAnimationFrame(f);
		}
	});

	onMount(async () => {
		const confetti = (await import('./confetti')).default;
		confettiCanvas.width = window.innerWidth / 2;
		confettiCanvas.height = window.innerHeight / 2;

		const update = confetti.create(confettiCanvas);

		function frame() {
			i = (i + 1) % 1000;
			if (i % 10 === 0) {
				update({
					particleCount: 1,
					startVelocity: 0,
					useWorker: true,
					origin: {
						x: Math.random(),
						// since particles fall down, skew start toward the top
						y: Math.random()
					},
					colors: ['#d9c556'],
					shapes: ['circle'],
					gravity: randomInRange(0.4, 0.6),
					scalar: randomInRange(0.1, 0.5),
					drift: randomInRange(-2, 2),
					disableForReducedMotion: true
				});
			}

			f = requestAnimationFrame(frame);
		}
		frame();
	});
</script>

<canvas style="height: 100vh; width: 100vw" bind:this={confettiCanvas} />

<style>
	canvas {
		position: fixed;
		top: 0px;
		left: 0px;
		pointer-events: none;
		user-select: none;
	}
</style>
