<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 { SocketEvent } from '@/application/enums'
import Modal from '@/components/utilities/Modal.vue'
import { socketManager } from '@/managers/SocketManager'
import { useGameStore } from '@/stores/gameStore'
import { 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(SocketEvent.NOTIFICATION, (data: Notification) => {
    gameStore.addNotification({
      title: data.title,
      message: data.message
    })
  })
}

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

onUnmounted(() => {
  const connection = socketManager.connection
  if (connection) {
    connection.off(SocketEvent.NOTIFICATION)
  }
})
</script>
