<template>
  <main class="page">
    <section class="page-hero" :style="heroStyle">
      <div class="page-hero-mask">
        <div class="mx-auto max-w-screen-xl px-4 py-8">
          <a-breadcrumb class="page-breadcrumb">
            <a-breadcrumb-item>
              <NuxtLink to="/">首页</NuxtLink>
            </a-breadcrumb-item>
            <a-breadcrumb-item v-if="parentName">{{ parentName }}</a-breadcrumb-item>
            <a-breadcrumb-item>{{ pageTitle }}</a-breadcrumb-item>
          </a-breadcrumb>

          <div class="page-hero-title">{{ pageTitle }}</div>

          <div class="page-hero-meta">
            <a-tag v-if="modelName" color="green">{{ modelName }}</a-tag>
            <a-tag v-if="createTime" color="blue">{{ createTime }}</a-tag>
            <a-tag v-if="typeof readNum === 'number'" color="default">阅读 {{ readNum }}</a-tag>
          </div>
        </div>
      </div>
    </section>

    <section class="mx-auto max-w-screen-xl px-4 py-10">
      <a-card class="page-card" :bordered="false">
        <div class="page-card-head">
          <a-space>
            <a-button @click="goBack">返回</a-button>
            <a-button type="primary" @click="navigateTo('/')">首页</a-button>
          </a-space>
        </div>

        <a-divider class="!my-4" />

        <div class="page-content">
          <a-skeleton v-if="pending" active :paragraph="{ rows: 10 }" />

          <a-result
            v-else-if="loadError"
            status="error"
            title="页面加载失败"
            :sub-title="loadError.message"
          >
            <template #extra>
              <a-space>
                <a-button type="primary" @click="refresh()">重试</a-button>
                <a-button @click="navigateTo('/')">返回首页</a-button>
              </a-space>
            </template>
          </a-result>

          <a-result
            v-else-if="!navigation"
            status="404"
            title="页面不存在"
            sub-title="未找到对应的页面内容。"
          >
            <template #extra>
              <a-space>
                <a-button type="primary" @click="navigateTo('/')">返回首页</a-button>
              </a-space>
            </template>
          </a-result>

          <template v-else>
            <a-alert v-if="!pageContent" class="mb-6" type="info" show-icon message="暂无内容" />
            <RichText v-else :content="pageContent" />
          </template>
        </div>
      </a-card>
    </section>
  </main>
</template>

<script setup lang="ts">
import { getCmsNavigation } from '@/api/cms/cmsNavigation'
import type { CmsNavigation } from '@/api/cms/cmsNavigation/model'

const route = useRoute()
const router = useRouter()

const id = computed(() => {
  const raw = route.params.id
  const text = Array.isArray(raw) ? raw[0] : raw
  const n = Number(text)
  return Number.isFinite(n) ? n : NaN
})

const {
  data: navigation,
  pending,
  error: loadError,
  refresh
} = await useAsyncData<CmsNavigation | null>(
  () => `cms-navigation-${String(route.params.id)}`,
  async () => {
    if (!Number.isFinite(id.value)) return null
    return await getCmsNavigation(id.value)
  },
  { watch: [id] }
)

function pickString(obj: Record<string, unknown>, key: string) {
  const v = obj[key]
  return typeof v === 'string' ? v.trim() : ''
}

function coerceContent(value: unknown): string {
  if (typeof value === 'string') return value
  if (value && typeof value === 'object') {
    try {
      return JSON.stringify(value)
    } catch {
      return String(value)
    }
  }
  return ''
}

const pageTitle = computed(() => {
  const nav = navigation.value as unknown as Record<string, unknown> | null
  if (!nav) return '页面'
  return pickString(nav, 'title') || pickString(nav, 'label') || `页面 ${String(route.params.id)}`
})

const heroStyle = computed(() => {
  const nav = navigation.value as unknown as Record<string, unknown> | null
  const banner = nav ? pickString(nav, 'banner') : ''
  if (banner) {
    return {
      backgroundImage: `url(${banner})`
    }
  }
  return {}
})

const parentName = computed(() => {
  const nav = navigation.value as unknown as Record<string, unknown> | null
  if (!nav) return ''
  return pickString(nav, 'parentName')
})

const modelName = computed(() => {
  const nav = navigation.value as unknown as Record<string, unknown> | null
  if (!nav) return ''
  return pickString(nav, 'modelName')
})

const createTime = computed(() => {
  const nav = navigation.value as unknown as Record<string, unknown> | null
  if (!nav) return ''
  return pickString(nav, 'createTime')
})

const readNum = computed(() => {
  const nav = navigation.value as unknown as Record<string, unknown> | null
  if (!nav) return undefined
  const n = nav.readNum
  if (typeof n === 'number' && Number.isFinite(n)) return n
  if (typeof n === 'string' && n.trim() && Number.isFinite(Number(n))) return Number(n)
  return undefined
})

const pageContent = computed(() => {
  const nav = navigation.value as unknown as Record<string, unknown> | null
  if (!nav) return ''

  // Different CMS deployments may store content under different keys.
  const candidates = [
    'content',
    'html',
    'body',
    'text',
    'pageContent',
    'articleContent',
    'suffix',
    'comments',
    'meta',
    'style'
  ]

  for (const k of candidates) {
    const val = nav[k]
    const text = coerceContent(val).trim()
    if (text) return text
  }

  return ''
})

const seoTitle = computed(() => pageTitle.value)
const seoDescription = computed(() =>
  pageContent.value ? pageContent.value.slice(0, 120) : `${pageTitle.value} - 页面内容`
)

useSeoMeta({
  title: seoTitle,
  description: seoDescription,
  ogTitle: seoTitle,
  ogDescription: seoDescription,
  ogType: 'article'
})

const canonicalUrl = computed(() => {
  if (import.meta.client) return window.location.href
  try {
    return useRequestURL().href
  } catch {
    return ''
  }
})

useHead(() => ({
  link: canonicalUrl.value ? [{ rel: 'canonical', href: canonicalUrl.value }] : []
}))

function goBack() {
  if (import.meta.client && window.history.length > 1) {
    router.back()
    return
  }
  navigateTo('/')
}
</script>

<style scoped>
.page {
  background: #f4f6f8;
}

.page-hero {
  background:
    radial-gradient(circle at 15% 20%, rgba(22, 163, 74, 0.22), transparent 60%),
    radial-gradient(circle at 85% 10%, rgba(59, 130, 246, 0.18), transparent 55%),
    linear-gradient(180deg, #ffffff, #f8fafc);
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
}

.page-hero-mask {
  background: linear-gradient(180deg, rgba(255, 255, 255, 0.88), rgba(255, 255, 255, 0.92));
}

.page-breadcrumb {
  color: rgba(0, 0, 0, 0.6);
}

.page-hero-title {
  margin-top: 10px;
  font-size: 30px;
  font-weight: 900;
  color: rgba(0, 0, 0, 0.88);
  line-height: 1.2;
}

.page-hero-meta {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.page-card {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 10px 28px rgba(0, 0, 0, 0.06);
}

.page-card-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.page-content {
  max-width: 860px;
  margin: 0 auto;
}
</style>
