<template>
  <div class="video-player">
    <video
      v-if="src"
      ref="player"
      :src="src"
      :poster="poster || ''"
      controls
      playsinline
      class="video-player__media"
      @timeupdate="onTimeUpdate"
    />
    <div v-else class="video-player__placeholder">
      <SvgIcon name="paper-plane-right" :size="48" color="rgba(0, 112, 116, 0.31)" />
      <p>ویدیویی برای نمایش وجود ندارد</p>
    </div>
  </div>
</template>

<script setup>
import SvgIcon from '@/components/icons/SvgIcon.vue'
import { onBeforeUnmount, onMounted, ref } from 'vue'

const props = defineProps({
  src: { type: String, default: '' },
  poster: { type: String, default: '' },
  videoId: { type: [String, Number], default: '' },
})

const player = ref(null)
const storageKey = () => (props.videoId ? `video_progress_${props.videoId}` : '')

onMounted(() => {
  if (!player.value || !props.videoId) return
  const saved = localStorage.getItem(storageKey())
  if (saved) {
    const t = Number.parseFloat(saved)
    if (Number.isFinite(t)) player.value.currentTime = t
  }
})

const onTimeUpdate = () => {
  if (!player.value || !props.videoId) return
  try {
    localStorage.setItem(storageKey(), String(player.value.currentTime))
  } catch {
    /* storage unavailable */
  }
}

onBeforeUnmount(() => {
  if (player.value) {
    player.value.pause()
    player.value.src = ''
  }
})
</script>

<style lang="scss" scoped>
.video-player {
  width: 100%;
  aspect-ratio: 16 / 9;
  border-radius: 1.5rem;
  overflow: hidden;
  background: #000;
  display: flex;
  align-items: center;
  justify-content: center;

  &__media {
    width: 100%;
    height: 100%;
    object-fit: contain;
    display: block;
  }

  &__placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 0.75rem;
    width: 100%;
    height: 100%;
    background: rgba(0, 112, 116, 4%);
    color: #007074;
    font-family: var(--font-family-fa);
    font-size: 0.875rem;
  }

  &__placeholder p {
    margin: 0;
  }
}
</style>
