<script lang="ts">
  import type { TrackRef } from '$lib/api/types';
  import { playQueue, enqueueTrack } from '$lib/player/store.svelte';
  import { FALLBACK_COVER, coverUrl } from '$lib/media/covers';
  import TrackMenu from './TrackMenu.svelte';
  import CardActionCluster from './CardActionCluster.svelte';

  // Horizontal compact track row — cover thumb on the left, title +
  // artist on the right. Mirrors Android's CompactTrackTile so the
  // Most Played section reads the same way across platforms (three
  // narrow rows that scroll together).

  let {
    track,
    sectionTracks,
    index
  }: {
    track: TrackRef;
    sectionTracks: TrackRef[];
    index: number;
  } = $props();

  const cover = $derived(coverUrl(track.album_id));

  function onImgError(e: Event) {
    (e.currentTarget as HTMLImageElement).src = FALLBACK_COVER;
  }

  function onClick() {
    playQueue(sectionTracks, index);
  }

  function onAddToQueue(e: MouseEvent) {
    e.preventDefault();
    e.stopPropagation();
    enqueueTrack(track);
  }
</script>

<div class="card group relative w-72">
  <button
    type="button"
    aria-label={`Play ${track.title}`}
    onclick={onClick}
    class="flex w-full items-center gap-2 rounded-md p-1 pr-12 text-left
           hover:bg-surface-hover focus-visible:ring-2 focus-visible:ring-accent"
  >
    <div class="h-12 w-12 flex-shrink-0 overflow-hidden rounded bg-surface-hover">
      <img
        src={cover}
        alt=""
        class="h-full w-full object-cover"
        loading="lazy"
        onerror={onImgError}
      />
    </div>
    <div class="min-w-0 flex-1">
      <div class="truncate text-sm font-medium text-text-primary">{track.title}</div>
      <div class="truncate text-xs text-text-secondary">{track.artist_name}</div>
    </div>
  </button>
  <CardActionCluster
    likeEntityType="track"
    likeEntityId={track.id}
    onAdd={onAddToQueue}
    addLabel={`Add ${track.title} to queue`}
  >
    {#snippet menu()}
      <TrackMenu {track} />
    {/snippet}
  </CardActionCluster>
</div>
