<script lang="ts">
  import { page } from '$app/state';
  import { createSearchArtistsInfiniteQuery } from '$lib/api/queries';
  import ArtistRow from '$lib/components/ArtistRow.svelte';
  import LibrarySkeleton from '$lib/components/LibrarySkeleton.svelte';
  import ApiErrorBanner from '$lib/components/ApiErrorBanner.svelte';
  import { useDelayed } from '$lib/utils/useDelayed.svelte';

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

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

<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">Artists matching '{q}'</h1>
    {#if !query?.isPending && !query?.isError && q}
      <p class="text-sm text-text-secondary">{total} {total === 1 ? 'artist' : 'artists'}</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 && artists.length === 0}
    <LibrarySkeleton variant="list" count={12} />
  {:else if total === 0}
    <p class="text-text-secondary">No artist matches.</p>
  {:else}
    <div>
      {#each artists as a (a.id)}
        <ArtistRow artist={a} />
      {/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>
