<template>
  <div class="docs-page">
    <!-- 面包屑 -->
    <div class="breadcrumb-bar">
      <div class="breadcrumb-inner">
        <a-breadcrumb>
          <a-breadcrumb-item>
            <a href="/developer">开发者中心</a>
          </a-breadcrumb-item>
          <a-breadcrumb-item>
            <NuxtLink to="/developer/docs">开发文档</NuxtLink>
          </a-breadcrumb-item>
          <a-breadcrumb-item v-if="page">{{ page.title }}</a-breadcrumb-item>
        </a-breadcrumb>
      </div>
    </div>

    <div class="docs-layout">
      <!-- 左侧导航 -->
      <aside class="docs-sidebar">
        <div class="sidebar-inner">
          <div class="sidebar-back">
            <NuxtLink to="/developer/docs" class="back-link">
              ← 返回文档中心
            </NuxtLink>
          </div>

          <!-- 导航树 -->
          <nav class="sidebar-nav">
            <div v-for="cat in navCategories" :key="cat.key" class="nav-group">
              <div class="nav-group-title" @click="toggleGroup(cat.key)">
                <span>{{ cat.icon }}</span>
                <span class="nav-group-label">{{ cat.label }}</span>
                <span class="nav-group-arrow" :class="{ collapsed: !expandedGroups[cat.key] }">▾</span>
              </div>
              <div v-show="expandedGroups[cat.key]" class="nav-group-items">
                <NuxtLink
                  v-for="doc in cat.items"
                  :key="doc.stem?.path"
                  :to="toPageUrl(doc.stem?.path)"
                  class="nav-item"
                  :class="{ active: isActive(doc) }"
                >
                  {{ doc.title }}
                </NuxtLink>
              </div>
            </div>
          </nav>
        </div>
      </aside>

      <!-- 右侧内容 -->
      <main class="docs-main">
        <div v-if="page" class="docs-content">
          <h1 class="docs-title">{{ page.title }}</h1>
          <p v-if="page.description" class="docs-desc">{{ page.description }}</p>

          <ContentRenderer :value="page" />

          <!-- 上下篇导航 -->
          <div class="docs-nav-footer">
            <div v-if="prevDoc" class="nav-footer-item prev" @click="navigateToDoc(prevDoc)">
              <span class="nav-footer-dir">← 上一篇</span>
              <span class="nav-footer-title">{{ prevDoc.title }}</span>
            </div>
            <div v-else />
            <div v-if="nextDoc" class="nav-footer-item next" @click="navigateToDoc(nextDoc)">
              <span class="nav-footer-dir">下一篇 →</span>
              <span class="nav-footer-title">{{ nextDoc.title }}</span>
            </div>
          </div>
        </div>

        <!-- 404 -->
        <div v-else class="docs-not-found">
          <div class="not-found-icon">📄</div>
          <h2>文档未找到</h2>
          <p>你访问的文档不存在或已被移除。</p>
          <NuxtLink to="/developer/docs" class="back-to-docs">
            ← 返回文档中心
          </NuxtLink>
        </div>
      </main>
    </div>
  </div>
</template>

<script setup lang="ts">
definePageMeta({ layout: 'developer' })

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

// 将 /developer/docs/xxx 转换为 /docs/xxx 用于 Nuxt Content 查询
const contentPath = computed(() => {
  return '/docs/' + (route.params.slug as string[]).join('/')
})

// 查询当前文档
const { data: page } = await useAsyncData(contentPath.value, () =>
  queryCollection('docs').path(contentPath.value).first()
)

// 设置页面标题
watchEffect(() => {
  if (page.value) {
    useHead({ title: `${page.value.title} - 开发文档 - 开发者中心` })
  }
})

// 查询所有文档
const { data: allDocs } = await useAsyncData('docs-nav', () =>
  queryCollection('docs')
    .order('order', 'ASC')
    .all()
)

// 分类定义
const categoryMap: Record<string, { label: string; icon: string }> = {
  'getting-started': { label: '快速开始', icon: '🚀' },
  'api': { label: 'API 参考', icon: '🔌' },
  'ai': { label: 'AI 功能', icon: '🤖' },
  'deploy': { label: '部署运维', icon: '🚢' },
}

// 构建导航分类
const navCategories = computed(() => {
  const docs = allDocs.value || []
  const groups: { key: string; label: string; icon: string; items: any[] }[] = []
  for (const [key, val] of Object.entries(categoryMap)) {
    const items = docs.filter((d: any) => d.category === key)
    if (items.length) {
      groups.push({ key, label: val.label, icon: val.icon, items })
    }
  }
  return groups
})

// 分组展开状态
const expandedGroups = reactive<Record<string, boolean>>({})
for (const cat of navCategories.value) {
  expandedGroups[cat.key] = true
}

function toggleGroup(key: string) {
  expandedGroups[key] = !expandedGroups[key]
}

// 判断是否为当前活动项
function isActive(doc: any) {
  return doc.stem?.path === contentPath.value
}

// 路径转换：/docs/xxx → /developer/docs/xxx
function toPageUrl(path?: string) {
  if (!path) return ''
  return path.replace(/^\/docs/, '/developer/docs')
}

// 上/下篇文档
const currentIndex = computed(() => {
  const docs = allDocs.value || []
  return docs.findIndex((d: any) => d.stem?.path === contentPath.value)
})

const prevDoc = computed(() => {
  const idx = currentIndex.value
  return idx > 0 ? (allDocs.value as any[])?.[idx - 1] : null
})

const nextDoc = computed(() => {
  const docs = allDocs.value || []
  const idx = currentIndex.value
  return idx < docs.length - 1 ? docs[idx + 1] : null
})

function navigateToDoc(doc: any) {
  if (doc?.stem?.path) {
    router.push(toPageUrl(doc.stem.path))
  }
}

// 滚动到顶部
onMounted(() => {
  window.scrollTo(0, 0)
})
</script>

<style scoped>
.docs-page {
  min-height: 100%;
  background: #f9fafb;
}

/* 面包屑 */
.breadcrumb-bar {
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
}

.breadcrumb-inner {
  max-width: 100%;
  padding: 12px 28px;
}

/* 布局 */
.docs-layout {
  display: flex;
  min-height: calc(100vh - 160px);
}

/* 左侧导航 */
.docs-sidebar {
  width: 260px;
  flex-shrink: 0;
  border-right: 1px solid #f0f0f0;
  background: #fff;
  overflow-y: auto;
  height: calc(100vh - 160px);
  position: sticky;
  top: 0;
}

.sidebar-inner {
  padding: 16px 0;
}

.sidebar-back {
  padding: 0 16px 12px;
  border-bottom: 1px solid #f5f5f5;
  margin-bottom: 8px;
}

.back-link {
  font-size: 13px;
  color: #4f46e5;
  text-decoration: none;
  display: block;
}

.back-link:hover {
  color: #3730a3;
}

/* 导航树 */
.sidebar-nav {
  padding: 4px 0;
}

.nav-group {
  margin-bottom: 4px;
}

.nav-group-title {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  font-size: 12px;
  font-weight: 600;
  color: rgba(0, 0, 0, 0.45);
  text-transform: uppercase;
  letter-spacing: 0.05em;
  cursor: pointer;
  user-select: none;
  transition: color 0.15s;
}

.nav-group-title:hover {
  color: rgba(0, 0, 0, 0.65);
}

.nav-group-label { flex: 1; }

.nav-group-arrow {
  font-size: 10px;
  transition: transform 0.2s;
  color: rgba(0, 0, 0, 0.3);
}

.nav-group-arrow.collapsed {
  transform: rotate(-90deg);
}

.nav-group-items {
  padding: 2px 0;
}

.nav-item {
  display: block;
  padding: 7px 16px 7px 36px;
  font-size: 13px;
  color: rgba(0, 0, 0, 0.6);
  text-decoration: none;
  transition: all 0.15s;
  border-left: 2px solid transparent;
  line-height: 1.5;
}

.nav-item:hover {
  color: #4f46e5;
  background: #f5f7ff;
}

.nav-item.active {
  color: #4f46e5;
  font-weight: 500;
  background: #eef2ff;
  border-left-color: #4f46e5;
}

/* 主内容区 */
.docs-main {
  flex: 1;
  min-width: 0;
}

.docs-content {
  max-width: 800px;
  margin: 0 auto;
  padding: 32px 40px 60px;
}

.docs-title {
  font-size: 28px;
  font-weight: 700;
  color: rgba(0, 0, 0, 0.88);
  margin: 0 0 8px;
  line-height: 1.3;
}

.docs-desc {
  font-size: 15px;
  color: rgba(0, 0, 0, 0.45);
  margin: 0 0 32px;
  line-height: 1.6;
}

/* Nuxt Content 渲染的 Markdown 内容样式 */
.docs-content :deep(h2) {
  font-size: 22px;
  font-weight: 600;
  color: rgba(0, 0, 0, 0.85);
  margin: 36px 0 16px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.docs-content :deep(h3) {
  font-size: 18px;
  font-weight: 600;
  color: rgba(0, 0, 0, 0.82);
  margin: 28px 0 12px;
}

.docs-content :deep(h4) {
  font-size: 15px;
  font-weight: 600;
  color: rgba(0, 0, 0, 0.78);
  margin: 20px 0 10px;
}

.docs-content :deep(p) {
  font-size: 14px;
  line-height: 1.75;
  color: rgba(0, 0, 0, 0.72);
  margin: 0 0 16px;
}

.docs-content :deep(blockquote) {
  margin: 16px 0;
  padding: 12px 16px;
  border-left: 3px solid #4f46e5;
  background: #f5f7ff;
  border-radius: 0 8px 8px 0;
}

.docs-content :deep(blockquote p) {
  margin: 0;
  color: rgba(0, 0, 0, 0.6);
}

.docs-content :deep(ul),
.docs-content :deep(ol) {
  padding-left: 24px;
  margin: 12px 0 20px;
}

.docs-content :deep(li) {
  font-size: 14px;
  line-height: 1.75;
  color: rgba(0, 0, 0, 0.72);
  margin-bottom: 4px;
}

.docs-content :deep(code) {
  font-size: 13px;
  padding: 2px 6px;
  background: #f3f4f6;
  border-radius: 4px;
  font-family: 'JetBrains Mono', 'Fira Code', Consolas, monospace;
  color: #e11d48;
}

.docs-content :deep(pre) {
  margin: 16px 0;
  padding: 16px 20px;
  background: #1e1e2e;
  border-radius: 10px;
  overflow-x: auto;
}

.docs-content :deep(pre code) {
  background: transparent;
  padding: 0;
  color: #cdd6f4;
  font-size: 13px;
  line-height: 1.6;
}

.docs-content :deep(table) {
  width: 100%;
  border-collapse: collapse;
  margin: 16px 0;
  font-size: 13px;
}

.docs-content :deep(th) {
  background: #f9fafb;
  padding: 10px 14px;
  text-align: left;
  font-weight: 600;
  color: rgba(0, 0, 0, 0.72);
  border-bottom: 2px solid #e5e7eb;
}

.docs-content :deep(td) {
  padding: 10px 14px;
  border-bottom: 1px solid #f0f0f0;
  color: rgba(0, 0, 0, 0.65);
}

.docs-content :deep(tr:hover td) {
  background: #fafbff;
}

.docs-content :deep(a) {
  color: #4f46e5;
  text-decoration: none;
}

.docs-content :deep(a:hover) {
  text-decoration: underline;
}

.docs-content :deep(hr) {
  border: none;
  border-top: 1px solid #f0f0f0;
  margin: 28px 0;
}

.docs-content :deep(strong) {
  color: rgba(0, 0, 0, 0.85);
  font-weight: 600;
}

/* 上下篇导航 */
.docs-nav-footer {
  display: flex;
  justify-content: space-between;
  gap: 16px;
  margin-top: 48px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}

.nav-footer-item {
  flex: 1;
  max-width: 50%;
  padding: 14px 16px;
  border-radius: 10px;
  border: 1px solid #f0f0f0;
  background: #fff;
  cursor: pointer;
  transition: all 0.2s;
}

.nav-footer-item:hover {
  border-color: #c7d2fe;
  box-shadow: 0 2px 12px rgba(79, 70, 229, 0.08);
}

.nav-footer-item.next {
  text-align: right;
  margin-left: auto;
}

.nav-footer-dir {
  display: block;
  font-size: 12px;
  color: rgba(0, 0, 0, 0.4);
  margin-bottom: 4px;
}

.nav-footer-title {
  font-size: 13px;
  font-weight: 500;
  color: #4f46e5;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 404 */
.docs-not-found {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  padding: 80px 24px;
  min-height: 50vh;
}

.not-found-icon {
  font-size: 56px;
  margin-bottom: 16px;
}

.docs-not-found h2 {
  font-size: 20px;
  font-weight: 600;
  color: rgba(0, 0, 0, 0.72);
  margin: 0 0 8px;
}

.docs-not-found p {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.4);
  margin: 0 0 20px;
}

.back-to-docs {
  color: #4f46e5;
  font-size: 14px;
  text-decoration: none;
  padding: 8px 16px;
  border-radius: 8px;
  border: 1px solid #e0e7ff;
  transition: all 0.15s;
}

.back-to-docs:hover {
  background: #eef2ff;
}

/* 响应式 */
@media (max-width: 1024px) {
  .docs-sidebar {
    display: none;
  }
  .docs-content {
    padding: 24px 20px 48px;
  }
}
</style>
