<template>
  <div class="grid grid-cols-[1fr_1fr] gap-2">
    <template v-for="(group, id) in groupedConsumers" :key="id">
      <GalleryCard
        v-for="consumer in group"
        :key="consumer.id"
        :consumer="consumer"
        @click="watch(consumer)"
      />
    </template>
  </div>
</template>

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

definePageMeta({
  name: 'Gallery',
})

const { videoConsumers, shareConsumers } = useMediasoup()
const fullscreenVideo = useFullscreenVideo()

const groupedConsumers = computed<Partial<Record<string, Consumer[]>>>(() => {
  if (fullscreenVideo.visible.value)
    return {}

  const consumers = [...videoConsumers.value, ...shareConsumers.value]

  return Object.groupBy(consumers, (consumer) => {
    return consumer.appData.socketId!
  })
})

function watch(consumer: Consumer) {
  fullscreenVideo.show(new MediaStream([consumer.raw.track]))
}
</script>
