<script setup>
const profileStore = useProfileStore()

const globalMessages = ref([])

const setup = async () => {
  let data = []
  try {
    data = await useNuxtApp().$api("/api/resource/globalmessages")
  } catch (e) {
    data = []
  }

  data = (data || []).filter((message) => !message.profiles || message.profiles.length === 0)

  globalMessages.value = data

  if(data.length > 0) {
    messageToShow.value = data[0]
    showMessageModal.value = true
  }


}


const showMessageModal = ref(false)
const messageToShow = ref(null)

const showMessage = (message) => {
  messageToShow.value = message
  showMessageModal.value = true
}
const markMessageAsRead = async () => {
  try {
    await useNuxtApp().$api("/api/resource/globalmessagesseen", {
      method: "POST",
      body: {
        profile: profileStore.activeProfile.id,
        message: messageToShow.value.id,
      }
    })
  } catch (e) {
    // noop: endpoint optional in newer backend versions
  }
  showMessageModal.value = false
  setup()

}




setup()
</script>

<template>
  <UModal v-model:open="showMessageModal" prevent-close>
    <template #content>
      <UCard>
        <template #header>
          <span class="font-bold">{{messageToShow.title}}</span>
        </template>
        <p class=" my-2" v-html="messageToShow.description"></p>
        <UButton
            variant="outline"
            @click="markMessageAsRead"
        >Gelesen</UButton>
      </UCard>
    </template>
  </UModal>

<!--  <UCard
      v-if="globalMessages.length >0"
      class="mt-3"
      style="border: .75px solid #69c350"
  >
    <p class="font-bold">{{globalMessages[0].title}}</p>
    <UButton
        icon="i-heroicons-chevron-right"
        variant="ghost"
        @click="showMessage(globalMessages[0])"
    />
    <UModal v-model:open="showMessageModal">
      <UCard>
        <template #header>
          <span class="font-bold">{{messageToShow.title}}</span>
        </template>
        <p class=" my-2" v-html="messageToShow.description"></p>
        <UButton
            variant="outline"
            @click="markMessageAsRead"
        >Gelesen</UButton>
      </UCard>
    </UModal>
  </UCard>-->
</template>

<style scoped>

</style>
