<script setup lang="ts">
import ChatroomCard from '@/components/chatroom/ChatroomCard.vue'
import { ref, watch } from 'vue'
import { api } from '@/tools/web.ts'
import type { ChatroomPublic } from '@/types/chatroom.ts'
import type { ReturnDto } from '@/types/response.ts'
import ChatroomCreatorModal from '@/components/chatroom/ChatroomCreatorModal.vue'
import { useNowUser } from '@/stores/now-user.ts'
import { useHead } from '@unhead/vue'

useHead({
  title: '聊天室列表',
})

const NOWUSER = useNowUser()

const crList = ref<ChatroomPublic[]>([])

const showModal = ref(false)

function load() {
  api
    .get('/chatroom/')
    .then((res) => res.data as ReturnDto)
    .then((data) => data.result as ChatroomPublic[])
    .then((list) => {
      crList.value = list
    })
}

watch(
  () => NOWUSER.isLogin,
  () => {
    load()
  },
  { immediate: true },
)
</script>

<template>
  <n-card title="聊天室">
    查看您创建的所有聊天室。
    <template #footer>
      <n-flex>
        <n-button secondary type="primary" style="margin-left: auto" @click="showModal = true">
          创建聊天室
        </n-button>
      </n-flex>
    </template>
  </n-card>
  <div id="chatroom-card-list">
    <chatroom-card
      v-for="cr in crList"
      v-bind:key="cr.id"
      :id="cr.id"
      :name="cr.name"
      :description="cr.description"
      :feature_image="cr.feature_image"
      info-mode
    />
  </div>

  <chatroom-creator-modal v-model:show-modal="showModal" />
</template>

<style scoped>
div#chatroom-card-list {
  width: 800px;

  display: flex;
  flex-direction: column;
  gap: 6px;
}
</style>
