<script setup lang="ts">
import type { PageDataResourceGroup } from '#layers/types/api/pageData'

interface Props {
  resourcesData: PageDataResourceGroup
  gradient?: string
  size?: 'contain' | 'cover'
}

const props = withDefaults(defineProps<Props>(), {
  gradient: '',
  size: 'cover',
})

const { getCurrentSrc } = useResponsiveSrc()

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

const resPath = computed(() => props.resourcesData?.res_path)
const imageSrc = computed(() => {
  return getCurrentSrc(resPath.value)
})
const videoSrc = computed(() => {
  return getCurrentSrc(resPath.value, { resourcesType: 'video' })
})
const posterSrc = computed(() => {
  return getCurrentSrc(resPath.value)
})
const imageClasses = computed(() => [
  `w-full h-full bg-center bg-no-repeat`,
  props.size === 'contain' ? 'bg-contain' : 'bg-cover',
])
const gradientClasses = computed(() => [
  'absolute bottom-0 left-0 right-0',
  props.gradient,
])

// src 변경 시 비디오 다시 로드
watch(videoSrc, () => {
  if (!videoRef.value) return

  videoRef.value.currentTime = 0
  videoRef.value.load()
})
</script>

<template>
  <div class="absolute inset-0 w-full h-full">
    <!-- 이미지 타입 -->
    <div
      v-if="isTypeImage(resourcesData?.resource_type) && imageSrc"
      :class="imageClasses"
      :style="{ backgroundImage: `url(${imageSrc})` }"
    />

    <!-- 비디오 타입 -->
    <video
      v-else-if="isTypeVideo(resourcesData?.resource_type) && videoSrc"
      ref="videoRef"
      class="w-full h-full object-cover"
      :poster="posterSrc"
      autoplay
      muted
      loop
      playsinline
    >
      <source :src="videoSrc" type="video/mp4" />
    </video>

    <!-- 그라디언트 오버레이 -->
    <div v-if="gradient" :class="gradientClasses" />
  </div>
</template>
