<template>
<div class="d-flex flex-column vh-100">
  <header class="bg-light px-3 py-2 d-flex flex-row align-items-center">
    <span class="mb-0 me-3 fs-3">{{ channel.name }}</span>
    <Key :channel="channel" />
  </header>
  <div class="messages overflow-auto p-3">
    <Message v-for="message in messages" :key="message.id" :message="message" />
    <div ref="bottom"></div>
  </div>
  <Input :channel="channel" class="mt-auto px-3" />
</div>
</template>

<script setup>
import { computed, onMounted, onUpdated, ref } from 'vue'
import { onBeforeRouteUpdate, useRoute } from 'vue-router'
import { useChannelStore } from '../stores/channelStore'
import { useMessageStore } from '../stores/messageStore'
import Input from '../components/Input.vue'
import Message from '../components/Message.vue'
import Key from '../components/Key.vue'

const route = useRoute()
const channelStore = useChannelStore()
const messageStore = useMessageStore()

const channel = computed(() => { return channelStore.getChannelById(route.params.channelId) })
const messages = computed(() => { return messageStore.getMessagesByChannelId(route.params.channelId) })

// Show the key.
const locked = ref(false)
onBeforeRouteUpdate(async (to, from) => { locked.value = false })

// Scroll to bottom.
const bottom = ref(null)
onUpdated(() => {
  bottom.value.scrollIntoView({ behavior: "smooth", block: "center" })
})
onMounted(() => {
  bottom.value.scrollIntoView({ block: "center" })
})
</script>
