<template>
  <div class="live-player">
    <video
      ref="videoRef"
      class="screen-media"
      muted
      autoplay
      playsinline
    />
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { createLivePlayer, destroyLivePlayer } from '../utils/liveStreamPlayer.js'

const props = defineProps({
  url: {
    type: String,
    default: ''
  },
  playerConfig: {
    type: Object,
    default: () => ({})
  },
  active: {
    type: Boolean,
    default: true
  }
})

const videoRef = ref(null)
let playerInstance = null

const teardown = () => {
  destroyLivePlayer(playerInstance)
  playerInstance = null
}

const setup = async () => {
  teardown()
  if (!props.active || !props.url) {
    return
  }
  await nextTick()
  if (!videoRef.value) {
    return
  }
  playerInstance = createLivePlayer(videoRef.value, props.url, props.playerConfig)
}

watch(
  () => [props.url, props.active, props.playerConfig],
  setup,
  { deep: true }
)

onMounted(setup)
onBeforeUnmount(teardown)
</script>

<style scoped>
.live-player {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.screen-media {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
  background: #0a1418;
}
</style>
