<script lang="ts">
  import { marked } from "$lib/markdown-safe";
  import { fade } from "svelte/transition";
  import { getBlockLayoutClasses } from "$lib/block-layout";
  import SectionHeader from "$lib/components/SectionHeader.svelte";
  import type {
    YoutubeVideoGalleryBlockData,
    YoutubeVideoBlockData,
  } from "$lib/block-types";
  import "$lib/iconify-offline";
  import Icon from "@iconify/svelte";
  import { useTranslate } from "$lib/translations";
  import { T } from "$lib/translations";
  import IconButton from "$lib/components/IconButton.svelte";

  const t = useTranslate();
  let { block }: { block: YoutubeVideoGalleryBlockData } = $props();

  function parseYouTube(input: string | undefined): {
    videoId: string | null;
    playlistId: string | null;
  } {
    if (!input) return { videoId: null, playlistId: null };
    const raw = input.trim();
    if (!raw) return { videoId: null, playlistId: null };
    if (raw.startsWith("http")) {
      try {
        const u = new URL(raw);
        const v = u.searchParams.get("v");
        const list = u.searchParams.get("list");
        let pathVid: string | null = null;
        if (u.hostname.includes("youtu.be")) {
          pathVid = u.pathname.replace(/^\/+/, "").split("/")[0] || null;
        }
        const embedMatch = u.pathname.match(/\/embed\/([^/?]+)/);
        const embedVid = embedMatch?.[1] ?? null;
        return { videoId: v ?? pathVid ?? embedVid, playlistId: list };
      } catch {
        return { videoId: null, playlistId: null };
      }
    }
    if (/^PL[A-Za-z0-9_-]+$/.test(raw)) {
      return { videoId: null, playlistId: raw };
    }
    return { videoId: raw, playlistId: null };
  }

  function buildEmbedUrl(v: YoutubeVideoBlockData): string | null {
    const fromVid = parseYouTube(v.youtubeId);
    const fromList = parseYouTube(v.playlistId);
    const videoId = fromVid.videoId ?? fromList.videoId;
    const playlistId = fromList.playlistId ?? fromVid.playlistId;
    if (!videoId && !playlistId) return null;
    const base = "https://www.youtube-nocookie.com/embed";
    const path = videoId ? `/${encodeURIComponent(videoId)}` : "/videoseries";
    const params = new URLSearchParams();
    params.set("rel", "0");
    if (playlistId) params.set("list", playlistId);
    if (v.params) {
      try {
        const extra = new URLSearchParams(String(v.params).replace(/^&/, ""));
        for (const [k, val] of extra.entries()) params.set(k, val);
      } catch {
        /* ignore */
      }
    }
    return `${base}${path}?${params.toString()}`;
  }

  function thumbnailUrl(v: YoutubeVideoBlockData): string | null {
    const fromVid = parseYouTube(v.youtubeId);
    const id = fromVid.videoId;
    return id ? `https://i.ytimg.com/vi/${encodeURIComponent(id)}/hqdefault.jpg` : null;
  }

  const layoutClasses = $derived(getBlockLayoutClasses(block.layout));
  const actionRef = $derived(
    block.action && typeof block.action === "object" ? block.action : null,
  );
  const descriptionHtml = $derived(
    block.description && typeof block.description === "string"
      ? (marked.parse(block.description) as string)
      : "",
  );

  function renderMd(text: string | undefined): string {
    if (!text || typeof text !== "string") return "";
    return marked.parse(text) as string;
  }

  type Item = {
    video: YoutubeVideoBlockData;
    embedUrl: string;
    thumb: string | null;
  };

  const items = $derived<Item[]>(
    (block.videos ?? [])
      .filter(
        (v): v is YoutubeVideoBlockData =>
          v != null && typeof v === "object",
      )
      .map((video) => {
        const embedUrl = buildEmbedUrl(video);
        if (!embedUrl) return null;
        return { video, embedUrl, thumb: thumbnailUrl(video) };
      })
      .filter((x): x is Item => x != null),
  );

  let currentIndex = $state(0);
  let modalIndex = $state<number>(-1);
  const modalOpen = $derived(modalIndex >= 0);

  function openModal(i: number) {
    modalIndex = i;
  }
  function closeModal() {
    modalIndex = -1;
  }
  function modalPrev() {
    if (modalIndex < 0) return;
    modalIndex = (modalIndex - 1 + items.length) % items.length;
  }
  function modalNext() {
    if (modalIndex < 0) return;
    modalIndex = (modalIndex + 1) % items.length;
  }
  function onModalKey(e: KeyboardEvent) {
    if (!modalOpen) return;
    if (e.key === "Escape") {
      e.preventDefault();
      closeModal();
    } else if (e.key === "ArrowLeft") {
      modalPrev();
    } else if (e.key === "ArrowRight") {
      modalNext();
    }
  }

  function prev() {
    currentIndex = (currentIndex - 1 + items.length) % items.length;
  }
  function next() {
    currentIndex = (currentIndex + 1) % items.length;
  }
</script>

<svelte:window onkeydown={onModalKey} />

<div
  class={layoutClasses}
  data-block="YoutubeVideoGallery" data-block-type="youtube_video_gallery"
  data-block-slug={block._slug}
>
  {#if block.title}
    <div class="mb-3">
      <SectionHeader
        number={block.number}
        kicker={block.kicker}
        title={block.title}
        subtitle={block.subtitle}
        tag="h3"
        actionLabel={actionRef?.linkName}
        actionHref={actionRef?.url}
      />
    </div>
  {/if}
  {#if descriptionHtml}
    <div class="markdown max-w-none prose prose-zinc mb-4">
      {@html descriptionHtml}
    </div>
  {/if}

  {#if items.length === 0}
    <p class="text-sm text-stein-500">{t(T.youtube_missing)}</p>
  {:else if block.variant === "grid"}
    <ul class="not-prose grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
      {#each items as item, i}
        {@const label = (item.video.title ?? "").trim()}
        <li class="m-0 p-0">
          <button
            type="button"
            class="group relative block w-full aspect-video overflow-hidden rounded-xs bg-stein-100 cursor-pointer focus:outline-none focus:ring-2 focus:ring-wald-500"
            onclick={() => openModal(i)}
            aria-label={label || t(T.youtube_title_fallback)}
          >
            {#if item.thumb}
              <img
                src={item.thumb}
                alt={label}
                class="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
                loading={i < 3 ? "eager" : "lazy"}
              />
            {:else}
              <div class="w-full h-full flex items-center justify-center bg-stein-200 text-stein-500 text-sm">
                {label}
              </div>
            {/if}
            <span
              class="absolute inset-0 flex items-center justify-center bg-black/20 group-hover:bg-black/30 transition-colors"
            >
              <span
                class="inline-flex h-12 w-12 items-center justify-center rounded-full bg-white/90 text-stein-900 shadow-md group-hover:bg-white"
              >
                <Icon icon="lucide:play" class="text-2xl" aria-hidden="true" />
              </span>
            </span>
            {#if label}
              <span
                class="absolute inset-x-0 bottom-0 px-2 py-1.5 text-left text-xs leading-tight text-white bg-gradient-to-t from-black/95 via-black/70 to-transparent line-clamp-2"
              >
                {label}
              </span>
            {/if}
          </button>
        </li>
      {/each}
    </ul>

    {#if modalOpen}
      {@const cur = items[modalIndex]}
      {@const curLabel = (cur.video.title ?? "").trim()}
      <div
        class="fixed inset-0 z-[100] flex items-center justify-center bg-black/85 p-4"
        role="dialog"
        aria-modal="true"
        aria-label={curLabel || t(T.youtube_title_fallback)}
        onclick={closeModal}
        transition:fade={{ duration: 150 }}
      >
        <div
          class="relative max-h-[90vh] w-full max-w-5xl flex flex-col gap-3"
          onclick={(e) => e.stopPropagation()}
          role="presentation"
        >
          <div class="aspect-video w-full overflow-hidden rounded-xs bg-black">
            {#key modalIndex}
              <iframe
                title={curLabel || t(T.youtube_title_fallback)}
                src={cur.embedUrl + (cur.embedUrl.includes("?") ? "&" : "?") + "autoplay=1"}
                class="h-full w-full border-0"
                loading="lazy"
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                allowfullscreen
              ></iframe>
            {/key}
          </div>
          <div class="flex items-center justify-between gap-3 text-white">
            <div class="min-w-0 flex-1">
              {#if curLabel}
                <p class="truncate text-sm font-medium">{curLabel}</p>
              {/if}
              {#if items.length > 1}
                <p class="text-xs text-white/60">{modalIndex + 1} / {items.length}</p>
              {/if}
            </div>
          </div>
          {#if items.length > 1}
            <IconButton icon="lucide:chevron-left" label={t(T.image_gallery_prev_aria)} variant="surface" size="md" onclick={modalPrev} class="absolute left-2 top-1/2 -translate-y-1/2" />
            <IconButton icon="lucide:chevron-right" label={t(T.image_gallery_next_aria)} variant="surface" size="md" onclick={modalNext} class="absolute right-2 top-1/2 -translate-y-1/2" />
          {/if}
          <IconButton icon="lucide:x" label={t(T.image_gallery_close)} variant="ghost" size="md" onclick={closeModal} class="absolute -top-2 -right-2" />
        </div>
      </div>
    {/if}
  {:else}
    {@const second = items.length > 1 ? items[(currentIndex + 1) % items.length] : null}
    <div class="group">
      <div class="relative">
        <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
          {#key currentIndex}
            {@const current = items[currentIndex]}
            <div class="aspect-video w-full overflow-hidden rounded-xs bg-stein-100">
              <iframe
                title={current.video.title ?? t(T.youtube_title_fallback)}
                src={current.embedUrl}
                class="h-full w-full border-0"
                loading="lazy"
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                allowfullscreen
              ></iframe>
            </div>
            {#if second}
              <div class="hidden md:block aspect-video w-full overflow-hidden rounded-xs bg-stein-100">
                <iframe
                  title={second.video.title ?? t(T.youtube_title_fallback)}
                  src={second.embedUrl}
                  class="h-full w-full border-0"
                  loading="lazy"
                  allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                  allowfullscreen
                ></iframe>
              </div>
            {/if}
          {/key}
        </div>

        {#if items.length > 1}
          <IconButton icon="lucide:chevron-left" label={t(T.image_gallery_prev_aria)} variant="surface" size="md" onclick={prev} class="absolute left-2 top-1/2 -translate-y-1/2 transition-opacity lg:opacity-0 lg:group-hover:opacity-100" />
          <IconButton icon="lucide:chevron-right" label={t(T.image_gallery_next_aria)} variant="surface" size="md" onclick={next} class="absolute right-2 top-1/2 -translate-y-1/2 transition-opacity lg:opacity-0 lg:group-hover:opacity-100" />
        {/if}
      </div>

      {#key currentIndex}
        {@const current = items[currentIndex]}
        <div class="grid grid-cols-1 gap-4 md:grid-cols-2 mt-2">
          <div class="min-w-0">
            {#if current.video.title}
              <p class="text-sm font-medium text-stein-900 break-words">{current.video.title}</p>
            {/if}
            {#if current.video.description}
              <div class="text-xs text-stein-600 break-words [overflow-wrap:anywhere] prose prose-sm max-w-none [&_p]:my-1 [&_a]:text-wald-700 [&_a]:break-all">{@html renderMd(current.video.description)}</div>
            {/if}
          </div>
          {#if second}
            <div class="hidden md:block min-w-0">
              {#if second.video.title}
                <p class="text-sm font-medium text-stein-900 break-words">{second.video.title}</p>
              {/if}
              {#if second.video.description}
                <div class="text-xs text-stein-600 break-words [overflow-wrap:anywhere] prose prose-sm max-w-none [&_p]:my-1 [&_a]:text-wald-700 [&_a]:break-all">{@html renderMd(second.video.description)}</div>
              {/if}
            </div>
          {/if}
        </div>
      {/key}

      {#if items.length > 1}

        <div
          class="flex justify-center gap-1.5 mt-2"
          role="tablist"
          aria-label={t(T.image_gallery_position_aria)}
        >
          {#each items as _, i}
            <button
              type="button"
              role="tab"
              aria-label={t(T.image_gallery_slide_aria, { index: i + 1 })}
              aria-selected={i === currentIndex}
              class="w-2 h-2 rounded-full transition-colors {i === currentIndex
                ? 'bg-wald-600'
                : 'bg-stein-300 hover:bg-stein-400'}"
              onclick={() => (currentIndex = i)}
            ></button>
          {/each}
        </div>
      {/if}
    </div>
  {/if}
</div>
