<script lang="ts">
	import {
		Pause,
		Play,
		Repeat,
		Repeat1,
		Shuffle,
		SkipBack,
		SkipForward,
	} from "@lucide/svelte";
	import { Button } from "$lib/components/ui/button";
	import { player } from "$lib/player/store.svelte";
	import { getAudioContext } from "./ctx.svelte";

	let audio = getAudioContext();

	// Derived state for icons/labels
	let isPlaying = $derived(!audio.paused);
	let shuffleMode = $derived(player.isShuffled);
	let repeatMode = $derived(player.repeatMode);
</script>

<div class="flex items-center gap-2">
    <!-- Shuffle -->
    <Button
        variant="ghost"
        size="icon"
        class={shuffleMode
            ? "text-primary hover:bg-primary/20 hover:text-primary"
            : "text-muted-foreground"}
        onclick={() => player.toggleShuffle()}
        title="Toggle Shuffle"
    >
        <Shuffle class="h-4 w-4" />
    </Button>

    <!-- Prev -->
    <Button
        variant="ghost"
        size="icon"
        onclick={() => {
            if (audio.currentTime > 3) {
                audio.seek(0);
            } else {
                player.prev();
            }
        }}
        disabled={player.history.length <= 1 && audio.currentTime <= 3}
        title="Previous"
    >
        <SkipBack class="h-5 w-5" />
    </Button>

    <!-- Play/Pause -->
    <Button
        variant="outline"
        size="icon"
        class="h-10 w-10 rounded-full"
        onclick={() => audio.toggle()}
        disabled={!player.currentTrack}
        title={isPlaying ? "Pause" : "Play"}
    >
        {#if isPlaying}
            <Pause class="h-5 w-5" />
        {:else}
            <Play class="h-5 w-5 ml-0.5" />
        {/if}
    </Button>

    <!-- Next -->
    <Button
        variant="ghost"
        size="icon"
        onclick={() => player.next()}
        disabled={player.queue.length === 0}
        title="Next"
    >
        <SkipForward class="h-5 w-5" />
    </Button>

    <!-- Repeat -->
    <Button
        variant="ghost"
        size="icon"
        class={repeatMode !== "off"
            ? "text-primary hover:bg-primary/20 hover:text-primary"
            : "text-muted-foreground"}
        onclick={() => player.toggleRepeat()}
        title="Toggle Repeat"
    >
        {#if repeatMode === "one"}
            <Repeat1 class="h-4 w-4" />
        {:else}
            <Repeat class="h-4 w-4" />
        {/if}
    </Button>
</div>
