<script lang="ts">
  import { pageTitle } from '$lib/branding';
  import { createHistoryQuery } from '$lib/api/history';
  import { groupByDay } from '$lib/utils/dayGroup';
  import HistoryRow from '$lib/components/HistoryRow.svelte';
  import InfiniteScrollSentinel from '$lib/components/InfiniteScrollSentinel.svelte';
  import LibrarySkeleton from '$lib/components/LibrarySkeleton.svelte';
  import ApiErrorBanner from '$lib/components/ApiErrorBanner.svelte';
  import QuickFilter from '$lib/components/QuickFilter.svelte';
  import EmptyState from '$lib/components/EmptyState.svelte';

  const queryStore = createHistoryQuery();
  const query = $derived($queryStore);
  const flatEvents = $derived(query.data?.pages?.flatMap((p) => p.events) ?? []);

  let filter = $state('');
  const filteredEvents = $derived.by(() => {
    const q = filter.trim().toLowerCase();
    if (!q) return flatEvents;
    return flatEvents.filter((e) =>
      e.track.title.toLowerCase().includes(q) ||
      e.track.artist_name.toLowerCase().includes(q) ||
      (e.track.album_title ?? '').toLowerCase().includes(q)
    );
  });
  const grouped = $derived(groupByDay(filteredEvents, new Date()));
</script>

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

<div class="space-y-4">
  <header class="flex flex-wrap items-end justify-between gap-3">
    <h1 class="font-display text-2xl font-medium text-text-primary">History</h1>
    {#if flatEvents.length > 0}
      <QuickFilter bind:value={filter} placeholder="Filter history" />
    {/if}
  </header>

  {#if query.isPending}
    <LibrarySkeleton variant="list" count={12} />
  {:else if query.isError}
    <ApiErrorBanner error={query.error} onRetry={query.refetch} />
  {:else if flatEvents.length === 0}
    <EmptyState
      title="No listening history yet"
      hint="Once you've played something, it'll show up here, grouped by day."
    >
      {#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">
          Listen to something
        </a>
      {/snippet}
    </EmptyState>
  {:else if filter.trim() && filteredEvents.length === 0}
    <p class="text-text-secondary">
      No history in your loaded events matches
      <span class="font-medium">'{filter.trim()}'</span>.
    </p>
  {:else}
    {#each grouped as group (group.label)}
      <section>
        <h2 class="sticky top-0 z-10 mb-2 bg-background py-1 text-lg font-medium text-text-secondary">
          {group.label}
        </h2>
        <div class="divide-y divide-border">
          {#each group.events as event (event.id)}
            <HistoryRow {event} />
          {/each}
        </div>
      </section>
    {/each}

    {#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 flatEvents.length > 0}
      <p class="py-2 text-center text-sm text-text-secondary">End of history</p>
    {/if}
  {/if}
</div>
