<template>
  <div class="notifications">
    <Modal v-for="notification in notifications.getNotifications" :key="notification.id" :isModalOpen="true" @modal:close="closeNotification(notification.id)">
      <template #modal-body>
        <p>{{ notification.message }}</p>
      </template>
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { useNotificationStore } from '@/stores/notifications'
import { useSocketStore } from '@/stores/socket'
import Modal from '@/components/utilities/Modal.vue'
import { onMounted, onUnmounted, ref, watch } from 'vue'

const notifications = useNotificationStore()
const socket = useSocketStore()

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

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

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

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