<script lang="ts">
  import { pageTitle } from '$lib/branding';
  import { createAlbumsAlphaInfiniteQuery } from '$lib/api/albums';
  import AlbumCard from '$lib/components/AlbumCard.svelte';
  import AlphabeticalGrid from '$lib/components/AlphabeticalGrid.svelte';
  import ApiErrorBanner from '$lib/components/ApiErrorBanner.svelte';
  import InfiniteScrollSentinel from '$lib/components/InfiniteScrollSentinel.svelte';
  import QuickFilter from '$lib/components/QuickFilter.svelte';
  import { useDelayed } from '$lib/utils/useDelayed.svelte';
  import type { AlbumRef } from '$lib/api/types';

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

  let filter = $state('');
  const filtered = $derived.by(() => {
    const q = filter.trim().toLowerCase();
    if (!q) return albums;
    return albums.filter(
      (a) => a.title.toLowerCase().includes(q) || a.artist_name.toLowerCase().includes(q)
    );
  });
</script>

<svelte:head><title>{pageTitle('Library · Albums')}</title></svelte:head>

<div class="space-y-4">
  <header class="flex flex-wrap items-end justify-between gap-3">
    <div>
      <h1 class="font-display text-2xl font-medium text-text-primary">Albums</h1>
      {#if !query.isPending && !query.isError}
        <p class="text-sm text-text-secondary">
          {total} {total === 1 ? 'album' : 'albums'}
        </p>
      {/if}
    </div>
    {#if albums.length > 0}
      <QuickFilter bind:value={filter} placeholder="Filter albums" />
    {/if}
  </header>

  {#if query.isError}
    <ApiErrorBanner error={query.error} onRetry={query.refetch} />
  {:else if showSkeleton.value && albums.length === 0}
    <p class="text-text-secondary">Loading…</p>
  {:else if !query.isPending && total === 0}
    <p class="text-text-secondary">No albums yet — scan a library folder via the server's config.</p>
  {:else if filter.trim() && filtered.length === 0}
    <p class="text-text-secondary">
      No albums in your loaded library match
      <span class="font-medium">'{filter.trim()}'</span>.
      <a href={`/search/albums?q=${encodeURIComponent(filter.trim())}`} class="text-accent hover:underline">
        Search the full library →
      </a>
    </p>
  {:else}
    <AlphabeticalGrid
      items={filtered}
      getKey={(a: AlbumRef) => a.sort_title || a.title}
    >
      {#snippet item(album: AlbumRef)}
        <AlbumCard {album} />
      {/snippet}
    </AlphabeticalGrid>

    {#if query.hasNextPage}
      <InfiniteScrollSentinel
        enabled={!query.isFetchingNextPage}
        onIntersect={() => query.fetchNextPage()}
      />
      {#if query.isFetchingNextPage}
        <p class="py-2 text-center text-sm text-text-secondary">Loading more…</p>
      {/if}
    {:else if albums.length > 0}
      <p class="py-2 text-center text-sm text-text-secondary">End of library</p>
    {/if}
  {/if}
</div>
