<script lang="ts">
  import type { TrackRef } from '$lib/api/types';
  import { formatDuration } from '$lib/media/duration';
  import { playQueue, enqueueTrack } from '$lib/player/store.svelte';
  import LikeButton from './LikeButton.svelte';

  type PlayHandler = (tracks: TrackRef[], index: number) => void;

  let {
    tracks,
    index,
    onPlay
  }: { tracks: TrackRef[]; index: number; onPlay?: PlayHandler } = $props();

  const track = $derived(tracks[index]);

  function activate() {
    if (onPlay) onPlay(tracks, index);
    else playQueue(tracks, index);
  }

  function onRowClick() {
    activate();
  }

  function onRowKey(e: KeyboardEvent) {
    if (e.key === 'Enter' || e.key === ' ') {
      e.preventDefault();
      activate();
    }
  }

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

<div
  role="button"
  tabindex="0"
  aria-label={track.title}
  onclick={onRowClick}
  onkeydown={onRowKey}
  class="grid w-full cursor-pointer grid-cols-[32px_1fr_auto_auto_auto] items-center gap-4 px-3 py-2 text-left text-sm odd:bg-surface/50 hover:bg-surface focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent"
>
  <span class="text-right tabular-nums text-text-secondary">
    {track.track_number ?? '—'}
  </span>
  <span class="truncate">{track.title}</span>
  <LikeButton entityType="track" entityId={track.id} />
  <button
    type="button"
    aria-label="Add to queue"
    onclick={onAddClick}
    class="rounded p-1 text-text-secondary hover:text-text-primary"
  >+</button>
  <span class="tabular-nums text-text-secondary">{formatDuration(track.duration_sec)}</span>
</div>
