<script lang="ts">
	import { PUBLIC_VERSION } from '$env/static/public';
	import supportedFormats from '$lib/common/supportedFormats.json';
	import Loader from '$lib/components/Loader.svelte';
	import { onMount } from 'svelte';

	let source = $state('youtube');
	let link = $state('');
	let format = $state('mp3');
	let showModal = $state(false);
	let href = $state('');
	let disabled = $state(true);
	let metadata = $state(false);
	let downloading = $state(false);
	let logs = $state('');
	let logId = undefined;

	const formats = Object.keys(supportedFormats).map((f) => {
		return { value: f, label: f.toUpperCase() };
	});

	const toggleModal = () => {
		showModal = !showModal;
	};

	onMount(() => {
		document.cookie = 'downloading=0';
	});

	const readLogs = () => {
		logId = setInterval(() => {
			logs += "We're downloading <br>";
		}, 2000);
	};
	const onClick = () => {
		let checkIterations = 0;
		link = '';
		downloading = true;
		document.cookie = 'downloading=1';

		readLogs();

		const id = setInterval(() => {
			if (document.cookie.includes('downloading=0') || checkIterations > 3) {
				downloading = false && clearInterval(id) && clearInterval(logId);
			}
			checkIterations++;
		}, 1000);
	};

	const createAnchor = () => {
		if (!(source && link && format)) {
			disabled = true;
			return;
		}

		try {
			new URL(link);
			disabled = false;
		} catch (err) {
			/*
			if (err.code === 'ERR_INVALID_URL') {

			}
			*/
			disabled = true;
			return;
		}

		const searchParams = new URLSearchParams();
		searchParams.append('source', source);
		searchParams.append('link', link);
		searchParams.append('format', format);

		if (metadata) searchParams.append('metadata', '1');

		href = `/download?${searchParams.toString()}`;
	};

	$effect(() => {
		createAnchor();
		// Auto selected the radio button based on url regex
		if (link.includes('spotify')) {
			source = 'spotify';
		} else if (link.includes('youtube')) {
			source = 'youtube';
		}
	});
</script>

<div
	id="wrapper"
	class="relative mx-auto rounded-lg bg-black p-6 text-[#00ff7f] shadow-lg sm:max-w-sm sm:border-4 sm:border-[#00ff7f] md:mt-10 md:max-w-md lg:max-w-lg 2xl:max-w-2xl"
>
	<div
		id="loader"
		class={[
			'absolute inset-0 z-10 flex items-center justify-center bg-black/20 backdrop-blur-xs',
			{ downloading }
		]}
	>
		<Loader />
		{@html logs}
	</div>

	<!-- Info Icon -->
	<button
		onclick={toggleModal}
		class="absolute top-3 right-3 text-[#ff007f] transition hover:text-[#ff3399]"
		aria-label="Open Info Modal"
	>
		<svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" class="h-6 w-6" viewBox="0 0 24 24">
			<path
				d="M12 0C5.373 0 0 5.373 0 12c0 6.627 5.373 12 12 12s12-5.373 12-12C24 5.373 18.627 0 12 0zm.75 18h-1.5v-6h1.5v6zm0-8h-1.5V8h1.5v2z"
			/>
		</svg>
	</button>

	<p id="title" class="mb-6 text-center text-[#00e5ff]">🐙 Scaricatore 🐙</p>
	<form class="space-y-6">
		<!-- Source Selection -->
		<fieldset class="space-y-4">
			<legend class="text-[#00e5ff]">Choose Source:</legend>

			<label class="flex items-center space-x-3">
				<input type="radio" name="source" value="youtube" bind:group={source} class="retro-radio" />
				<span>YouTube</span>
			</label>

			<label class="flex items-center space-x-3">
				<input
					disabled
					type="radio"
					name="source"
					value="spotify"
					bind:group={source}
					class="retro-radio"
				/>
				<span class="not-available">Spotify</span>
			</label>

			<label class="flex items-center space-x-3">
				<input type="radio" name="source" value="other" bind:group={source} class="retro-radio" />
				<span>
					Any other website
					<!-- 
						(<a
						href="https://github.com/yt-dlp/yt-dlp/blob/master/supportedsites.md"
						target="_blank"
						rel="noopener noreferrer"
						class="text-[#ff3399] hover:underline"
						>supported sites
					</a>)
					-->
				</span>
			</label>
		</fieldset>

		<!-- Link Input -->
		<div>
			<label for="link" class="mb-2 block text-[#00e5ff]"> Enter Video Link: </label>
			<input
				name="link"
				type="url"
				id="link"
				bind:value={link}
				required
				placeholder="Paste your link here"
				class="w-full rounded-lg border-4 border-[#00ff7f] bg-[#001a00] px-4 py-3 text-[#00ff7f] focus:border-[#ff3399] focus:outline-none"
			/>
		</div>

		<!-- Format Selection -->
		<div>
			<label for="format" class="mb-2 block text-[#00e5ff]"> Choose Format: </label>
			<select
				id="format"
				name="format"
				bind:value={format}
				class="w-full rounded-lg border-4 border-[#00ff7f] bg-[#001a00] px-4 py-3 text-[#00ff7f] focus:border-[#ff3399] focus:outline-none"
			>
				{#each formats as format}
					<option value={format.value}>{format.label}</option>
				{/each}
			</select>
		</div>

		<!-- Metadata -->
		<div>
			<label for="metadata" class="mb-2 block text-[#00e5ff]"
				>Set filename (<span class="text-red-700">SLOW</span>)</label
			>
			<input
				type="checkbox"
				id="metadata"
				name="metadata"
				bind:checked={metadata}
				class="rounded-lg border-4 border-[#00ff7f] bg-[#001a00] px-4 py-3 text-[#00ff7f] focus:border-[#ff3399] focus:outline-none"
			/>
		</div>

		<a
			id="btn-download"
			{href}
			rel="external"
			onclick={onClick}
			class="{disabled
				? 'disabled'
				: ''} block w-full rounded-lg border-4 border-[#ff3399] bg-[#ff007f] px-4 py-3 text-center text-4xl text-black transition hover:bg-[#ff3399] active:border-yellow-500"
		>
			DOWNLOAD
		</a>
	</form>
</div>

<!-- Modal -->
{#if showModal}
	<div class="bg-opacity-80 fixed inset-0 z-50 flex items-center justify-center bg-black">
		<div
			class="w-4/5 max-w-lg rounded-lg border-4 border-[#00ff7f] bg-[#002b00] p-6 text-center text-[#00ff7f]"
		>
			<h2 class="mb-4 text-lg">🐙 Scaricatore v{PUBLIC_VERSION} 🐙</h2>
			<p>
				This app allows you to download Spotify playlists and YouTube videos directly. Choose your
				source, paste the link, and select a format to start downloading!
			</p>
			<span class="mt-10 block">
				<a class="text-[#00e5ff] underline" href="https://git.pweapon.org/odo/dl.emersa.it"
					>Click here for the source code</a
				>
			</span>
			<button
				onclick={toggleModal}
				class="mt-6 rounded-lg border-4 border-[#ff3399] bg-[#ff007f] px-4 py-2 text-black hover:bg-[#ff3399]"
			>
				Close
			</button>
		</div>
	</div>
{/if}

<style>
	* {
		font-family: 'Press Start 2P', cursive;
	}

	@media (max-height: 1000px) {
		* {
			font-size: 10px;
		}
	}
	@media (min-width: 1024px) {
		* {
			font-size: 12px;
		}
	}

	#loader {
		display: none;
	}
	#loader.downloading {
		display: grid;
		justify-items: center;
		align-items: center;
	}
	.not-available {
		text-decoration-line: line-through;
		text-decoration-color: red;
	}

	.retro-radio {
		appearance: none;
		background-color: #000;
		border: 2px solid #00ff7f;
		width: 20px;
		height: 20px;
		cursor: pointer;
	}

	.retro-radio:checked {
		background-color: #00ff7f;
		box-shadow:
			0 0 4px #00ff7f,
			0 0 10px #00ff7f;
	}

	input[type='url'],
	select {
		font-family: inherit;
	}

	#title {
		font-size: 18px;
	}

	#btn-download {
		font-size: 26px;
		transition: opacity 0.3s ease;
	}
	a.disabled {
		pointer-events: none;
		cursor: default;
		opacity: 0.5;
	}
</style>
