<script lang="ts">
  import { page } from '$app/state';
  import { createAlbumQuery } from '$lib/api/queries';
  import TrackRow from '$lib/components/TrackRow.svelte';
  import LibrarySkeleton from '$lib/components/LibrarySkeleton.svelte';
  import ApiErrorBanner from '$lib/components/ApiErrorBanner.svelte';
  import { useDelayed } from '$lib/utils/useDelayed.svelte';
  import { formatDuration } from '$lib/media/duration';
  import { FALLBACK_COVER } from '$lib/media/covers';
  import type { ApiError } from '$lib/api/client';

  const id = $derived(page.params.id ?? '');
  const queryStore = $derived(createAlbumQuery(id));
  const query = $derived($queryStore);
  const showSkeleton = useDelayed(() => query.isPending);

  const notFound = $derived(
    query.isError && (query.error as unknown as ApiError | undefined)?.code === 'not_found'
  );

  function onCoverError(e: Event) {
    (e.currentTarget as HTMLImageElement).src = FALLBACK_COVER;
  }
</script>

<div class="space-y-6">
  {#if notFound}
    <div role="alert" class="rounded border border-border bg-surface p-4">
      <p>Album not found.</p>
      <a href="/" class="mt-2 inline-block text-sm text-accent">Back to Library</a>
    </div>
  {:else if query.isError}
    <ApiErrorBanner error={query.error} onRetry={query.refetch} />
  {:else if showSkeleton.value && !query.data}
    <LibrarySkeleton variant="album" />
  {:else if query.data}
    {@const album = query.data}
    <a
      href={`/artists/${album.artist_id}`}
      class="text-sm text-text-secondary hover:text-text-primary"
    >
      ← {album.artist_name}
    </a>

    <header class="flex flex-col gap-4 md:flex-row md:items-end">
      <img
        src={album.cover_url}
        alt={album.title}
        class="h-60 w-60 rounded object-cover"
        loading="lazy"
        onerror={onCoverError}
      />
      <div class="flex-1 space-y-1">
        <h1 class="text-3xl font-semibold">{album.title}</h1>
        <p>
          <a href={`/artists/${album.artist_id}`} class="hover:underline">{album.artist_name}</a>
        </p>
        {#if album.year}
          <p class="text-sm text-text-secondary">{album.year}</p>
        {/if}
        <p class="text-sm text-text-secondary">
          {album.track_count} {album.track_count === 1 ? 'track' : 'tracks'}
          · {formatDuration(album.duration_sec)}
        </p>
      </div>
    </header>

    {#if album.tracks.length === 0}
      <p class="text-text-secondary">This album has no tracks.</p>
    {:else}
      <div class="overflow-hidden rounded border border-border">
        {#each album.tracks as track, i (track.id)}
          <TrackRow tracks={album.tracks} index={i} />
        {/each}
      </div>
    {/if}
  {/if}
</div>
