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

  let previouslyFocused: HTMLElement | null = null;
  let closeButton: HTMLButtonElement | undefined = $state();

  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`;
  }

  $effect(() => {
    if (player.queueDrawerOpen) {
      previouslyFocused = document.activeElement as HTMLElement | null;
      // Defer to next microtask so the close button is rendered + visible
      // before we focus (the drawer may still be transitioning in).
      Promise.resolve().then(() => closeButton?.focus());
    } else if (previouslyFocused) {
      previouslyFocused.focus();
      previouslyFocused = null;
    }
  });
</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
  aria-label="Playback queue"
  aria-hidden={!player.queueDrawerOpen}
  inert={!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"
      bind:this={closeButton}
      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>
