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

  const artists = $derived(query?.data?.artists);
  const albums  = $derived(query?.data?.albums);
  const tracks  = $derived(query?.data?.tracks);

  const allEmpty = $derived(
    !!query?.data &&
    artists?.items.length === 0 &&
    albums?.items.length === 0 &&
    tracks?.items.length === 0
  );

  const showSkeleton = useDelayed(() => !!query?.isPending);

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

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

<div class="space-y-6">
  {#if !q}
    <p class="text-text-secondary">
      Start typing to search artists, albums, and tracks.
    </p>
  {:else if query?.isError}
    <ApiErrorBanner error={query.error} onRetry={query.refetch} />
  {:else if showSkeleton.value && !query?.data}
    <SearchSkeleton />
  {:else if allEmpty}
    <p class="text-text-secondary">
      No matches for <span class="font-medium">'{q}'</span>.
    </p>
  {:else if query?.data}
    {#if artists && artists.items.length > 0}
      <section>
        <header class="mb-2 flex items-baseline justify-between">
          <h2 class="text-lg font-semibold">Artists</h2>
          {#if artists.total > artists.items.length}
            <a
              href={`/search/artists?q=${encodeURIComponent(q)}`}
              class="text-sm text-accent hover:underline"
            >
              See all {artists.total} →
            </a>
          {/if}
        </header>
        <div class="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
          {#each artists.items as a (a.id)}
            <ArtistCard artist={a} />
          {/each}
        </div>
      </section>
    {/if}

    {#if albums && albums.items.length > 0}
      <section>
        <header class="mb-2 flex items-baseline justify-between">
          <h2 class="text-lg font-semibold">Albums</h2>
          {#if albums.total > albums.items.length}
            <a
              href={`/search/albums?q=${encodeURIComponent(q)}`}
              class="text-sm text-accent hover:underline"
            >
              See all {albums.total} →
            </a>
          {/if}
        </header>
        <div class="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
          {#each albums.items as al (al.id)}
            <AlbumCard album={al} />
          {/each}
        </div>
      </section>
    {/if}

    {#if tracks && tracks.items.length > 0}
      <section>
        <header class="mb-2 flex items-baseline justify-between">
          <h2 class="text-lg font-semibold">Tracks</h2>
          {#if tracks.total > tracks.items.length}
            <a
              href={`/search/tracks?q=${encodeURIComponent(q)}`}
              class="text-sm text-accent hover:underline"
            >
              See all {tracks.total} →
            </a>
          {/if}
        </header>
        <div class="overflow-hidden rounded border border-border">
          {#each tracks.items as t, i (t.id)}
            <TrackRow tracks={tracks.items} index={i} onPlay={onTrackPlay} />
          {/each}
        </div>
      </section>
    {/if}
  {/if}
</div>
