<script lang="ts">
    import QueueSlider from "$lib/components/QueueSlider.svelte"
    import SuggestionInput from "$lib/components/SuggestionInput.svelte"
    import Error from "$lib/components/Error.svelte"
    import { type Suggestion, type Song } from "$lib/types.js"
    import { onMount } from "svelte"
    import SuggestionList from "$lib/components/SuggestionList.svelte"
    import { getQueueSongs, getSuggestions, joinRoom } from "$lib/utils.js"
    import type { FetchError } from "$lib/types.js"

    let { data } = $props()

    let queueSongs = $state<Song[]>([])
    let playingIndex = $state(0)

    let suggestions = $state<Suggestion[]>([])

    let returnError = $state<FetchError | null>()

    let wsUrl = ""

    onMount(async () => {
        // Join the room

        let sugg, queue, index
        ;[returnError, wsUrl] = await joinRoom(data.roomId)
        if (returnError) {
            return
        }

        ;[returnError, sugg] = await getSuggestions(data.roomId)
        if (returnError) {
            return
        }

        ;[returnError, queue, index] = await getQueueSongs(data.roomId)
        if (returnError) {
            return
        }

        queueSongs = queue
        suggestions = sugg
        playingIndex = index
    })
</script>

<!-- Check if the room exists -->
{#if returnError}
    <Error {returnError} />
{:else}
    <div class="flex w-full flex-col items-center justify-center p-4 lg:p-10">
        <QueueSlider {queueSongs} {playingIndex} />
        <div class="w-full py-6 lg:w-[30vw]">
            <SuggestionInput roomId={data.roomId} />
        </div>
        <div class="w-full py-6 lg:w-[30vw]">
            <SuggestionList {suggestions} roomId={data.roomId} />
        </div>
    </div>
{/if}
