<template>
  <NCard title="产物汇总">
    <NSpin :show="loading">
      <div v-if="grouped.length > 0" class="space-y-4">
        <div v-for="g in grouped" :key="g.phase">
          <h3 class="text-sm font-semibold mb-2">
            {{ PHASE_TITLE[g.phase] }}（{{ g.items.length }} 个版本）
          </h3>
          <NList :show-divider="false">
            <NListItem v-for="a in g.items" :key="a.id">
              <NThing class="cursor-pointer" @click="selected = selected?.id === a.id ? null : a">
                <template #header>
                  <span
                    class="text-sm font-medium"
                    :class="selected?.id === a.id ? 'text-blue-600' : ''"
                    >v{{ a.version }}</span
                  >
                  <NTag v-if="a.source_message_id" size="tiny" class="ml-1"> AI </NTag>
                </template>
                <template #header-extra>
                  <span class="text-xs text-gray-400">
                    {{ formatDateTime(a.created_at) }}
                  </span>
                </template>
                <span v-if="a.note" class="text-xs text-gray-500">{{ a.note }}</span>
              </NThing>
            </NListItem>
          </NList>
        </div>

        <template v-if="selected">
          <NDivider />
          <!-- eslint-disable vue/no-v-html -->
          <div class="prose prose-sm max-w-none" v-html="rendered" />
          <!-- eslint-enable vue/no-v-html -->
        </template>
      </div>
      <NEmpty v-else-if="!loading" description="暂无任何阶段产物" />
    </NSpin>
  </NCard>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { NCard, NDivider, NEmpty, NList, NListItem, NSpin, NTag, NThing } from 'naive-ui'
import type { Artifact, ArtifactPhase } from '@/api/projects'
import { md } from '@/utils/markdown'
import { formatDateTime } from '@/utils/date'
import { useRequirementsStore } from '@/stores/requirements'

const PHASE_TITLE: Record<ArtifactPhase, string> = {
  planning: '规划',
  prototyping: '原型',
  auditing: '评审',
}
const PHASE_ORDER: ArtifactPhase[] = ['planning', 'prototyping', 'auditing']

const props = defineProps<{
  slug: string
  number: number
}>()

const store = useRequirementsStore()

const artifacts = ref<Artifact[]>([])
const loading = ref(false)
const selected = ref<Artifact | null>(null)

const grouped = computed(() =>
  PHASE_ORDER.map((phase) => ({
    phase,
    items: artifacts.value.filter((a) => a.phase === phase),
  })).filter((g) => g.items.length > 0),
)

const rendered = computed(() => (selected.value ? md.render(selected.value.content) : ''))

onMounted(async () => {
  loading.value = true
  try {
    artifacts.value = await store.listArtifacts(props.slug, props.number)
  } finally {
    loading.value = false
  }
})
</script>
