<script lang="ts">
  import type { TrackRef } from '$lib/api/types';
  import { formatDuration } from '$lib/media/duration';
  import { playQueue, enqueueTrack, playRadio } from '$lib/player/store.svelte';
  import LikeButton from './LikeButton.svelte';
  import TrackMenu from './TrackMenu.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);
  }

  function onRadioClick(e: MouseEvent) {
    e.stopPropagation();
    playRadio(track.id);
  }
</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_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="Play radio from this track"
    title="Play radio"
    onclick={onRadioClick}
    class="rounded p-1 text-text-secondary hover:text-text-primary"
  >📻</button>
  <button
    type="button"
    aria-label="Add to queue"
    onclick={onAddClick}
    class="rounded p-1 text-text-secondary hover:text-text-primary"
  >+</button>
  <TrackMenu {track} />
  <span class="tabular-nums text-text-secondary">{formatDuration(track.duration_sec)}</span>
</div>
