<script lang="ts">
  import { Play, MoreVertical, RefreshCcw } from 'lucide-svelte';
  import { useQueryClient } from '@tanstack/svelte-query';
  import type { Playlist, PlaylistTrack, TrackRef } from '$lib/api/types';
  import { user } from '$lib/auth/store.svelte';
  import { getPlaylist, refreshDiscover, refreshForYou } from '$lib/api/playlists';
  import { playlistTrackToRef } from '$lib/playlists/playlistTrackToRef';
  import { errCode } from '$lib/api/errors';
  import { qk } from '$lib/api/queries';
  import { playQueue } from '$lib/player/store.svelte';
  import { pushToast } from '$lib/stores/toast.svelte';

  let { playlist }: { playlist: Playlist } = $props();

  const isOwn = $derived(user.value?.id === playlist.user_id);
  const isDiscover = $derived(playlist.system_variant === 'discover');
  const isForYou = $derived(playlist.system_variant === 'for_you');
  const isSystem = $derived(playlist.system_variant != null);
  const refreshLabel = $derived(
    isDiscover ? 'Refresh Discover' : isForYou ? 'Refresh For You' : 'Refresh',
  );

  const queryClient = useQueryClient();

  let starting = $state(false);
  let menuOpen = $state(false);

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

  // Map PlaylistTrack rows to TrackRef shape and drop tracks whose
  // upstream file has been removed (track_id null).
  function toTrackRefs(rows: PlaylistTrack[]): TrackRef[] {
    return rows
      .map((r) => playlistTrackToRef(r))
      .filter((t): t is TrackRef => t !== null);
  }

  async function onPlayClick(e: MouseEvent) {
    e.preventDefault();
    e.stopPropagation();
    if (starting) return;
    starting = true;
    try {
      const detail = await getPlaylist(playlist.id);
      const refs = toTrackRefs(detail.tracks);
      if (refs.length > 0) {
        // System playlists default to shuffle so replaying within a
        // day feels different. User playlists keep stored order.
        // Explicit refresh moved to the kebab menu — playing no
        // longer rebuilds the snapshot.
        playQueue(refs, 0, { shuffle: playlist.system_variant != null });
      }
    } finally {
      starting = false;
    }
  }

  async function onRefresh(e: MouseEvent) {
    e.preventDefault();
    e.stopPropagation();
    menuOpen = false;
    try {
      if (isDiscover) {
        await refreshDiscover();
        pushToast('Discover refreshed.');
      } else if (isForYou) {
        await refreshForYou();
        pushToast('For You refreshed.');
      } else {
        return;
      }
      await queryClient.invalidateQueries({ queryKey: qk.playlist(playlist.id) });
      await queryClient.invalidateQueries({ queryKey: qk.playlists() });
    } catch (err: unknown) {
      pushToast(`Refresh failed: ${errCode(err)}`, 'error');
    }
  }
</script>

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

<div class="card relative">
  {#if isSystem}
    <div class="kebab-wrap absolute right-1 top-1 z-10">
      <button
        type="button"
        aria-label="Playlist actions"
        aria-haspopup="menu"
        aria-expanded={menuOpen}
        onclick={toggleMenu}
        class="rounded p-1 text-text-muted hover:bg-surface-hover hover:text-text-primary"
      >
        <MoreVertical size={16} strokeWidth={1} />
      </button>
      {#if menuOpen}
        <!-- svelte-ignore a11y_click_events_have_key_events -->
        <!-- onclick is a stopPropagation guard against the window-level
             click-closes-menu pattern; not user-facing interaction. -->
        <div
          role="menu"
          tabindex="-1"
          class="absolute right-0 top-full z-20 mt-1 w-44 rounded-md border border-border bg-surface p-1 shadow-lg"
          onclick={(e) => e.stopPropagation()}
        >
          <button
            type="button"
            role="menuitem"
            onclick={onRefresh}
            class="flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm text-text-primary hover:bg-surface-hover"
          >
            <RefreshCcw size={14} strokeWidth={1} />
            {refreshLabel}
          </button>
        </div>
      {/if}
    </div>
  {/if}
  <a
    href={`/playlists/${playlist.id}`}
    class="group flex w-full flex-col items-start gap-2 rounded-md p-2 text-left hover:bg-surface-hover"
  >
    <div class="art-wrap relative aspect-square w-full overflow-hidden rounded-md bg-surface-hover">
      {#if playlist.cover_url}
        <img
          src={playlist.cover_url}
          alt=""
          class="h-full w-full object-cover transition-transform group-hover:scale-105"
        />
      {:else}
        <div class="flex h-full w-full items-center justify-center text-text-muted">
          <span class="text-xs">No tracks yet</span>
        </div>
      {/if}
      <button
        type="button"
        aria-label={`Play ${playlist.name}`}
        onclick={onPlayClick}
        disabled={starting || playlist.track_count === 0}
        class="play-overlay absolute inset-0 m-auto flex h-12 w-12 items-center justify-center rounded-full disabled:opacity-50"
      >
        <Play size={24} strokeWidth={1.5} fill="currentColor" class="ml-0.5" />
      </button>
    </div>
    <div class="w-full min-w-0">
      <div class="truncate text-sm font-medium text-text-primary">{playlist.name}</div>
      <div class="truncate text-xs text-text-muted">
        {playlist.track_count} {playlist.track_count === 1 ? 'track' : 'tracks'}
        {#if !isOwn}
          · by {playlist.owner_username}
        {/if}
      </div>
    </div>
  </a>
</div>

