<template>
  <Modal v-for="notification in notifications.getNotifications" :key="notification.id" :isModalOpen="true" @modal:close="closeNotification(notification.id)">
    <template #modalHeader v-if="notification.title">
      <h3 class="m-0 font-medium shrink-0">{{ 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 { useNotificationStore } from '@/stores/notifications'
import { useGameStore } from '@/stores/game'
import Modal from '@/components/utilities/Modal.vue'
import { onBeforeMount, onBeforeUnmount, watch } from 'vue'

const notifications = useNotificationStore()
const gameStore = useGameStore()

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

function setupNotificationListener(connection: any) {
  connection.on('notification', (data: { message: string }) => {
    notifications.addNotification({
      message: data.message
    })
  })
}

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

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