<script lang="ts">
  import { MoreVertical, Heart, HeartOff, ListMusic, Plus } from 'lucide-svelte';
  import { useQueryClient } from '@tanstack/svelte-query';
  import { createLikedIdsQuery, likeEntity, unlikeEntity } from '$lib/api/likes';
  import { listArtistTracks } from '$lib/api/artists';
  import { enqueueTracks } from '$lib/player/store.svelte';
  import AddToPlaylistMenu from './AddToPlaylistMenu.svelte';
  import TrackMenuItem from './TrackMenuItem.svelte';
  import TrackMenuDivider from './TrackMenuDivider.svelte';
  import type { TrackRef } from '$lib/api/types';

  let {
    artistId,
    artistName,
    tracks,
    direction = 'down'
  }: {
    artistId: string;
    artistName: string;
    /** Pre-loaded tracks; menu fetches lazily on action click when omitted. */
    tracks?: TrackRef[];
    /** Open above the trigger when used near the bottom of the viewport. */
    direction?: 'up' | 'down';
  } = $props();

  let menuOpen = $state(false);
  let addOpen = $state(false);
  // Lazy track cache — see AlbumMenu.svelte for the same reasoning.
  // Starts null so the `tracks` prop is read inside ensureTracks() each
  // call rather than captured at component-creation time.
  let cachedTracks: TrackRef[] | null = $state(null);

  const queryClient = useQueryClient();
  const likedQ = $derived(createLikedIdsQuery());
  const liked = $derived.by(() => {
    const data = $likedQ?.data;
    if (!data) return false;
    return data.artist_ids.includes(artistId);
  });

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

  function closeAll() {
    menuOpen = false;
    addOpen = false;
  }

  async function ensureTracks(): Promise<TrackRef[]> {
    if (cachedTracks) return cachedTracks;
    if (tracks) {
      cachedTracks = tracks;
      return tracks;
    }
    const fetched = await listArtistTracks(artistId);
    cachedTracks = fetched;
    return fetched;
  }

  async function onAddAllToQueue() {
    const ts = await ensureTracks();
    enqueueTracks(ts);
    closeAll();
  }

  async function onOpenAddToPlaylist() {
    await ensureTracks();
    menuOpen = false;
    addOpen = true;
  }

  async function onToggleLike() {
    closeAll();
    if (liked) {
      await unlikeEntity(queryClient, 'artist', artistId);
    } else {
      await likeEntity(queryClient, 'artist', artistId);
    }
  }

  function onKeydown(e: KeyboardEvent) {
    if (!menuOpen && !addOpen) return;
    if (e.key === 'Escape') {
      e.preventDefault();
      closeAll();
    }
  }
</script>

<svelte:window onclick={() => { menuOpen = false; addOpen = false; }} onkeydown={onKeydown} />

<div class="relative inline-block">
  <button
    type="button"
    aria-label={`Artist actions for ${artistName}`}
    aria-haspopup="menu"
    aria-expanded={menuOpen}
    onclick={toggleMenu}
    class="rounded p-1 text-text-muted hover:text-text-primary"
  >
    <MoreVertical size={16} strokeWidth={1} />
  </button>

  {#if menuOpen}
    <!-- svelte-ignore a11y_click_events_have_key_events -->
    <!-- See AlbumMenu.svelte for the same intentional pattern: the
         onclick is a stopPropagation guard against the window-level
         menu-closer; Escape-to-close is on svelte:window onkeydown. -->
    <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()}
    >
      <TrackMenuItem
        icon={liked ? HeartOff : Heart}
        label={liked ? 'Unlike artist' : 'Like artist'}
        onclick={onToggleLike}
      />
      <TrackMenuDivider />
      <TrackMenuItem icon={Plus} label="Add all to queue" onclick={onAddAllToQueue} />
      <TrackMenuItem icon={ListMusic} label="Add all to playlist…" onclick={onOpenAddToPlaylist} />
    </div>
  {/if}

  {#if addOpen && cachedTracks}
    <AddToPlaylistMenu tracks={cachedTracks} onClose={closeAll} />
  {/if}
</div>
