<script lang="ts">
  import { pageTitle } from '$lib/branding';
  import { page } from '$app/state';
  import { createSearchTracksInfiniteQuery } from '$lib/api/queries';
  import TrackRow from '$lib/components/TrackRow.svelte';
  import LibrarySkeleton from '$lib/components/LibrarySkeleton.svelte';
  import ApiErrorBanner from '$lib/components/ApiErrorBanner.svelte';
  import { useDelayed } from '$lib/utils/useDelayed.svelte';
  import { playRadio } from '$lib/player/store.svelte';
  import type { TrackRef } from '$lib/api/types';

  const q = $derived((page.url.searchParams.get('q') ?? '').trim());
  const queryStore = $derived(q ? createSearchTracksInfiniteQuery(q) : null);
  const query = $derived(queryStore ? $queryStore : null);

  const tracks = $derived(query?.data?.pages?.flatMap((p) => p.items) ?? []);
  const total = $derived(query?.data?.pages?.[0]?.total ?? 0);
  const showSkeleton = useDelayed(() => !!query?.isPending);

  function onTrackPlay(_tracks: TrackRef[], index: number) {
    playRadio(_tracks[index].id);
  }
</script>

<svelte:head><title>{pageTitle('Search · Tracks')}</title></svelte:head>

<div class="space-y-4">
  <header>
    <a href={`/search?q=${encodeURIComponent(q)}`} class="text-sm text-text-secondary hover:text-text-primary">
      ← Back to search
    </a>
    <h1 class="mt-2 text-2xl font-semibold">Tracks matching '{q}'</h1>
    {#if !query?.isPending && !query?.isError && q}
      <p class="text-sm text-text-secondary">{total} {total === 1 ? 'track' : 'tracks'}</p>
    {/if}
  </header>

  {#if !q}
    <p class="text-text-secondary">No query — return to search to start typing.</p>
  {:else if query?.isError}
    <ApiErrorBanner error={query.error} onRetry={query.refetch} />
  {:else if showSkeleton.value && tracks.length === 0}
    <LibrarySkeleton variant="list" count={12} />
  {:else if total === 0}
    <p class="text-text-secondary">No track matches.</p>
  {:else}
    <div class="overflow-hidden rounded border border-border">
      {#each tracks as t, i (t.id)}
        <TrackRow tracks={tracks} index={i} onPlay={onTrackPlay} />
      {/each}
    </div>
    {#if query?.hasNextPage}
      <button
        type="button"
        class="w-full rounded bg-surface py-2 text-sm hover:bg-surface-hover disabled:opacity-60"
        disabled={query.isFetchingNextPage}
        onclick={() => query.fetchNextPage()}
      >
        {query.isFetchingNextPage ? 'Loading…' : 'Load more'}
      </button>
    {/if}
  {/if}
</div>
