<script setup lang="ts">
import { request, unwrapApiBody, type ApiResponse } from '../../../utils/http/factory'

definePageMeta({ title: '文章' })

type Row = { id: number; title: string; slug: string; visibility: string }

const posts = ref<Row[]>([])
const loading = ref(true)

async function load() {
  loading.value = true
  try {
    const res = await request<ApiResponse<{ posts: Row[] }>>('/api/me/posts')
    posts.value = unwrapApiBody(res).posts
  } finally {
    loading.value = false
  }
}

onMounted(load)
</script>

<template>
  <UContainer class="py-8 space-y-4">
    <div class="flex justify-between items-center">
      <h1 class="text-2xl font-semibold">
        文章
      </h1>
      <UButton to="/me/posts/new">
        新建
      </UButton>
    </div>
    <div v-if="loading" class="text-muted">
      加载中…
    </div>
    <UEmpty v-else-if="!posts.length" title="暂无文章" description="创建第一篇 Markdown 文章" />
    <ul v-else class="space-y-2">
      <li v-for="p in posts" :key="p.id" class="flex justify-between border border-default rounded-lg p-3">
        <div>
          <div class="font-medium">
            {{ p.title }}
          </div>
          <div class="text-xs text-muted">
            /{{ p.slug }} · {{ p.visibility }}
          </div>
        </div>
        <UButton :to="`/me/posts/${p.id}`" size="xs" variant="ghost">
          编辑
        </UButton>
      </li>
    </ul>
  </UContainer>
</template>
