<script setup>
const route = useRoute()
const { $socket } = useNuxtApp()

let { cosetta, comments } = reactive(await $fetch(`/api/cosetta/${route.params.cosetta}`))

const comment = reactive({ cosetta_uuid: route.params.cosetta, message: '' })
const addComment = async () => {
  const ret = await $fetch(`/api/comment`, { method: 'POST', body: { ...comment } })
  comment.message = ''
  const db_comment = await $fetch(`/api/comment/${ret.comment.uuid}`)
  comments.unshift(db_comment)
  $socket.emit("newComment", db_comment, route.params.cosetta )
}

onMounted(() => {
  $socket.emit("joinRoom", route.params.cosetta)
  $socket.on("newComment", (newComment) => {
    comments.unshift(newComment.message)
  })
})

</script>
<template>
  <section class="bg-white py-8">

    <div class="container mx-auto pt-4 pb-12">
      <img v-if='cosetta.images' :src="`/${cosetta.images[0]}`" />
      <h2 class="text-pink-500 text-2xl card-title uppercase mb-2 divider" v-text='cosetta.name' />
      <div class="px-6 pt-4 pb-2">
        <span v-for='tag in cosetta.tags' :key='tag'
          class="inline-block bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700 mr-2 mb-2"
          v-text='tag' />
      </div>
      <p class='pt-1 text-gray-700 text-xl'>{{ cosetta.description }}</p>

    </div>

    <div class="container mx-auto">
      <p class="font-bold text-xl uppercase">chiacchiere</p>
      <div class='form-control'>
        <div class='input-group'>
          <input v-model='comment.message' class="input input-bordered w-full text-sm" @keypress:enter="addComment" />
          <button class="btn btn-success" @click='addComment'>Invia</button>
        </div>

        <div class='mt-2' v-for='comment in comments' :key='comment.uuid'>
          <span class="label-text-alt" v-text='comment.updatedAt' />
          <div class="alert" v-text='comment.message' />
        </div>
      </div>
    </div>
  </section>
</template>
