<script lang="ts">
  import { library, genres, selectedGenres } from "$lib/stores/library";

  interface Props {
    onFilterChange?: () => void;
  }

  let { onFilterChange }: Props = $props();

  function handleToggleGenre(genreName: string) {
    library.toggleGenre(genreName);
    onFilterChange?.();
  }

  function handleClearAll() {
    library.clearGenres();
    onFilterChange?.();
  }
</script>

{#if $genres.length > 0}
  <div class="space-y-2">
    <div class="flex items-center justify-between">
      <span class="text-sm text-gray-400">Filter by genre</span>
      {#if $selectedGenres.length > 0}
        <button
          onclick={handleClearAll}
          class="text-xs text-[var(--color-jellyfin)] hover:underline"
        >
          Clear all
        </button>
      {/if}
    </div>
    <div class="flex flex-wrap gap-2">
      {#each $genres as genre (genre.id)}
        {@const isSelected = $selectedGenres.includes(genre.name)}
        <button
          onclick={() => handleToggleGenre(genre.name)}
          class="px-3 py-1 rounded-full text-sm transition-colors
            {isSelected
              ? 'bg-[var(--color-jellyfin)] text-white'
              : 'bg-[var(--color-surface)] text-gray-300 hover:bg-[var(--color-surface-hover)]'}"
        >
          {genre.name}
        </button>
      {/each}
    </div>
  </div>
{/if}
