<!-- TRACES: UR-007, UR-023, UR-034 | DR-007, DR-038, DR-039 -->
<script lang="ts">
  import { onMount } from "svelte";
  import { goto } from "$app/navigation";
  import { currentLibrary } from "$lib/stores/library";
  import { tv } from "$lib/stores/tv";
  import { isServerReachable } from "$lib/stores/connectivity";
  import { useServerReachabilityReload } from "$lib/composables/useServerReachabilityReload";
  import HeroBanner from "$lib/components/home/HeroBanner.svelte";
  import Carousel from "$lib/components/home/Carousel.svelte";
  import type { MediaItem } from "$lib/api/types";

  interface Category {
    id: string;
    name: string;
    icon: string;
    description: string;
    route: string;
  }

  const categories: Category[] = [
    {
      id: "shows",
      name: "All Shows",
      icon: "M4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-8 12.5v-9l6 4.5-6 4.5z",
      description: "Browse all series",
      route: "/library/tv/shows",
    },
    {
      id: "genres",
      name: "Genres",
      icon: "M18 4l2 4h-3l-2-4h-2l2 4h-3l-2-4H8l2 4H7L5 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4h-4z",
      description: "Browse by genre",
      route: "/library/shows/genres",
    },
  ];

  async function load() {
    if (!$currentLibrary) {
      goto("/library");
      return;
    }
    await tv.loadSections($currentLibrary.id);
  }

  const { markLoaded, checkServerReachability } = useServerReachabilityReload(load);

  onMount(async () => {
    await load();
    markLoaded();
  });

  $effect(() => {
    checkServerReachability($isServerReachable);
  });

  function handleItemClick(item: MediaItem) {
    switch (item.type) {
      case "Series":
      case "Season":
      case "Folder":
        goto(`/library/${item.id}`);
        break;
      default:
        // Episodes and movies play directly.
        goto(`/player/${item.id}`);
        break;
    }
  }

  const heroItems = $derived($tv.heroItems);
  const continueWatching = $derived($tv.continueWatching);
  const nextUp = $derived($tv.nextUp);
  const recentlyAdded = $derived($tv.recentlyAdded);
  const genreRows = $derived($tv.genreRows);
  const isLoading = $derived($tv.isLoading);
  const hasContent = $derived(
    heroItems.length > 0 ||
      continueWatching.length > 0 ||
      nextUp.length > 0 ||
      recentlyAdded.length > 0
  );
</script>

{#if isLoading}
  <div class="flex justify-center items-center py-32">
    <div class="w-8 h-8 border-2 border-[var(--color-jellyfin)] border-t-transparent rounded-full animate-spin"></div>
  </div>
{:else}
  <div class="space-y-8 pb-8">
    <!-- Header -->
    <div class="flex items-center justify-between px-4">
      <h1 class="text-3xl font-bold text-white">{$currentLibrary?.name ?? "TV Shows"}</h1>
      <button
        onclick={() => goto("/library")}
        class="p-2 rounded-lg hover:bg-white/10 transition-colors text-gray-400 hover:text-white"
        title="Back to libraries"
        aria-label="Back to libraries"
      >
        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
        </svg>
      </button>
    </div>

    <!-- Hero Banner -->
    {#if heroItems.length > 0}
      <HeroBanner items={heroItems} />
    {/if}

    <!-- Continue Watching -->
    {#if continueWatching.length > 0}
      <Carousel
        title="Continue Watching"
        items={continueWatching}
        onItemClick={handleItemClick}
      />
    {/if}

    <!-- Next Up -->
    {#if nextUp.length > 0}
      <Carousel
        title="Next Up"
        items={nextUp}
        onItemClick={handleItemClick}
      />
    {/if}

    <!-- Recently Added -->
    {#if recentlyAdded.length > 0}
      <Carousel
        title="Recently Added"
        items={recentlyAdded}
        onItemClick={handleItemClick}
        showAll={() => goto("/library/tv/shows")}
      />
    {/if}

    <!-- One slider per genre -->
    {#each genreRows as row (row.id)}
      <Carousel
        title={row.name}
        items={row.items}
        onItemClick={handleItemClick}
        showAll={() => goto(`/library/shows/genres`)}
      />
    {/each}

    {#if !hasContent}
      <p class="px-4 text-gray-400">Nothing here yet. Start watching something to fill this page.</p>
    {/if}

    <!-- Browse by category -->
    <div class="space-y-3 px-4 pt-4">
      <h2 class="text-2xl font-semibold text-white">Browse</h2>
      <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
        {#each categories as category (category.id)}
          <button
            onclick={() => goto(category.route)}
            class="group relative flex items-center gap-3 bg-[var(--color-surface)] hover:bg-white/10 rounded-xl p-4 text-left transition-colors"
          >
            <div class="w-10 h-10 flex-shrink-0 rounded-full bg-[var(--color-jellyfin)]/20 flex items-center justify-center group-hover:scale-110 transition-transform">
              <svg class="w-5 h-5 text-[var(--color-jellyfin)]" fill="currentColor" viewBox="0 0 24 24">
                <path d={category.icon} />
              </svg>
            </div>
            <div class="min-w-0">
              <div class="text-white font-semibold truncate">{category.name}</div>
              <div class="text-gray-400 text-xs truncate">{category.description}</div>
            </div>
          </button>
        {/each}
      </div>
    </div>
  </div>
{/if}
