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

  // onClose: when provided, renders an X button in the header so the
  //   slide-in drawer can dismiss itself. The embedded panel on the
  //   now-playing route (visible at lg+ widths) omits it.
  // closeButtonRef: bind:this hook so the drawer can focus the X for
  //   keyboard users on open.
  type Props = {
    onClose?: () => void;
    closeButtonRef?: HTMLButtonElement;
  };

  let { onClose, closeButtonRef = $bindable() }: Props = $props();

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

<div class="flex h-full flex-col">
  <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>
    {#if onClose}
      <button
        type="button"
        bind:this={closeButtonRef}
        aria-label="Close queue"
        onclick={onClose}
        class="text-text-secondary hover:text-text-primary"
      >
        <X size={20} />
      </button>
    {/if}
  </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>
</div>
