<script>
	import CurrentMusicStore from '../../stores/currentMusic';
	import musicStore from '../../stores/musicStore';

	export let show = false;
	let showMusicMan = false;

	/**
	 * @type {{ musicTitle: string; musicUrl: string; musicArtist: string; }[]}
	 */
	let musicSelection = $musicStore;
	const sleep = (/** @type {number | undefined} */ ms) => new Promise((r) => setTimeout(r, ms));
	/**
	 * @param {{ musicTitle: string; musicUrl: string; musicArtist: string; }} v
	 */
	async function setSong(v) {
		$CurrentMusicStore.musicArtist = v.musicArtist;
		$CurrentMusicStore.musicTitle = v.musicTitle;
		$CurrentMusicStore.musicUrl = v.musicUrl;
		// THIS IS SUCH A DUMB WORKAROUND!!!!
		// WITHOUT THIS, THE VALUE OF FALSE IS NEVER REASSIGNED AND THE MUSIC WILL NEVER START PLAYING!!!
		$CurrentMusicStore.paused = true;
		await sleep(10);
		$CurrentMusicStore.paused = false;
		close();
	}
	function close() {
		show = !show;
		showMusicMan = false;
	}
</script>

{#if show}
	<div
		on:click={() => {
			close();
		}}
		class="h-screen w-screen bg-opacity-60 bg-black fixed top-0 left-0 z-10 py-20 "
	>
		<div on:click|stopPropagation class="h-full w-3/4 bg-red-100 mx-auto rounded-xl pb-3  overflow-y-auto">
			<div class="bg-indigo-200 rounded-t-xl p-3">
				<span
					on:click={() => {
						showMusicMan = true;
					}}>Music Selection</span
				>
			</div>
			<div class="grid grid-cols-1 xl:grid-cols-2 p-3">
				{#each musicSelection as v}
					<ul
						on:click={() => {
							setSong(v);
						}}
						class="mt-3 hover:cursor-pointer underline max-w-full shadow-lg hover:shadow-xl w-max bg-indigo-100 p-2 rounded-md"
					>
						{v.musicArtist} - {v.musicTitle}
					</ul>
				{/each}
				{#if showMusicMan}
					<ul
						on:click={() => {
							setSong({
								musicTitle: 'MUUUSIC MAN!',
								musicArtist: 'MatPat',
								musicUrl: '/music/MUUUSIC-MAN!.opus'
							});
						}}
						class="mt-3 hover:cursor-pointer underline max-w-full shadow-lg hover:shadow-xl w-max bg-indigo-100 p-2 rounded-md"
					>
						MUSIC MAN!!
					</ul>
				{/if}
			</div>
		</div>
	</div>
{/if}
