<template>
  <div
    class="group cursor-pointer hover:outline outline-primary relative rounded overflow-hidden flex items-center justify-center"
    @click="watch"
  >
    <video :srcObject="stream" muted autoplay />

    <PrimeTag
      severity="secondary"
      class="absolute bottom-2 text-sm opacity-70 group-hover:opacity-100"
      rounded
    >
      {{ isMe ? 'You' : client.displayName }}
    </PrimeTag>
  </div>
</template>

<script setup lang="ts">
import type { ChadClient, Consumer, Producer } from '#shared/types'

const props = defineProps<{
  client: ChadClient
  consumer?: Consumer
  producer?: Producer
}>()

const { me } = useClients()
const fullscreenVideo = useFullscreenVideo()

const isMe = computed(() => {
  return props.client.socketId === me.value?.socketId
})

const track = computed(() => {
  return props.consumer?.raw.track ?? props.producer?.raw.track
})

const stream = computed<MediaStream | undefined>((previousStream) => {
  if (previousStream?.getTracks()[0] === track.value) {
    return previousStream
  }

  return track.value ? new MediaStream([track.value]) : undefined
})

function watch() {
  if (stream.value)
    fullscreenVideo.show(stream.value)
}
</script>

<style>

</style>
