<script setup lang="ts">
import { onMounted, ref } from 'vue'
import CategoryTree from '../components/CategoryTree.vue'
import { fetchCategoryTree } from '../api/category'
import { fetchDemandBelongCategory } from '../api/demand'
import type { CategoryNode } from '../types/category'
import type { DemandsByCategory } from '../types/demand'
import { groupDemandsByCategory } from '../types/demand'

const nodes = ref<CategoryNode[]>([])
const demandsByCategory = ref<DemandsByCategory>({})
const loading = ref(true)
const error = ref<string | null>(null)

onMounted(async () => {
  try {
    const [tree, demands] = await Promise.all([
      fetchCategoryTree(),
      fetchDemandBelongCategory(),
    ])
    nodes.value = tree.nodes ?? []
    demandsByCategory.value = groupDemandsByCategory(demands.items ?? [])
  } catch (e) {
    error.value = e instanceof Error ? e.message : String(e)
  } finally {
    loading.value = false
  }
})
</script>

<template>
  <div class="view">
    <div v-if="loading" class="state">正在加载分类树…</div>
    <div v-else-if="error" class="state error">{{ error }}</div>
    <CategoryTree
      v-else
      :nodes="nodes"
      :demands-by-category="demandsByCategory"
    />
  </div>
</template>

<style scoped>
.view {
  height: 100%;
  min-height: 0;
}

.state {
  padding: 64px 24px;
  text-align: center;
  color: #64748b;
  font-size: 15px;
}

.state.error {
  color: #b91c1c;
}
</style>
