<script lang="ts">
  import { pageTitle } from '$lib/branding';
  import {
    createLikedTracksInfiniteQuery,
    createLikedAlbumsInfiniteQuery,
    createLikedArtistsInfiniteQuery
  } from '$lib/api/likes';
  import ArtistCard from '$lib/components/ArtistCard.svelte';
  import AlbumCard from '$lib/components/AlbumCard.svelte';
  import TrackRow from '$lib/components/TrackRow.svelte';
  import QuickFilter from '$lib/components/QuickFilter.svelte';
  import EmptyState from '$lib/components/EmptyState.svelte';

  const artistsStore = $derived(createLikedArtistsInfiniteQuery());
  const albumsStore  = $derived(createLikedAlbumsInfiniteQuery());
  const tracksStore  = $derived(createLikedTracksInfiniteQuery());

  const artistsQuery = $derived($artistsStore);
  const albumsQuery  = $derived($albumsStore);
  const tracksQuery  = $derived($tracksStore);

  const artists = $derived(artistsQuery?.data?.pages?.flatMap((p) => p.items) ?? []);
  const albums  = $derived(albumsQuery?.data?.pages?.flatMap((p) => p.items) ?? []);
  const tracks  = $derived(tracksQuery?.data?.pages?.flatMap((p) => p.items) ?? []);

  const artistsTotal = $derived(artistsQuery?.data?.pages?.[0]?.total ?? 0);
  const albumsTotal  = $derived(albumsQuery?.data?.pages?.[0]?.total ?? 0);
  const tracksTotal  = $derived(tracksQuery?.data?.pages?.[0]?.total ?? 0);

  let filter = $state('');
  const q = $derived(filter.trim().toLowerCase());
  const fArtists = $derived(q ? artists.filter((a) => a.name.toLowerCase().includes(q)) : artists);
  const fAlbums  = $derived(q
    ? albums.filter((a) => a.title.toLowerCase().includes(q) || a.artist_name.toLowerCase().includes(q))
    : albums);
  const fTracks  = $derived(q
    ? tracks.filter((t) =>
        t.title.toLowerCase().includes(q) ||
        t.artist_name.toLowerCase().includes(q) ||
        (t.album_title ?? '').toLowerCase().includes(q))
    : tracks);
  const filterMatchesNothing = $derived(
    !!q && fArtists.length === 0 && fAlbums.length === 0 && fTracks.length === 0
  );
  const allEmpty = $derived(
    !q && artistsTotal === 0 && albumsTotal === 0 && tracksTotal === 0
  );
</script>

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

<div class="space-y-6">
  <header class="flex flex-wrap items-end justify-between gap-3">
    <h1 class="text-2xl font-semibold">Liked</h1>
    {#if artists.length + albums.length + tracks.length > 0}
      <QuickFilter bind:value={filter} placeholder="Filter liked" />
    {/if}
  </header>

  {#if filterMatchesNothing}
    <p class="text-text-secondary">
      Nothing in your loaded likes matches
      <span class="font-medium">'{filter.trim()}'</span>.
    </p>
  {/if}

  {#if allEmpty}
    <EmptyState
      title="No likes yet"
      hint="Tap the heart on a track, album, or artist to start your collection."
    >
      {#snippet actions()}
        <a href="/" class="inline-flex items-center rounded-md bg-action-secondary px-4 py-2 text-sm text-action-fg hover:opacity-90">
          Explore Home
        </a>
        <a href="/library/albums" class="inline-flex items-center rounded-md border border-border px-4 py-2 text-sm text-text-secondary hover:text-text-primary">
          Browse albums
        </a>
      {/snippet}
    </EmptyState>
  {/if}

  {#if !allEmpty && (!q || fArtists.length > 0)}
  <section>
    <h2 class="mb-2 text-lg font-semibold">Artists</h2>
    {#if artistsTotal === 0}
      <EmptyState
        variant="inline"
        title="No liked artists yet."
      >
        {#snippet actions()}
          <a href="/library/artists" class="text-accent hover:underline">Browse artists →</a>
        {/snippet}
      </EmptyState>
    {:else}
      <div class="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
        {#each fArtists as a (a.id)}
          <ArtistCard artist={a} />
        {/each}
      </div>
      {#if artistsQuery?.hasNextPage}
        <button
          type="button"
          class="mt-2 w-full rounded bg-surface py-2 text-sm hover:bg-surface-hover disabled:opacity-60"
          disabled={artistsQuery.isFetchingNextPage}
          onclick={() => artistsQuery.fetchNextPage()}
        >
          {artistsQuery.isFetchingNextPage ? 'Loading…' : 'Load more'}
        </button>
      {/if}
    {/if}
  </section>
  {/if}

  {#if !allEmpty && (!q || fAlbums.length > 0)}
  <section>
    <h2 class="mb-2 text-lg font-semibold">Albums</h2>
    {#if albumsTotal === 0}
      <EmptyState
        variant="inline"
        title="No liked albums yet."
      >
        {#snippet actions()}
          <a href="/library/albums" class="text-accent hover:underline">Browse albums →</a>
        {/snippet}
      </EmptyState>
    {:else}
      <div class="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
        {#each fAlbums as al (al.id)}
          <AlbumCard album={al} />
        {/each}
      </div>
      {#if albumsQuery?.hasNextPage}
        <button
          type="button"
          class="mt-2 w-full rounded bg-surface py-2 text-sm hover:bg-surface-hover disabled:opacity-60"
          disabled={albumsQuery.isFetchingNextPage}
          onclick={() => albumsQuery.fetchNextPage()}
        >
          {albumsQuery.isFetchingNextPage ? 'Loading…' : 'Load more'}
        </button>
      {/if}
    {/if}
  </section>
  {/if}

  {#if !allEmpty && (!q || fTracks.length > 0)}
  <section>
    <h2 class="mb-2 text-lg font-semibold">Tracks</h2>
    {#if tracksTotal === 0}
      <EmptyState
        variant="inline"
        title="No liked tracks yet."
      >
        {#snippet actions()}
          <a href="/" class="text-accent hover:underline">Find something new →</a>
        {/snippet}
      </EmptyState>
    {:else}
      <div class="overflow-hidden rounded border border-border">
        {#each fTracks as t, i (t.id)}
          <TrackRow tracks={fTracks} index={i} />
        {/each}
      </div>
      {#if tracksQuery?.hasNextPage}
        <button
          type="button"
          class="mt-2 w-full rounded bg-surface py-2 text-sm hover:bg-surface-hover disabled:opacity-60"
          disabled={tracksQuery.isFetchingNextPage}
          onclick={() => tracksQuery.fetchNextPage()}
        >
          {tracksQuery.isFetchingNextPage ? 'Loading…' : 'Load more'}
        </button>
      {/if}
    {/if}
  </section>
  {/if}
</div>
