<template>
  <div class="grid grid-cols-2 h-screen">
    <div class="flex flex-col shadow-xl overflow-y-hidden">
      <div class="flex items-center bg-surface-950 border-b-2 border-surface-800 px-3 py-3">
        <h1>
          Шальные сиськи 18+
        </h1>

        <div class="inline-flex gap-2 ml-auto">
          <PrimeButton icon="pi pi-headphones" text size="large" />
          <PrimeButton icon="pi pi-microphone" text size="large" />
        </div>
      </div>

      <div v-auto-animate class="p-3 overflow-y-auto flex-1 bg-surface-900 overflow-hidden divide-y divide-surface-800">
        <ClientRow v-for="client of clients" :key="client.id" :client="client" />
      </div>
    </div>
  </div>

  <audio v-for="client in clients" :key="client.id" :ref="(el) => onAudioRef(el, client)" autoplay controls />

  <PrimeBadge class="fixed top-3 right-3" severity="success" />
</template>

<script setup lang="ts">
import type { ChadClient } from '#shared/types'
import { vAutoAnimate } from '@formkit/auto-animate'

const { clients } = useGlobalState()
const { consumers } = useMediasoup()

function onAudioRef(ref: HTMLAudioElement, client: ChadClient) {
  if (!ref || !client)
    return

  if (client.isMe)
    return

  const consumersArray = client.consumerIds.map(id => consumers.value.get(id)!)

  const audioConsumer = consumersArray.find(
    consumer => consumer.track.kind === 'audio',
  )

  if (!audioConsumer)
    return

  const stream = new MediaStream()

  stream.addTrack(audioConsumer!.track)

  ref.srcObject = stream
  ref.setAttribute('data-consumer-id', audioConsumer.id)
}
</script>
