<script lang="ts">
  import { useQueryClient } from '@tanstack/svelte-query';
  import { createSuggestionsQuery } from '$lib/api/suggestions';
  import { createRequest } from '$lib/api/requests';
  import { qk } from '$lib/api/queries';
  import DiscoverResultCard from './DiscoverResultCard.svelte';
  import type { ArtistSuggestion, SeedContribution } from '$lib/api/types';

  const client = useQueryClient();
  const queryStore = createSuggestionsQuery();
  const query = $derived($queryStore);
  const suggestions = $derived((query.data ?? []) as ArtistSuggestion[]);

  // Track MBIDs the user just requested so the card flips immediately.
  let optimisticRequested = $state(new Set<string>());

  function visible(s: ArtistSuggestion): boolean {
    return !optimisticRequested.has(s.mbid);
  }

  function attributionText(attribution: SeedContribution[]): string {
    if (attribution.length === 0) return '';
    const verb = (s: SeedContribution) => (s.is_liked ? 'liked' : 'played');
    const phrases = attribution.map((s) => `${verb(s)} ${s.name}`);
    if (phrases.length === 1) {
      return `Because you ${phrases[0]}.`;
    }
    if (phrases.length === 2) {
      return `Because you ${phrases[0]} and ${phrases[1]}.`;
    }
    // 3 with Oxford comma
    return `Because you ${phrases[0]}, ${phrases[1]}, and ${phrases[2]}.`;
  }

  async function onRequest(s: ArtistSuggestion) {
    try {
      await createRequest({
        kind: 'artist',
        lidarr_artist_mbid: s.mbid,
        artist_name: s.name
      });
      const next = new Set(optimisticRequested);
      next.add(s.mbid);
      optimisticRequested = next;
      // The server-side filter hides this candidate on next refetch.
      await client.invalidateQueries({ queryKey: qk.suggestions() });
    } catch {
      // Swallow for v1; the SPA will refetch on next mount and the card
      // stays requestable so the user can retry.
    }
  }
</script>

<div>
  <header class="mb-4 space-y-1">
    <h2 class="font-display text-2xl font-medium text-text-primary">Suggested for you</h2>
    <p class="text-text-secondary">Out-of-library artists drawn from what you've liked and played.</p>
  </header>

  {#if !query.isPending && suggestions.length === 0}
    <p class="text-text-secondary">Listen to something or like an artist to start getting suggestions.</p>
  {:else if suggestions.length > 0}
    <div class="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
      {#each suggestions.filter(visible) as s (s.mbid)}
        <DiscoverResultCard
          kind="artist"
          title={s.name}
          state="requestable"
          attribution={attributionText(s.attribution)}
          onRequest={() => onRequest(s)}
        />
      {/each}
    </div>
  {/if}
</div>
