<script lang="ts">
  import { X } from 'lucide-svelte';
  import { player, closeQueueDrawer } from '$lib/player/store.svelte';
  import QueueTrackRow from './QueueTrackRow.svelte';

  function totalDurationLabel(tracks: { duration_ms: number }[]): string {
    const totalSec = Math.floor(
      tracks.reduce((s, tr) => s + (tr.duration_ms ?? 0), 0) / 1000
    );
    const m = Math.floor(totalSec / 60);
    const h = Math.floor(m / 60);
    return h > 0 ? `${h}h ${m % 60}m` : `${m} min`;
  }
</script>

{#if player.queueDrawerOpen}
  <button
    type="button"
    aria-label="Close queue backdrop"
    class="fixed inset-0 bg-obsidian/40 z-40"
    onclick={() => closeQueueDrawer()}
  ></button>
{/if}

<aside
  role="complementary"
  aria-label="Playback queue"
  aria-hidden={!player.queueDrawerOpen}
  class="fixed top-0 right-0 h-full w-full sm:w-96 bg-surface z-50
         transition-transform duration-200 flex flex-col
         {player.queueDrawerOpen ? 'translate-x-0' : 'translate-x-full'}"
>
  <div class="flex items-center justify-between border-b border-border px-4 py-3">
    <div>
      <h2 class="text-lg font-semibold">Queue</h2>
      <p class="text-xs text-text-secondary">
        {player.queue.length} {player.queue.length === 1 ? 'track' : 'tracks'}
        {#if player.queue.length > 0} · {totalDurationLabel(player.queue)}{/if}
      </p>
    </div>
    <button
      type="button"
      aria-label="Close queue"
      onclick={() => closeQueueDrawer()}
      class="text-text-secondary hover:text-text-primary"
    >
      <X size={20} />
    </button>
  </div>

  <div class="flex-1 overflow-y-auto">
    {#if player.queue.length === 0}
      <p class="text-text-secondary text-center p-8">No tracks queued.</p>
    {:else}
      {#each player.queue as track, i (track.id)}
        <QueueTrackRow {track} index={i} isCurrent={i === player.index} />
      {/each}
    {/if}
  </div>
</aside>
