<template>
  <PrimeScrollPanel class="grid grid-cols-[1fr_1fr] gap-2 min-h-0">
    <GalleryCard
      v-for="producer in producers"
      :key="`producer-${producer.id}`"
      :client="me!"
      :producer="producer"
    />

    <GalleryCard
      v-for="consumer in consumers"
      :key="`consumer-${consumer.consumer.id}`"
      :client="consumer.client"
      :consumer="consumer.consumer"
    />
  </PrimeScrollPanel>
</template>

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

definePageMeta({
  name: 'Gallery',
})

const { videoProducer, shareProducer } = useMediasoup()
const { clients, me } = useClients()

const producers = computed(() => {
  return [videoProducer.value, shareProducer.value].filter(p => !!p && !!p.raw.track) as Producer[]
})

const consumers = computed(() => {
  return clients.value.reduce<{ client: ChadClient, consumer: Consumer }[]>((acc, client) => {
    const { streaming, videoConsumers: clientVideoConsumers, shareConsumers: clientShareConsumers } = useClient(client.socketId)

    if (!streaming.value)
      return acc

    for (const consumer of [...clientVideoConsumers.value, ...clientShareConsumers.value]) {
      acc.push({ client, consumer })
    }

    return acc
  }, [])
})

const hasItems = computed(() => producers.value.length > 0 || consumers.value.length > 0)

watch(hasItems, (hasItems) => {
  if (hasItems)
    return

  navigateTo({ name: 'Index' })
})
</script>
