<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, parseSong, parseSuggestion } from "$lib/types.js"
    import { onDestroy, 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"
    import { io, Socket } from "socket.io-client"
    import { get_coords } from "$lib/gps.js"

    let { data } = $props()

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

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

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

    let socket: Socket

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

        let { coords, error } = await get_coords()
        if (error || coords == null) {
            // Default to Lido
            coords = { latitude: 46.6769043, longitude: 11.1851585 }
        }

        let sugg, queue, index
        ;[returnError] = await joinRoom(data.roomId, coords, data.pin)
        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

        // Setup websocket connection
        socket = io("/", { path: "/ws", transports: ["websocket"] })
        await socket.emitWithAck("join_room", { id: data.roomId })

        socket.on("queue_update", async (d) => {
            const songs = await Promise.all(d.queue.map(parseSong))
            queueSongs = songs
            playingIndex = d.index
        })

        socket.on("new_vote", async (d) => {
            const updated = await parseSuggestion(d.song)
            suggestions = suggestions.map((s) => (s.uuid === updated.uuid ? updated : s))
        })

        socket.on("new_song", async (d) => {
            const song = await parseSuggestion(d.song)
            suggestions = [...suggestions, song]
        })
    })
    onDestroy(() => {
        if (socket) socket.disconnect()
    })
</script>

<!-- Check if the room exists -->
{#if returnError}
    <Error {returnError} />
{:else}
    <div class="flex w-full flex-col items-center justify-center px-2 py-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 bind:suggestions roomId={data.roomId} />
        </div>
    </div>
{/if}
