<script lang="ts">
  import { Play } from 'lucide-svelte';
  import type { Playlist, PlaylistTrack, TrackRef } from '$lib/api/types';
  import { user } from '$lib/auth/store.svelte';
  import { getPlaylist } from '$lib/api/playlists';
  import { playQueue } from '$lib/player/store.svelte';

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

  const isOwn = $derived(user.value?.id === playlist.user_id);

  let starting = $state(false);

  // Map PlaylistTrack rows to TrackRef shape and drop tracks whose upstream
  // file has been removed (track_id is null). Mirrors PlaylistTrackRow's
  // liveTrack derivation.
  function toTrackRefs(rows: PlaylistTrack[]): TrackRef[] {
    const out: TrackRef[] = [];
    for (const r of rows) {
      if (!r.track_id) continue;
      out.push({
        id: r.track_id,
        title: r.title,
        album_id: r.album_id ?? '',
        album_title: r.album_title,
        artist_id: r.artist_id ?? '',
        artist_name: r.artist_name,
        duration_sec: r.duration_sec,
        stream_url: r.stream_url ?? ''
      });
    }
    return out;
  }

  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) {
        playQueue(refs, 0);
      }
    } finally {
      starting = false;
    }
  }
</script>

<div class="card relative">
  <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>

<style>
  .play-overlay {
    background: var(--fs-accent);
    color: var(--fs-parchment);
    opacity: 0;
    transition: opacity 150ms ease;
  }
  @media (hover: hover) {
    .card:hover .play-overlay { opacity: 1; }
  }
  @media (hover: none) {
    .play-overlay { opacity: 1; }
  }
</style>
