<script setup lang="ts">
import { readPostPreviewDraft, type PostPreviewDraftPayload } from '../../../../utils/post-preview-draft'
import { renderSafeMarkdown } from '../../../../utils/render-markdown'

const route = useRoute()
const draft = ref<PostPreviewDraftPayload | null>(null)
const previewStatus = ref<'loading' | 'missing_key' | 'invalid' | 'ready'>('loading')

const visibilityLabel = computed(() => {
  if (!draft.value) {
    return ''
  }
  if (draft.value.visibility === 'private') {
    return '私密预览'
  }
  if (draft.value.visibility === 'unlisted') {
    return '仅链接预览'
  }
  return '公开预览'
})

const renderedBody = computed(() => {
  if (!draft.value) {
    return ''
  }
  return renderSafeMarkdown(draft.value.bodyMarkdown)
})

onMounted(() => {
  const key = typeof route.query.key === 'string' ? route.query.key : ''
  if (!key) {
    previewStatus.value = 'missing_key'
    return
  }
  const payload = readPostPreviewDraft(key)
  if (!payload) {
    previewStatus.value = 'invalid'
    return
  }
  draft.value = payload
  previewStatus.value = 'ready'
})

usePageTitle(() => {
  const t = draft.value?.title?.trim()
  return t ? [t, '预览'] : ['草稿预览']
})
</script>

<template>
  <UContainer class="py-10 space-y-6">
    <div v-if="previewStatus === 'loading'" class="text-sm text-muted">
      预览加载中…
    </div>
    <template v-if="draft">
      <div class="flex flex-wrap items-center gap-2">
        <UBadge color="neutral" variant="soft">
          {{ visibilityLabel }}
        </UBadge>
        <UBadge color="primary" variant="outline">
          草稿
        </UBadge>
      </div>

      <h1 class="text-2xl font-semibold">
        {{ draft.title || '未命名文章' }}
      </h1>
      <p v-if="draft.excerpt" class="text-muted">
        {{ draft.excerpt }}
      </p>
      <article
        class="prose prose-neutral dark:prose-invert max-w-none prose-a:text-primary prose-img:rounded-lg prose-headings:text-highlighted prose-p:text-default prose-strong:text-highlighted markdown-body green"
        v-html="renderedBody"
      />
    </template>
    <UAlert
      v-else-if="previewStatus === 'missing_key'"
      color="neutral"
      title="请从编辑页打开预览"
      description="当前地址缺少预览参数，请返回新建/编辑页点击“预览（新窗口）”。"
    />
    <UAlert
      v-else-if="previewStatus === 'invalid'"
      color="warning"
      title="预览内容不存在或已失效"
      description="请返回新建/编辑页，重新点击预览。"
    />
  </UContainer>
</template>
