<script setup lang="ts">
import { joinURL } from 'ufo';

const runtimeConfig = useRuntimeConfig();
const cdnUrl = runtimeConfig.public.cdn_url;

const emit = defineEmits(['mediaload']);

const props = defineProps<{
  mediaPath: string | null | undefined;
  phase: string;
}>();

const media = computed(() => {
  const dotSplit = props.mediaPath?.split('.');
  const extension = dotSplit?.pop()?.toLowerCase();
  let type = null;
  if (extension === 'jpg' || extension === 'jpeg') {
    type = 'image';
  } else if (extension === 'wmv') {
    type = 'video';
  }
  return { name: dotSplit?.join('.'), type };
});

const video = useTemplateRef('video');

function onVideoLoad() {
  if (props.phase != 'result') {
    const videoPlayInterval = setInterval(() => {
      if (video.value) {
        video.value.play();
        let duration = video.value.duration;
        if (isNaN(duration) || duration == Infinity) {
          duration = 0;
        }
        setTimeout(
          () => {
            emit('mediaload');
          },
          duration * 1000 + 1500,
        );
        clearInterval(videoPlayInterval);
      }
    }, 1000);
  }
}
</script>

<template>
  <div
    class="select-none flex-auto w-full *:object-contain *:w-full *:h-full *:max-h-full relative *:absolute"
  >
    <div
      class="w-full h-full opacity-0"
      :class="phase != 'result' ? 'z-10' : 'z-[-10]'"
    ></div>
    <img v-if="phase == 'set-basic'" src="/placeholder.svg" alt="placeholder" />
    <NuxtImg
      v-else-if="media.type === 'image'"
      :key="`${mediaPath}-image`"
      provider="selfhost"
      :src="'/' + mediaPath"
      :alt="mediaPath ?? ''"
      @load="emit('mediaload')"
    />
    <video
      v-else-if="media.type === 'video'"
      :key="`${mediaPath}-video`"
      ref="video"
      :controls="phase == 'result'"
      @canplaythrough="onVideoLoad()"
    >
      <source :src="joinURL(cdnUrl, media.name + '.mp4')" type="video/mp4" />
    </video>
    <span v-else class="text-5xl font-bold flex items-center justify-center">{{
      $t('questionWithoutVisual')
    }}</span>
  </div>
</template>
