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

  import type { MediaKind } from "$lib/api/types";
  import { libraryViewUrl } from "$lib/utils/libraryView";

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

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

  // Map the item kind to its genre-browse surface. Video genres are a tab of
  // the library page now, not a route of their own (DR-105); linking straight
  // to the tab avoids a redirect hop through the legacy paths.
  function genreBasePath(kind: MediaKind | undefined): string {
    switch (kind) {
      case "album":
      case "artist":
      case "track":
      case "playlist":
        return "/library/music/genres";
      case "series":
      case "season":
      case "episode":
        return libraryViewUrl("/library/tv", "genres");
      case "movie":
        return libraryViewUrl("/library/movies", "genres");
      default:
        return libraryViewUrl("/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(itemKind)}?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>
