<script setup lang="ts">
import { useAuthSession } from '../../../composables/useAuthSession'

definePageMeta({ title: '文章' })

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

const posts = ref<Row[]>([])
const loading = ref(true)
const { user, refresh: refreshAuth } = useAuthSession()
const { fetchData } = useClientApi()

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

onMounted(() => {
  void refreshAuth(true)
  void load()
})

function postDetailHref(slug: string, visibility: string) {
  const ps = user.value?.publicSlug
  if (!ps || visibility !== 'public') {
    return ''
  }
  return `/@${ps}/posts/${encodeURIComponent(slug)}`
}
</script>

<template>
  <UContainer class="py-8 space-y-4 max-w-3xl">
    <div class="flex flex-wrap justify-between items-center gap-3">
      <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 flex-wrap justify-between items-center gap-3 border border-default rounded-lg p-3"
      >
        <div class="min-w-0 flex-1">
          <div class="font-medium truncate">
            {{ p.title }}
          </div>
          <div class="text-xs text-muted">
            /{{ p.slug }} · {{ p.visibility }}
          </div>
        </div>
        <div class="flex flex-wrap gap-1 justify-end">
          <UButton
            v-if="postDetailHref(p.slug, p.visibility)"
            :to="postDetailHref(p.slug, p.visibility)"
            size="xs"
            variant="soft"
            color="neutral"
          >
            详情
          </UButton>
          <UButton :to="`/me/posts/${p.id}`" size="xs" variant="ghost">
            编辑
          </UButton>
        </div>
      </li>
    </ul>
  </UContainer>
</template>
