<script setup lang="ts">
const props = defineProps<{
  videoUrl: string;
  thumbnailClass?: string;
  videoClass?: string;
}>();

const emit = defineEmits<{
  (e: "play" | "pause"): void;
}>();

const YOUTUBE_REGEX =
  /(?:youtube\.com\/(?:watch\?v=|shorts\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/;

const isYouTubeVideo = (url: string): boolean => {
  return url.includes("youtube") || url.includes("youtu.be");
};

const getYouTubeVideoId = (url: string): string | null => {
  const match = url.match(YOUTUBE_REGEX);
  return match ? match[1] : null;
};

const getYouTubeThumbnail = (url: string): string => {
  const videoId = getYouTubeVideoId(url);
  return videoId
    ? `https://img.youtube.com/vi/${videoId}/maxresdefault.jpg`
    : "";
};

const getYouTubeEmbedUrl = (url: string, autoplay = false): string => {
  const videoId = getYouTubeVideoId(url);
  if (!videoId) return "";

  const params = new URLSearchParams({
    // Unmuted playback after user click
    mute: "0",
    rel: "0",
    ...(autoplay && { autoplay: "1" }),
  });

  return `https://www.youtube-nocookie.com/embed/${videoId}?${params.toString()}`;
};

const hasStarted = ref(false);
const embedUrl = ref("");

const startPlayback = () => {
  if (!props.videoUrl || !isYouTubeVideo(props.videoUrl)) return;
  hasStarted.value = true;
  embedUrl.value = getYouTubeEmbedUrl(props.videoUrl, true);
  emit("play");
};
</script>

<template>
  <div
    class="rounded-ws-rounded bg-surface-background relative flex w-full items-center justify-center overflow-hidden"
  >
    <!-- YouTube Thumbnail -->
    <div
      v-if="!hasStarted && isYouTubeVideo(props.videoUrl)"
      class="relative flex cursor-pointer"
      :class="['rounded-ws-rounded object-cover', props.videoClass]"
      @click="startPlayback"
    >
      <NuxtImg
        :src="getYouTubeThumbnail(props.videoUrl)"
        alt="YouTube thumbnail"
      />
      <div
        class="absolute inset-0 flex items-center justify-center bg-black/40"
      >
        <SvgPlayIcon class="size-14 text-white" />
      </div>
    </div>

    <!-- YouTube Video -->
    <iframe
      v-else
      :src="embedUrl"
      :class="['rounded-ws-rounded object-cover', props.videoClass]"
      frameborder="0"
      allow="autoplay; encrypted-media; fullscreen"
      allowfullscreen
    />
  </div>
</template>
