<script lang="ts">
  import { goto } from "$app/navigation";

  interface Props {
    genres: string[];
    maxShow?: number;  // Default: unlimited
    clickable?: boolean;  // Default: true
    itemType?: string;  // Determines which genre browse page to open
  }

  let {
    genres,
    maxShow,
    clickable = true,
    itemType
  }: Props = $props();

  // Map the item type to its genre-browse route
  function genreBasePath(type: string | undefined): string {
    switch (type) {
      case "MusicAlbum":
      case "MusicArtist":
      case "Audio":
        return "/library/music/genres";
      case "Series":
      case "Season":
      case "Episode":
        return "/library/shows/genres";
      case "Movie":
        return "/library/movies/genres";
      default:
        return "/library/movies/genres";
    }
  }

  const displayGenres = $derived(
    maxShow ? genres.slice(0, maxShow) : genres
  );

  const hiddenCount = $derived(
    maxShow && genres.length > maxShow ? genres.length - maxShow : 0
  );

  function handleGenreClick(genre: string) {
    if (clickable) {
      goto(`${genreBasePath(itemType)}?genre=${encodeURIComponent(genre)}`);
    }
  }
</script>

{#if genres && genres.length > 0}
  <div class="flex flex-wrap gap-2 items-center">
    {#each displayGenres as genre (genre)}
      <button
        onclick={() => handleGenreClick(genre)}
        disabled={!clickable}
        class="px-3 py-1 bg-[var(--color-surface)] rounded-full text-sm transition-colors {clickable ? 'hover:bg-[var(--color-surface-hover)] cursor-pointer' : 'cursor-default'}"
      >
        {genre}
      </button>
    {/each}

    {#if hiddenCount > 0}
      <span class="text-sm text-gray-400 px-2">
        +{hiddenCount} more
      </span>
    {/if}
  </div>
{/if}

<style>
  button:disabled {
    opacity: 1;
  }
</style>
