<template>
  <div class="kb-container">
    <Breadcrumb :items="['知识管理', '知识库文档']" />
    
    <div class="kb-content">
      <!-- 左侧：文档列表 -->
      <div class="kb-left-panel">
        <a-card class="general-card" :body-style="{ padding: '12px' }">
          <!-- 标签页切换 -->
          <a-tabs v-model:active-key="activeTab" size="small" @change="handleTabChange">
            <a-tab-pane key="mine" title="我的" />
            <a-tab-pane key="all" title="全部" />
          </a-tabs>

          <!-- 搜索框 -->
          <a-input-search
            v-model="searchKeyword"
            placeholder="搜索文档..."
            allow-clear
            @search="handleSearch"
            @press-enter="handleSearch"
          />

          <!-- 工具栏 -->
          <div class="list-toolbar">
            <a-button type="primary" size="small" @click="handleCreate">
              <template #icon><icon-plus /></template>
              新建
            </a-button>
            <a-button size="small" @click="fetchData">
              <template #icon><icon-refresh /></template>
            </a-button>
          </div>

          <!-- 文档列表 -->
          <div class="document-list">
            <a-spin :loading="loading" style="width: 100%">
              <a-empty v-if="documentList.length === 0" description="暂无文档" />
              <div
                v-for="doc in documentList"
                :key="doc.id"
                class="document-item"
                :class="{ active: currentDocument?.id === doc.id }"
                @click="handleSelectDocument(doc)"
              >
                <div class="doc-title">
                  <icon-file class="doc-icon" />
                  <span class="title-text">{{ doc.title }}</span>
                </div>
                <div class="doc-meta">
                  <a-tag :color="getStatusColor(doc.status)" size="small">
                    {{ getStatusText(doc.status) }}
                  </a-tag>
                  <span class="doc-time">{{ formatDate(doc.updated_at) }}</span>
                </div>
              </div>
            </a-spin>
          </div>

          <!-- 分页 -->
          <div class="list-pagination">
            <a-pagination
              v-model:current="page"
              :total="total"
              :page-size="pageSize"
              size="small"
              simple
              @change="handlePageChange"
            />
          </div>
        </a-card>
      </div>

      <!-- 右侧：Markdown编辑器 -->
      <div class="kb-right-panel">
        <a-card class="general-card editor-card">
          <template #title>
            <div class="editor-header">
              <a-input
                v-if="isEditing"
                v-model="editForm.title"
                placeholder="请输入文档标题"
                :max-length="200"
                class="title-input"
              />
              <span v-else class="title-text">
                {{ currentDocument?.title || '请选择或新建文档' }}
              </span>
            </div>
          </template>
          <template #extra>
            <a-space v-if="currentDocument || isEditing">
              <!-- 编辑模式切换（仅在编辑状态时显示） -->
              <a-button-group v-if="isEditing">
                <a-button
                  :type="editorMode === 'edit' ? 'primary' : 'secondary'"
                  size="small"
                  @click="editorMode = 'edit'"
                >
                  源码
                </a-button>
                <a-button
                  :type="editorMode === 'preview' ? 'primary' : 'secondary'"
                  size="small"
                  @click="editorMode = 'preview'"
                >
                  预览
                </a-button>
                <a-button
                  :type="editorMode === 'split' ? 'primary' : 'secondary'"
                  size="small"
                  @click="editorMode = 'split'"
                >
                  分栏
                </a-button>
              </a-button-group>
              
              <!-- 操作按钮 -->
              <template v-if="isEditing">
                <a-button type="primary" size="small" :loading="saving" @click="handleSave">
                  保存
                </a-button>
                <a-button size="small" @click="handleCancelEdit">
                  取消
                </a-button>
              </template>
              <template v-else-if="currentDocument">
                <a-button
                  v-if="activeTab === 'mine'"
                  type="primary"
                  size="small"
                  @click="handleStartEdit"
                >
                  编辑
                </a-button>
                <a-button
                  v-if="activeTab === 'mine' && (currentDocument.status === 'draft' || currentDocument.status === 'rejected')"
                  size="small"
                  @click="handlePublish"
                >
                  发布
                </a-button>
                <a-button
                  v-if="currentDocument.status === 'reviewed'"
                  :type="isFavorited ? 'primary' : 'secondary'"
                  size="small"
                  @click="handleToggleFavorite"
                >
                  <template #icon>
                    <icon-star-fill v-if="isFavorited" />
                    <icon-star v-else />
                  </template>
                </a-button>
                <a-button size="small" @click="handleDownload">
                  <template #icon><icon-download /></template>
                </a-button>
                <a-button
                  v-if="activeTab === 'mine'"
                  size="small"
                  status="danger"
                  @click="handleDelete"
                >
                  删除
                </a-button>
              </template>
            </a-space>
          </template>

          <!-- 编辑器内容 -->
          <div class="editor-content">
            <template v-if="currentDocument || isEditing">
              <!-- 文档元信息 -->
              <div v-if="!isEditing && currentDocument" class="doc-info">
                <a-descriptions :column="4" size="small">
                  <a-descriptions-item label="类型">
                    <a-tag :color="getTypeColor(currentDocument.type)" size="small">
                      {{ getTypeText(currentDocument.type) }}
                    </a-tag>
                  </a-descriptions-item>
                  <a-descriptions-item label="作者">{{ currentDocument.author_name }}</a-descriptions-item>
                  <a-descriptions-item label="更新时间">{{ formatTime(currentDocument.updated_at) }}</a-descriptions-item>
                  <a-descriptions-item label="浏览">{{ currentDocument.view_count }}次</a-descriptions-item>
                </a-descriptions>
              </div>

              <!-- 编辑表单 -->
              <div v-if="isEditing" class="edit-form">
                <a-form :model="editForm" layout="inline" size="small">
                  <a-form-item label="类型">
                    <a-select v-model="editForm.type" style="width: 120px">
                      <a-option v-for="item in documentTypeOptions" :key="item.value" :value="item.value">
                        {{ item.label }}
                      </a-option>
                    </a-select>
                  </a-form-item>
                  <a-form-item label="分类">
                    <a-select
                      v-model="editForm.category_id"
                      placeholder="选择分类"
                      allow-clear
                      style="width: 150px"
                    >
                      <a-option v-for="item in categoryOptions" :key="item.value" :value="item.value">
                        {{ item.label }}
                      </a-option>
                    </a-select>
                  </a-form-item>
                </a-form>
              </div>

              <!-- Markdown编辑/预览区域 -->
              <div class="markdown-area" :class="isEditing ? editorMode : 'preview'">
                <!-- 编辑区（仅在编辑状态时显示） -->
                <div v-show="isEditing && (editorMode === 'edit' || editorMode === 'split')" class="editor-pane">
                  <!-- 工具栏 -->
                  <div class="md-toolbar">
                    <a-space>
                      <a-tooltip content="加粗 (Ctrl+B)">
                        <a-button size="mini" @click="insertFormat('bold')">
                          <template #icon><icon-bold /></template>
                        </a-button>
                      </a-tooltip>
                      <a-tooltip content="斜体 (Ctrl+I)">
                        <a-button size="mini" @click="insertFormat('italic')">
                          <template #icon><icon-italic /></template>
                        </a-button>
                      </a-tooltip>
                      <a-divider direction="vertical" />
                      <a-tooltip content="标题">
                        <a-dropdown @select="insertHeading">
                          <a-button size="mini">
                            <template #icon><icon-edit /></template>
                          </a-button>
                          <template #content>
                            <a-doption value="h1">一级标题</a-doption>
                            <a-doption value="h2">二级标题</a-doption>
                            <a-doption value="h3">三级标题</a-doption>
                          </template>
                        </a-dropdown>
                      </a-tooltip>
                      <a-tooltip content="代码块">
                        <a-button size="mini" @click="insertFormat('code')">
                          <template #icon><icon-code /></template>
                        </a-button>
                      </a-tooltip>
                      <a-tooltip content="链接">
                        <a-button size="mini" @click="insertFormat('link')">
                          <template #icon><icon-link /></template>
                        </a-button>
                      </a-tooltip>
                      <a-tooltip content="列表">
                        <a-button size="mini" @click="insertFormat('list')">
                          <template #icon><icon-list /></template>
                        </a-button>
                      </a-tooltip>
                    </a-space>
                  </div>
                  <!-- 文本编辑区 -->
                  <a-textarea
                    ref="editorRef"
                    v-model="editContent"
                    :auto-size="{ minRows: 20, maxRows: 40 }"
                    placeholder="请输入文档内容，支持Markdown格式..."
                    class="md-editor"
                  />
                </div>
                <!-- 预览区（非编辑状态始终显示，编辑状态根据模式显示） -->
                <div v-show="!isEditing || editorMode === 'preview' || editorMode === 'split'" class="preview-pane">
                  <div class="md-preview" v-html="renderedContent"></div>
                </div>
              </div>
            </template>
            <a-empty v-else description="请从左侧选择文档或新建文档" />
          </div>
        </a-card>
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <a-modal
      v-model:visible="deleteConfirmVisible"
      title="删除确认"
      @ok="handleConfirmDelete"
      @cancel="deleteConfirmVisible = false"
    >
      <p>确定要删除文档「{{ currentDocument?.title }}」吗？</p>
      <p style="color: rgb(var(--warning-6))">删除后文档将移入回收站。</p>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue'
import { Message } from '@arco-design/web-vue'
import {
  IconPlus,
  IconRefresh,
  IconFile,
  IconBold,
  IconItalic,
  IconCode,
  IconLink,
  IconList,
  IconDownload,
  IconStar,
  IconStarFill,
  IconEdit,
} from '@arco-design/web-vue/es/icon'
import dayjs from 'dayjs'
import type { Document, DocumentStatus, DocumentType, FetchDocumentListParams } from '@/api/kb/document'
import {
  fetchMyDocumentList,
  fetchApprovedDocumentList,
  fetchDocumentDetail,
  createDocument,
  updateDocument,
  publishDocument,
  moveToTrash,
  favoriteDocument,
  unfavoriteDocument,
} from '@/api/kb/document'
import { fetchCategoryList } from '@/api/kb/category'
import { documentTypeOptions } from './config/options'

// 当前标签页
const activeTab = ref<'mine' | 'all'>('mine')

// 搜索
const searchKeyword = ref('')

// 文档列表
const documentList = ref<Document[]>([])
const resourceTypeMap = ref<Record<number, string>>({}) // 保存 id -> resource_type 的映射
const loading = ref(false)
const page = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 当前选中的文档
const currentDocument = ref<Document | null>(null)
const currentResourceType = ref<string>('document') // 外层类型：document 或 faq
const isFavorited = ref(false)

// 编辑状态
const isEditing = ref(false)
const saving = ref(false)
const editForm = reactive({
  title: '',
  type: 'common' as DocumentType,
  category_id: undefined as number | undefined,
  description: '',
})
const editContent = ref('')
const editorRef = ref()

// 编辑器模式
const editorMode = ref<'edit' | 'preview' | 'split'>('split')

// 分类选项
const categoryOptions = ref<{ label: string; value: number }[]>([])

// 删除确认
const deleteConfirmVisible = ref(false)

// 渲染Markdown内容
const renderedContent = computed(() => {
  const content = isEditing.value ? editContent.value : currentDocument.value?.content
  if (!content) return ''
  
  let html = content
  // 标题
  html = html.replace(/^### (.*$)/gim, '<h3>$1</h3>')
  html = html.replace(/^## (.*$)/gim, '<h2>$1</h2>')
  html = html.replace(/^# (.*$)/gim, '<h1>$1</h1>')
  // 粗体
  html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
  // 斜体
  html = html.replace(/\*(.*?)\*/g, '<em>$1</em>')
  // 代码块
  html = html.replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>')
  // 行内代码
  html = html.replace(/`(.*?)`/g, '<code>$1</code>')
  // 链接
  html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank">$1</a>')
  // 列表
  html = html.replace(/^\- (.*$)/gim, '<li>$1</li>')
  html = html.replace(/^\d+\. (.*$)/gim, '<li>$1</li>')
  // 段落
  html = html.replace(/\n\n/g, '</p><p>')
  html = `<p>${html}</p>`
  return html
})

// 获取文档列表
const fetchData = async () => {
  try {
    loading.value = true
    const params: FetchDocumentListParams = {
      page: page.value,
      page_size: pageSize.value,
      keyword: searchKeyword.value || undefined,
    }
    
    console.log('fetchData params:', params, 'activeTab:', activeTab.value)
    
    const res: any = activeTab.value === 'mine'
      ? await fetchMyDocumentList(params)
      : await fetchApprovedDocumentList(params)
    
    console.log('fetchData response:', res)
    
    // 兼容多种API响应格式
    if (res?.code === 0) {
      let rawData: any[] = []
      
      // 格式1: res.details.data
      if (res.details?.data) {
        rawData = res.details.data || []
        total.value = res.details.total || 0
      }
      // 格式2: res.data.data
      else if (res.data?.data) {
        rawData = res.data.data || []
        total.value = res.data.total || 0
      }
      // 格式3: res.data 是数组
      else if (Array.isArray(res.data)) {
        rawData = res.data
        total.value = res.data.length
      }
      // 格式4: res.details 是数组
      else if (Array.isArray(res.details)) {
        rawData = res.details
        total.value = res.details.length
      }
      
      // 处理数据：提取 resource 字段（document 和 faq 都作为文档处理）
      // 同时保存每个文档对应的 resource_type
      documentList.value = rawData.map((item: any) => {
        // 保存 id -> resource_type 的映射
        if (item.resource?.id && item.type) {
          resourceTypeMap.value[item.resource.id] = item.type
        }
        return item.resource
      })
    } else {
      documentList.value = []
      total.value = 0
    }
    
    console.log('documentList:', documentList.value, 'total:', total.value)
  } catch (error) {
    console.error('获取文档列表失败:', error)
    documentList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 加载分类
const loadCategories = async () => {
  try {
    const res: any = await fetchCategoryList({ type: 'document' })
    // 兼容多种API响应格式
    let categoryList: any[] = []
    if (res?.code === 0 && Array.isArray(res.details)) {
      categoryList = res.details
    }
    categoryOptions.value = categoryList.map((item: any) => ({
      label: item.name,
      value: item.id,
    }))
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

// 标签页切换
const handleTabChange = () => {
  page.value = 1
  currentDocument.value = null
  isEditing.value = false
  fetchData()
}

// 搜索
const handleSearch = () => {
  page.value = 1
  fetchData()
}

// 分页
const handlePageChange = (current: number) => {
  page.value = current
  fetchData()
}

// 选择文档
const handleSelectDocument = async (doc: Document) => {
  if (isEditing.value) {
    // 如果正在编辑，提示保存
    Message.warning('请先保存或取消当前编辑')
    return
  }

  try {
    loading.value = true
    const res: any = await fetchDocumentDetail(doc.id)
    if (res?.code === 0 && res.details) {
      // 兼容两种响应格式：直接返回文档对象 或 { type, resource } 格式
      const docData = res.details.resource || res.details
      currentDocument.value = docData

      // 从文档详情中获取收藏状态
      isFavorited.value = docData.is_favorited || false

      // 获取 resource_type：优先从列表映射中获取（因为详情接口可能不返回外层 type）
      if (resourceTypeMap.value[doc.id]) {
        currentResourceType.value = resourceTypeMap.value[doc.id]
      } else if (res.details.type) {
        // 备用：从详情响应中获取（注意：这可能是内层 type，如 common/guide）
        currentResourceType.value = res.details.type
      }
    }
  } catch (error) {
    console.error('获取文档详情失败:', error)
    Message.error('获取文档详情失败')
  } finally {
    loading.value = false
  }
}

// 新建文档
const handleCreate = () => {
  currentDocument.value = null
  currentResourceType.value = 'document' // 新建时默认为 document
  isFavorited.value = false
  editForm.title = ''
  editForm.type = 'common'
  editForm.category_id = undefined
  editForm.description = ''
  editContent.value = ''
  isEditing.value = true
  editorMode.value = 'edit'
  loadCategories()
}

// 开始编辑
const handleStartEdit = () => {
  if (!currentDocument.value) return
  
  editForm.title = currentDocument.value.title
  editForm.type = currentDocument.value.type
  editForm.category_id = currentDocument.value.category_id
  editForm.description = currentDocument.value.description || ''
  editContent.value = currentDocument.value.content
  isEditing.value = true
  loadCategories()
}

// 取消编辑
const handleCancelEdit = () => {
  isEditing.value = false
  if (currentDocument.value) {
    // 恢复原始内容
    editContent.value = currentDocument.value.content
  }
}

// 保存文档
const handleSave = async () => {
  if (!editForm.title.trim()) {
    Message.warning('请输入文档标题')
    return
  }
  if (!editContent.value.trim()) {
    Message.warning('请输入文档内容')
    return
  }
  
  try {
    saving.value = true
    const data = {
      title: editForm.title,
      type: editForm.type,
      category_id: editForm.category_id,
      description: editForm.description,
      content: editContent.value,
    }
    
    if (currentDocument.value?.id) {
      // 更新
      await updateDocument({ ...data, id: currentDocument.value.id })
      Message.success('更新成功')
    } else {
      // 新建
      await createDocument(data)
      Message.success('创建成功')
    }
    
    isEditing.value = false
    await fetchData()
    
    // 重新加载当前文档
    if (currentDocument.value?.id) {
      const res: any = await fetchDocumentDetail(currentDocument.value.id)
      if (res?.code === 0) {
        currentDocument.value = res.details
      }
    }
  } catch (error) {
    console.error('保存失败:', error)
    Message.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 发布文档
const handlePublish = async () => {
  if (!currentDocument.value) return
  
  try {
    await publishDocument(currentDocument.value.id)
    Message.success('发布成功，等待审核')
    await fetchData()
    // 重新加载当前文档
    const res: any = await fetchDocumentDetail(currentDocument.value.id)
    if (res?.code === 0) {
      currentDocument.value = res.details
    }
  } catch (error) {
    console.error('发布失败:', error)
    Message.error('发布失败')
  }
}

// 切换收藏
const handleToggleFavorite = async () => {
  if (!currentDocument.value) return
  
  try {
    if (isFavorited.value) {
      await unfavoriteDocument(currentDocument.value.id)
      Message.success('已取消收藏')
    } else {
      await favoriteDocument(currentDocument.value.id)
      Message.success('收藏成功')
    }
    isFavorited.value = !isFavorited.value
  } catch (error) {
    console.error('操作失败:', error)
    Message.error('操作失败')
  }
}

// 下载文档
const handleDownload = () => {
  if (!currentDocument.value) return
  
  const content = `# ${currentDocument.value.title}\n\n` +
    `文档编号: ${currentDocument.value.doc_no}\n` +
    `作者: ${currentDocument.value.author_name}\n` +
    `创建时间: ${formatTime(currentDocument.value.created_at)}\n\n` +
    `## 描述\n\n${currentDocument.value.description || '无'}\n\n` +
    `## 内容\n\n${currentDocument.value.content}`
  
  const blob = new Blob([content], { type: 'text/markdown;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const link = window.document.createElement('a')
  link.href = url
  link.download = `${currentDocument.value.title}.md`
  window.document.body.appendChild(link)
  link.click()
  window.document.body.removeChild(link)
  URL.revokeObjectURL(url)
  
  Message.success('下载成功')
}

// 删除文档
const handleDelete = () => {
  deleteConfirmVisible.value = true
}

// 确认删除
const handleConfirmDelete = async () => {
  if (!currentDocument.value?.id) return

  try {
    await moveToTrash(currentDocument.value.id, currentResourceType.value)
    Message.success('删除成功，已移入回收站')
    deleteConfirmVisible.value = false
    currentDocument.value = null
    await fetchData()
  } catch (error) {
    console.error('删除失败:', error)
    Message.error('删除失败')
  }
}

// 插入格式
const insertFormat = (type: string) => {
  const textarea = editorRef.value?.$el?.querySelector('textarea')
  if (!textarea) return
  
  const start = textarea.selectionStart
  const end = textarea.selectionEnd
  const selectedText = editContent.value.substring(start, end)
  let newText = ''
  
  switch (type) {
    case 'bold':
      newText = `**${selectedText || '粗体文本'}**`
      break
    case 'italic':
      newText = `*${selectedText || '斜体文本'}*`
      break
    case 'code':
      newText = selectedText.includes('\n')
        ? `\`\`\`\n${selectedText || '代码块'}\n\`\`\``
        : `\`${selectedText || '代码'}\``
      break
    case 'link':
      newText = `[${selectedText || '链接文本'}](url)`
      break
    case 'list':
      newText = `\n- ${selectedText || '列表项'}`
      break
    default:
      newText = selectedText
  }
  
  editContent.value =
    editContent.value.substring(0, start) +
    newText +
    editContent.value.substring(end)
  
  nextTick(() => {
    textarea.focus()
    const newCursorPos = start + newText.length
    textarea.setSelectionRange(newCursorPos, newCursorPos)
  })
}

// 插入标题
const insertHeading = (level: string | number) => {
  const textarea = editorRef.value?.$el?.querySelector('textarea')
  if (!textarea) return
  
  const start = textarea.selectionStart
  const prefix = level === 'h1' ? '# ' : level === 'h2' ? '## ' : '### '
  const selectedText = editContent.value.substring(start, textarea.selectionEnd)
  
  editContent.value =
    editContent.value.substring(0, start) +
    prefix +
    (selectedText || '标题') +
    editContent.value.substring(textarea.selectionEnd)
}

// 格式化函数
const formatTime = (time: string | null): string => {
  return time ? dayjs(time).format('YYYY-MM-DD HH:mm') : '-'
}

const formatDate = (time: string | null): string => {
  return time ? dayjs(time).format('MM-DD HH:mm') : '-'
}

const getStatusText = (status: DocumentStatus): string => {
  const map: Record<DocumentStatus, string> = {
    draft: '草稿',
    published: '已发布',
    reviewed: '已审核',
    rejected: '未通过',
  }
  return map[status] || status
}

const getStatusColor = (status: DocumentStatus): string => {
  const map: Record<DocumentStatus, string> = {
    draft: 'gray',
    published: 'blue',
    reviewed: 'green',
    rejected: 'red',
  }
  return map[status] || 'gray'
}

const getTypeText = (type: DocumentType): string => {
  const map: Record<DocumentType, string> = {
    common: '通用',
    guide: '指南',
    solution: '方案',
    troubleshoot: '排查',
    process: '流程',
    technical: '技术',
  }
  return map[type] || type
}

const getTypeColor = (type: DocumentType): string => {
  const map: Record<DocumentType, string> = {
    common: 'gray',
    guide: 'blue',
    solution: 'green',
    troubleshoot: 'orange',
    process: 'purple',
    technical: 'cyan',
  }
  return map[type] || 'gray'
}

// 初始化
onMounted(() => {
  fetchData()
})
</script>

<script lang="ts">
export default {
  name: 'KbItems',
}
</script>

<style scoped lang="less">
.kb-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 0 20px 20px;
}

.kb-content {
  flex: 1;
  display: flex;
  gap: 16px;
  min-height: 0;
  margin-top: 16px;
}

.kb-left-panel {
  width: 320px;
  flex-shrink: 0;
  
  .general-card {
    height: 100%;
    display: flex;
    flex-direction: column;
    
    :deep(.arco-card-body) {
      flex: 1;
      display: flex;
      flex-direction: column;
      min-height: 0;
      overflow: hidden;
    }
  }
  
  .list-toolbar {
    display: flex;
    justify-content: space-between;
    margin-top: 12px;
    margin-bottom: 12px;
    flex-shrink: 0;
  }
  
  .document-list {
    flex: 1;
    overflow-y: auto;
    min-height: 100px;
  }
  
  .document-item {
    padding: 10px 12px;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.2s;
    margin-bottom: 4px;
    
    &:hover {
      background-color: var(--color-fill-2);
    }
    
    &.active {
      background-color: rgb(var(--primary-1));
      border-left: 3px solid rgb(var(--primary-6));
    }
    
    .doc-title {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 6px;
      
      .doc-icon {
        color: var(--color-text-3);
        flex-shrink: 0;
      }
      
      .title-text {
        font-weight: 500;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
    
    .doc-meta {
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      .doc-time {
        font-size: 12px;
        color: var(--color-text-3);
      }
    }
  }
  
  .list-pagination {
    margin-top: 12px;
    display: flex;
    justify-content: center;
    flex-shrink: 0;
    padding-top: 8px;
  }
}

.kb-right-panel {
  flex: 1;
  min-width: 0;
  
  .editor-card {
    height: 100%;
    display: flex;
    flex-direction: column;
    
    :deep(.arco-card-body) {
      flex: 1;
      display: flex;
      flex-direction: column;
      padding: 12px;
      min-height: 0;
    }
  }
  
  .editor-header {
    max-width: 80%;
    .title-input {
      font-size: 16px;
      font-weight: 600;
    }
    
    .title-text {
      font-size: 16px;
      font-weight: 600;
    }
  }
  
  .editor-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
  }
  
  .doc-info {
    margin-bottom: 12px;
    padding-bottom: 12px;
    border-bottom: 1px solid var(--color-border);
  }
  
  .edit-form {
    margin-bottom: 12px;
    padding-bottom: 12px;
    border-bottom: 1px solid var(--color-border);
  }
  
  .markdown-area {
    flex: 1;
    display: flex;
    gap: 12px;
    min-height: 0;
    
    &.edit .editor-pane {
      flex: 1;
    }
    
    &.preview .preview-pane {
      flex: 1;
    }
    
    &.split {
      .editor-pane,
      .preview-pane {
        flex: 1;
      }
    }
  }
  
  .editor-pane {
    display: flex;
    flex-direction: column;
    min-width: 0;
    
    .md-toolbar {
      padding: 8px;
      background-color: var(--color-fill-1);
      border: 1px solid var(--color-border);
      border-bottom: none;
      border-radius: 4px 4px 0 0;
    }
    
    .md-editor {
      flex: 1;
      border-radius: 0 0 4px 4px;
      font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
      font-size: 14px;
      line-height: 1.6;
    }
  }
  
  .preview-pane {
    min-width: 0;
    overflow: auto;
    border: 1px solid var(--color-border);
    border-radius: 4px;
    
    .md-preview {
      padding: 16px;
      line-height: 1.8;
      color: var(--color-text-1);
      
      :deep(h1) {
        font-size: 24px;
        font-weight: 600;
        margin: 16px 0;
        padding-bottom: 8px;
        border-bottom: 1px solid var(--color-border);
      }
      
      :deep(h2) {
        font-size: 20px;
        font-weight: 600;
        margin: 14px 0;
      }
      
      :deep(h3) {
        font-size: 16px;
        font-weight: 600;
        margin: 12px 0;
      }
      
      :deep(p) {
        margin: 8px 0;
      }
      
      :deep(code) {
        background-color: var(--color-fill-3);
        padding: 2px 6px;
        border-radius: 4px;
        font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
        font-size: 13px;
      }
      
      :deep(pre) {
        background-color: var(--color-fill-2);
        padding: 12px;
        border-radius: 4px;
        overflow-x: auto;
        
        code {
          background: none;
          padding: 0;
        }
      }
      
      :deep(a) {
        color: rgb(var(--primary-6));
        text-decoration: none;
        
        &:hover {
          text-decoration: underline;
        }
      }
      
      :deep(li) {
        margin: 4px 0;
        margin-left: 20px;
      }
      
      :deep(blockquote) {
        margin: 8px 0;
        padding: 8px 16px;
        border-left: 4px solid rgb(var(--primary-6));
        background-color: var(--color-fill-1);
        color: var(--color-text-2);
      }
    }
  }
}
</style>