<svelte:options runes={true} />

<script lang="ts">
    import {Button} from "$lib/components/ui/button";
    import {onMount} from "svelte";
    import {playbackState} from "$lib/states/playback-state.svelte";
    import {toFixedNumber} from "$lib/formatting";
    let mounted = $state(false);

    function changeVolume(change: number) {
        if (playbackState.volume + change > 1) {
            playbackState.volume = 1;
        }
        else if (playbackState.volume + change < 0) {
            playbackState.volume = 0;
        }
        else {
            playbackState.volume = toFixedNumber(playbackState.volume + change, 2, 10) ;
        }

        if (playbackState.song) {
            playbackState.song.volume = playbackState.volume;
        }
    }

    function progressPercent() {
        return playbackState.progress / playbackState.duration * 100 || 0;
    }

    function displayTime(rawSeconds: number) {
        const intSeconds = Math.round(rawSeconds);
        const seconds = intSeconds % 60;
        const minutes = Math.floor((intSeconds / 60)) % 60;
        const hours = Math.floor((intSeconds / 3600));

        if (hours == 0) {
            return `${minutes.toString()}:${seconds.toString().padStart(2, 0)}`
        }
        else {
            return `${hours}:${minutes.toString().padStart(2, 0)}:${seconds.toString().padStart(2, 0)}`
        }
    }

    onMount(() => {
        mounted = true;
    })
</script>

<div class="flex flex-row gap-2">
    {#if mounted}
        <div class="flex flex-row gap-2">
            <p class="border p-2">Song: {playbackState.metaData.title}</p>
            <p class="border p-2">Volume: {playbackState.volume}</p>
            <p class="border p-2">{displayTime(playbackState.progress)}/{displayTime(playbackState.duration)}</p>
            <p class="border p-2">{progressPercent().toFixed(2)}%</p>
            <Button class="border p-2" onclick={() => changeVolume(-0.05)}>-</Button>
            <Button class="border p-2" onclick={() => changeVolume(0.05)}>+</Button>
            <Button class="border p-2" onclick={() => playbackState.song.currentTime -= 5}>{"<<"}</Button>
            {#if playbackState.paused}
                <Button onclick={() => playbackState.play()}>Play</Button>
            {:else}
                <Button onclick={() => playbackState.pause()}>Pause</Button>
            {/if}
            <Button class="border p-2" onclick={() => playbackState.song.currentTime += 5}>{">>"}</Button>
            <Button class="border p-2" onclick={() => playbackState.mode.next()}>{playbackState.mode.get()}</Button>
        </div>
    {:else}
        <p>Nothing going on here</p>
    {/if}
</div>
