<script setup>

const supabase = useSupabaseClient()
const profileStore = useProfileStore()

const globalMessages = ref([])

const setup = async () => {
  let {data} = await supabase.from("globalmessages").select("*, profiles(id)")

  data = data.filter((message) => message.profiles.length === 0)

  globalMessages.value = data
}
const showMessageModal = ref(false)
const messageToShow = ref(null)

const showMessage = (message) => {
  messageToShow.value = message
  showMessageModal.value = true
}
const markMessageAsRead = async () => {
  await supabase.from("globalmessagesseen").insert({
    profile: profileStore.activeProfile.id,
    message: messageToShow.value.id,
  })
  setup()
  showMessageModal.value = false
}

setup()
</script>

<template>
  <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="showMessageModal">
      <UCard>
        <template #header>
          <span class="font-bold">{{messageToShow.title}}</span>
        </template>
        <p class="text-justify my-2" v-html="messageToShow.description"></p>
        <UButton
            variant="outline"
            @click="markMessageAsRead"
        >Gelesen</UButton>
      </UCard>
    </UModal>
  </UCard>
</template>

<style scoped>

</style>