<template>
  <Modal v-for="notification in gameStore.notifications" :key="notification.id" :isModalOpen="true" @modal:close="closeNotification(notification!.id as string)">
    <template #modalHeader v-if="notification.title">
      <h3 class="m-0 font-medium shrink-0 text-white">{{ notification.title }}</h3>
    </template>
    <template #modalBody v-if="notification.message">
      <p class="m-4">{{ notification.message }}</p>
    </template>
  </Modal>
</template>

<script setup lang="ts">
import Modal from '@/components/utilities/Modal.vue'
import { useGameStore } from '@/stores/gameStore'
import { onBeforeMount, onBeforeUnmount, onMounted, onUnmounted, watch } from 'vue'

const gameStore = useGameStore()

function closeNotification(id: string) {
  gameStore.removeNotification(id)
}

type Notification = {
  title?: string
  message?: string
}

function setupNotificationListener(connection: any) {
  connection.on('notification', (data: Notification) => {
    gameStore.addNotification({
      title: data.title,
      message: data.message
    })
  })
}

onMounted(() => {
  const connection = gameStore.connection
  if (connection) {
    setupNotificationListener(connection)
  } else {
    // Watch for changes in the socket connection
    watch(
      () => gameStore.connection,
      (newConnection) => {
        if (newConnection) setupNotificationListener(newConnection)
      }
    )
  }
})

onUnmounted(() => {
  const connection = gameStore.connection
  if (connection) {
    connection.off('notification')
  }
})
</script>
