<script setup lang="ts">
interface ProjectData {
  id: number;
  title: string;
  short_description: string;
  website_image: string;
  application_image: string;
  is_scroll: boolean;
  video: string | null;
  slug: string;
  logo: string;
  card_display_type: "video" | "image" | string;
}

interface Props {
  projectInfo: ProjectData;
  sectionBg: string;
}

const { projectInfo, sectionBg } = defineProps<Props>();

const videoRef = ref<HTMLVideoElement | null>(null);

// Whether overlay (play button) is showing
const showOverlay = ref(true);

// For YouTube: store src only after clicking play
const youtubeIframeUrl = ref("");

// Computed properties for better template readability
const isVideoType = computed(() => projectInfo.card_display_type === "video");
const isImageType = computed(() => projectInfo.card_display_type === "image");

const hasVideo = computed(() => !!projectInfo.video);
const isYoutubeVideo = computed(() => isYoutube(projectInfo.video));

// Normalize description newlines to avoid SSR/CSR text mismatch
const normalizedShortDescription = computed(() => {
  const s = projectInfo.short_description ?? "";
  // Normalize Windows CRLF/CR to LF consistently for SSR and client
  return s.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
});

// -----------------------------------------------------------------------

// Play logic
const playVideo = () => {
  showOverlay.value = false;

  if (isYoutubeVideo.value) {
    youtubeIframeUrl.value = getYoutubeEmbedUrl(projectInfo.video, true);
  } else if (hasVideo.value && videoRef.value) {
    videoRef.value.play().catch(console.error);
  }
};

// YouTube Utilities
const youtubeUtils = {
  // Extract YouTube video ID from URL
  getId: (url: string | null | undefined): string | null => {
    if (!url || typeof url !== "string") return null;

    const regex =
      /(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/;
    const match = url.match(regex);
    return match?.[1] ?? null;
  },

  // Check if URL is a YouTube video
  isYoutubeUrl: (url: string | null | undefined): boolean => {
    return !!youtubeUtils.getId(url);
  },

  // Get YouTube thumbnail URL
  getThumbnail: (url: string | null | undefined): string => {
    const id = youtubeUtils.getId(url);
    return id
      ? `https://img.youtube.com/vi/${id}/maxresdefault.jpg`
      : "/default-thumb.jpg";
  },

  // Get YouTube embed URL with options
  getEmbedUrl: (url: string | null | undefined, autoplay = false): string => {
    const id = youtubeUtils.getId(url);
    if (!id) return "";

    const params = new URLSearchParams({
      mute: "1",
      rel: "0",
      modestbranding: "1",
      ...(autoplay && { autoplay: "1" }),
    });

    return `https://www.youtube.com/embed/${id}?${params.toString()}`;
  },
};

// Simplified helper functions for template
const isYoutube = (url: string | null | undefined): boolean =>
  youtubeUtils.isYoutubeUrl(url);
const getYoutubeThumbnail = (url: string | null | undefined): string =>
  youtubeUtils.getThumbnail(url);
const getYoutubeEmbedUrl = (
  url: string | null | undefined,
  autoplay = false,
): string => youtubeUtils.getEmbedUrl(url, autoplay);
</script>

<template>
  <section class="py-narrow-section" :class="sectionBg">
    <div class="container mx-auto px-4">
      <SectionHeadline :title="projectInfo.title" />

      <div class="flex flex-col items-center gap-[40px]">
        <!-- VIDEO DISPLAY -->
        <div
          v-if="isVideoType"
          class="mx-auto aspect-video w-full rounded-xl xl:w-[950px]"
        >
          <div class="relative h-full w-full">
            <!-- YOUTUBE VIDEO -->
            <template v-if="isYoutubeVideo">
              <div class="h-full w-full overflow-hidden rounded-2xl">
                <template v-if="showOverlay">
                  <ClientOnly>
                    <NuxtImg
                      :src="getYoutubeThumbnail(projectInfo.video)"
                      :alt="projectInfo.title"
                      class="h-full w-full rounded-2xl object-cover"
                      loading="lazy"
                      preset="default"
                    />
                  </ClientOnly>
                  <div
                    class="absolute inset-0 flex cursor-pointer items-center justify-center rounded-2xl bg-[rgba(0,0,0,0.5)]"
                    @click="playVideo"
                  >
                    <SvgVideoButton class="h-[40px] w-[40px]" />
                  </div>
                </template>

                <!-- Iframe replaces thumbnail on click -->
                <iframe
                  v-else-if="youtubeIframeUrl"
                  class="h-full w-full rounded-2xl object-contain"
                  :src="youtubeIframeUrl"
                  frameborder="0"
                  allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                  allowfullscreen
                />
              </div>
            </template>

            <!-- MP4 VIDEO -->
            <template v-else-if="hasVideo">
              <video
                ref="videoRef"
                :src="projectInfo.video || undefined"
                class="h-full w-full rounded-2xl object-cover"
                controls
                muted
                loop
              />
              <div
                v-if="showOverlay"
                class="absolute inset-0 flex items-center justify-center rounded-2xl bg-[rgba(0,0,0,0.5)]"
                @click="playVideo"
              >
                <SvgVideoButton class="h-[40px] w-[40px]" />
              </div>
            </template>

            <!-- NO VIDEO FALLBACK -->
            <template v-else>
              <div
                class="flex h-full w-full items-center justify-center rounded-2xl bg-gray-100"
              >
                <p class="text-gray-500">
                  {{ $t("errors.noVideoAvailable", "No video available") }}
                </p>
              </div>
            </template>
          </div>
        </div>

        <!-- RESPONSIVE PICTURE -->
        <div
          v-else-if="isImageType"
          class="mx-auto flex w-full items-center justify-center gap-12 xl:w-[865px]"
        >
          <NuxtPicture
            :src="projectInfo.website_image"
            :alt="projectInfo.title"
            :width="862"
            :height="572"
            preset="default"
          >
            <template #fallback>
              <NuxtImg
                :src="projectInfo.application_image"
                :alt="projectInfo.title"
                preset="default"
                class="mx-auto h-full w-full rounded-xl object-cover"
              />
            </template>
          </NuxtPicture>
        </div>

        <!-- DESCRIPTION -->
        <div
          class="description flex w-full flex-col gap-5 px-8 text-center xl:w-[950px]"
        >
          <p class="whitespace-pre-line">{{ normalizedShortDescription }}</p>
          <NuxtLinkLocale
            class="ws-gradient-border mx-auto w-fit px-4 py-2"
            :to="{
              name: 'our-projects-slug',
              params: {
                slug: projectInfo.slug,
              },
            }"
          >
            {{ $t("projectsButtons.learnMore") }}
          </NuxtLinkLocale>
        </div>
      </div>
    </div>
  </section>
</template>
