<script setup lang="ts">
import MessageToolbar from '@/components/MessageToolbar.vue'
import MessageForm from '@/components/MessageForm.vue'
import MessageData from '@/components/MessageData.vue'
import { useMessagesStore } from '@/stores/messages.ts'
import { useAuthStore } from '@/stores/auth.ts'
import { computed, nextTick, useTemplateRef, watch } from 'vue'
import { useScroll } from '@vueuse/core'
import { useChatsStore } from '@/stores/chats.ts'

const authStore = useAuthStore()
const messagesStore = useMessagesStore()
const chatsStore = useChatsStore()

const area = useTemplateRef('messageArea')
const { y, arrivedState } = useScroll(area)

const messages = computed(() => {
  return [...messagesStore.messages]
})

async function scrollToBottom() {
  await nextTick()
  if (area.value) y.value = area.value?.scrollHeight
}

watch(messages, async () => {
  await scrollToBottom()
})
</script>

<template>
  <div class="h-full">
    <!--    <button class="position-absolute scroll-down" @click="scrollToBottom">UP</button>-->
    <div class="flex flex-col h-full">
      <div class="flex h-full flex-col overflow-hidden">
        <message-toolbar class="grow-0" />

        <div class="px-8 gap-2 grow flex flex-col-reverse overflow-y-auto" ref="messageArea">
          <message-data
            v-for="message in messages"
            :key="message.id"
            :text="message.text"
            :my="authStore.me?.id === message.user_id"
            :created-at="message.created_at"
          ></message-data>
          <!--          <div class="p-4 border" v-for="v in 101" :key="v">text {{ v }}</div>-->
        </div>

        <message-form class="grow-0 bg-green-200" />
      </div>
    </div>
  </div>
</template>

<style scoped>
.scroll-down {
  right: 16px;
  bottom: 104px;
}
.test {
  height: 400px;
}
</style>
