<script lang="ts">
  import { pageTitle } from '$lib/branding';
  import { page } from '$app/state';
  import { createSearchAlbumsInfiniteQuery } from '$lib/api/queries';
  import AlbumCard from '$lib/components/AlbumCard.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 ? createSearchAlbumsInfiniteQuery(q) : null);
  const query = $derived(queryStore ? $queryStore : null);

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

<svelte:head><title>{pageTitle('Search · Albums')}</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">Albums matching '{q}'</h1>
    {#if !query?.isPending && !query?.isError && q}
      <p class="text-sm text-text-secondary">{total} {total === 1 ? 'album' : 'albums'}</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 && albums.length === 0}
    <LibrarySkeleton variant="grid" count={12} />
  {:else if total === 0}
    <p class="text-text-secondary">No album matches.</p>
  {:else}
    <div class="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
      {#each albums as a (a.id)}
        <AlbumCard album={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>
