<script lang="ts">
  import { MoreVertical, Shuffle, Repeat, Repeat1, ListMusic, Volume2 } from 'lucide-svelte';
  import {
    player, toggleShuffle, cycleRepeat, toggleQueueDrawer, setVolume
  } from '$lib/player/store.svelte';
  import TrackMenuItem from './TrackMenuItem.svelte';
  import TrackMenuDivider from './TrackMenuDivider.svelte';

  let { direction = 'up' }: { direction?: 'up' | 'down' } = $props();

  let menuOpen = $state(false);

  function toggleMenu(e: MouseEvent) {
    e.stopPropagation();
    menuOpen = !menuOpen;
  }

  const repeatLabel = $derived(
    player.repeat === 'off' ? 'Repeat off' :
    player.repeat === 'all' ? 'Repeat all' : 'Repeat one'
  );

  const repeatIcon = $derived(player.repeat === 'one' ? Repeat1 : Repeat);

  function onShuffle() {
    toggleShuffle();
  }
  function onRepeat() {
    cycleRepeat();
  }
  function onQueue() {
    toggleQueueDrawer();
    menuOpen = false;
  }
  function onVolume(e: Event) {
    setVolume(Number((e.currentTarget as HTMLInputElement).value));
  }
</script>

<svelte:window onclick={() => { menuOpen = false; }} onkeydown={(e) => e.key === 'Escape' && (menuOpen = false)} />

<div class="relative inline-block">
  <button
    type="button"
    aria-label="Player options"
    aria-haspopup="menu"
    aria-expanded={menuOpen}
    onclick={toggleMenu}
    class="rounded p-1 text-text-muted hover:text-text-primary min-h-[44px] min-w-[44px]
           flex items-center justify-center"
  >
    <MoreVertical size={18} strokeWidth={1} />
  </button>

  {#if menuOpen}
    <div
      role="menu"
      tabindex="-1"
      class="absolute right-0 z-20 w-56 rounded-md border border-border bg-surface p-1 shadow-lg
             {direction === 'up' ? 'bottom-full mb-1' : 'top-full mt-1'}"
      onclick={(e) => e.stopPropagation()}
      onkeydown={(e) => e.stopPropagation()}
    >
      <TrackMenuItem
        icon={Shuffle}
        label={player.shuffle ? 'Shuffle on' : 'Shuffle off'}
        onclick={onShuffle}
      />
      <TrackMenuItem
        icon={repeatIcon}
        label={repeatLabel}
        onclick={onRepeat}
      />
      <TrackMenuItem
        icon={ListMusic}
        label={player.queueDrawerOpen ? 'Hide queue' : 'Show queue'}
        onclick={onQueue}
      />

      <TrackMenuDivider />

      <div class="flex items-center gap-2 px-2 py-1.5">
        <Volume2 size={14} strokeWidth={1} class="shrink-0 text-text-secondary" />
        <input
          type="range"
          aria-label="Volume"
          min="0"
          max="1"
          step="0.01"
          value={player.volume}
          oninput={onVolume}
          class="flex-1 accent-accent"
        />
      </div>
    </div>
  {/if}
</div>
