<script lang="ts">
  import type { ArtistRef, TrackRef } from '$lib/api/types';
  import { api } from '$lib/api/client';
  import { playQueue, enqueueTracks } from '$lib/player/store.svelte';
  import { Play } from 'lucide-svelte';
  import ArtistMenu from './ArtistMenu.svelte';
  import CardActionCluster from './CardActionCluster.svelte';
  import Cover from './Cover.svelte';
  import { listArtistTracks } from '$lib/api/artists';

  let { artist }: { artist: ArtistRef } = $props();

  let queueing = $state(false);

  function shuffle<T>(items: T[]): T[] {
    const arr = items.slice();
    for (let i = arr.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [arr[i], arr[j]] = [arr[j], arr[i]];
    }
    return arr;
  }

  async function onPlayClick(e: MouseEvent) {
    e.preventDefault();
    e.stopPropagation();
    const tracks = await api.get<TrackRef[]>(`/api/artists/${artist.id}/tracks`);
    if (tracks.length === 0) return;
    playQueue(shuffle(tracks), 0);
  }

  async function onAddToQueue(e: MouseEvent) {
    e.preventDefault();
    e.stopPropagation();
    if (queueing) return;
    queueing = true;
    try {
      const tracks = await listArtistTracks(artist.id);
      if (tracks.length > 0) enqueueTracks(tracks);
    } finally {
      queueing = false;
    }
  }
</script>

<div class="card group relative">
  <a
    href={`/artists/${artist.id}`}
    class="block rounded focus-visible:ring-2 focus-visible:ring-accent"
  >
    <div class="art-wrap relative mx-auto aspect-square w-full overflow-hidden rounded-full bg-surface-hover">
      <Cover
        src={artist.cover_url}
        shape="round"
        fallback="artist"
        class="transition-transform group-hover:scale-[1.03]"
      />
      <button
        type="button"
        aria-label={`Play ${artist.name}`}
        onclick={onPlayClick}
        class="play-overlay absolute inset-0 m-auto flex h-12 w-12 items-center justify-center rounded-full"
      >
        <Play size={24} strokeWidth={1.5} fill="currentColor" />
      </button>
    </div>
    <div class="mt-2 truncate text-center text-sm font-medium text-text-primary">{artist.name}</div>
  </a>
  <CardActionCluster
    likeEntityType="artist"
    likeEntityId={artist.id}
    onAdd={onAddToQueue}
    addLabel={`Add ${artist.name} to queue`}
    addDisabled={queueing}
  >
    {#snippet menu()}
      <ArtistMenu artistId={artist.id} artistName={artist.name} />
    {/snippet}
  </CardActionCluster>
</div>

