<!--
A simple wrapper for embeded YouTube videos

Usage:

<Yt id="yxo-h0scF98" />
<Yt url="https://www.youtube.com/watch?v=yxo-h0scF98" />
<Yt url="https://www.youtube.com/embed/yxo-h0scF98" />
-->

<template>
  <iframe
    :width="width"
    :height="height"
    :src="`https://www.youtube.com/embed/${id}${params}`"
    title="YouTube"
    frameborder="0"
    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
    allowfullscreen
  ></iframe>
</template>

<script setup lang="ts">
import { computed } from 'vue'

const props = withDefaults(defineProps<{
  id?: string
  url?: string
  /**
   * Ref: https://developers.google.com/youtube/player_parameters
   */
  params?: Record<string, string>
  width?: number | string
  height?: number | string
}>(), {
  params: () => ({ rel: '0' }),
})

const paramsInUrl = computed(() => {
  if (props.url)
    return Object.fromEntries(new URL(props.url).searchParams)
})

const idInEmbedUrl = computed(() => {
  if (props.url) {
    const path = new URL(props.url).pathname
    if (path.startsWith('/embed/'))
      return path.replace('/embed/', '')
  }
})

const id = computed(() => {
  if (props.id)
    return props.id
  if (paramsInUrl.value?.v)
    return paramsInUrl.value?.v
  if (idInEmbedUrl.value)
    return idInEmbedUrl.value
  return ''
})

const params = computed(() => {
  if (typeof props.params === 'object' && Object.keys(props.params).length) {
    const params = {
      ...props.params,
      ...(paramsInUrl.value ?? {}),
    }
    delete params.v
    return `?${new URLSearchParams(params)}`
  }
  return ''
})
</script>
