<template>
  <aside class="docs-panel">
    <!-- 头部 -->
    <header class="docs-header">
      <h1 class="docs-header-title">
        <IconLibrary name="folder" :size="20" />
        <span>文稿管理</span>
      </h1>
      <span class="badge badge-primary">Pro版</span>
    </header>

    <!-- 工具栏 -->
    <div class="docs-toolbar">
      <div class="flex gap-2">
        <button
          v-for="filter in statusFilters"
          :key="filter.value"
          @click="currentFilter = filter.value"
          :class="['filter-btn', { 'active': currentFilter === filter.value }]"
        >
          {{ filter.label }} ({{ getCountByStatus(filter.value) }})
        </button>
      </div>
      <button
        @click="createNewDocument"
        class="create-btn"
      >
        + 新建文稿
      </button>
    </div>

    <!-- 文稿列表 -->
    <div class="docs-list">
      <div v-if="filteredDocuments.length === 0" class="text-center text-muted py-8">
        <div class="w-16 h-16 flex items-center justify-center rounded-xl bg-slate-800/50 border border-slate-700 mx-auto mb-3 opacity-40">
          <IconLibrary name="document" :size="32" />
        </div>
        <p class="text-sm">暂无文稿</p>
      </div>

      <div
        v-for="doc in filteredDocuments"
        :key="doc.id"
        @click="selectDocument(doc)"
        :class="['doc-card', { 'selected': selectedDocId === doc.id }]"
      >
        <div class="flex items-start justify-between mb-2">
          <h3 class="font-medium text-primary text-sm truncate flex-1">{{ doc.title }}</h3>
          <span :class="['status-badge', statusStyles[doc.status]]">
            {{ statusLabels[doc.status] }}
          </span>
        </div>
        <p class="text-xs text-muted line-clamp-2 mb-2">
          {{ doc.content ? doc.content.substring(0, 100) + '...' : '空白文稿' }}
        </p>
        <div class="flex items-center justify-between text-xs text-muted">
          <span>{{ doc.word_count || 0 }} 字</span>
          <span>{{ formatDate(doc.updated_at) }}</span>
        </div>
      </div>
    </div>

    <!-- 底部操作区 -->
    <div v-if="selectedDocId" class="docs-footer">
      <div class="flex gap-2">
        <button
          @click="openDocument"
          class="action-btn primary flex items-center justify-center gap-1.5"
        >
          <IconLibrary name="edit" :size="14" />
          <span>编辑</span>
        </button>
        <button
          @click="duplicateDocument"
          class="action-btn secondary flex items-center justify-center gap-1.5"
        >
          <IconLibrary name="copy" :size="14" />
          <span>复制</span>
        </button>
        <button
          @click="toggleVersionPanel"
          class="action-btn success flex items-center justify-center gap-1.5"
        >
          <IconLibrary name="history" :size="14" />
          <span>版本</span>
        </button>
        <button
          @click="confirmDelete"
          class="action-btn danger flex items-center justify-center"
          aria-label="删除文稿"
        >
          <IconLibrary name="trash" :size="16" />
        </button>
      </div>
    </div>

    <!-- 删除确认弹窗 -->
    <div v-if="showDeleteConfirm" class="confirm-modal-backdrop">
      <div class="confirm-modal">
        <h3 class="confirm-modal-title">确认删除</h3>
        <p class="confirm-modal-text">确定要删除这篇文稿吗？此操作不可恢复。</p>
        <div class="confirm-modal-actions">
          <button
            @click="showDeleteConfirm = false"
            class="action-btn secondary"
          >
            取消
          </button>
          <button
            @click="deleteSelectedDocument"
            class="action-btn danger"
          >
            删除
          </button>
        </div>
      </div>
    </div>
  </aside>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useAppStore } from '../stores/app'
import { useDatabaseStore } from '../stores/database.js'
import { storeToRefs } from 'pinia'
import IconLibrary from './icons/IconLibrary.vue'

const appStore = useAppStore()
const dbStore = useDatabaseStore()

// 定义事件
const emit = defineEmits(['toggle-version-panel', 'document-selected'])

// 状态
const selectedDocId = ref(null)
const currentFilter = ref('all')
const showDeleteConfirm = ref(false)

// 文稿数据
const documents = ref([])

// 状态筛选选项
const statusFilters = [
  { label: '全部', value: 'all' },
  { label: '草稿', value: 'draft' },
  { label: '已发布', value: 'published' },
  { label: '已归档', value: 'archived' }
]

// 状态标签
const statusLabels = {
  draft: '草稿',
  published: '已发布',
  archived: '已归档'
}

// 状态样式
const statusStyles = {
  draft: 'draft',
  published: 'published',
  archived: 'archived'
}

// 筛选后的文稿
const filteredDocuments = computed(() => {
  if (currentFilter.value === 'all') {
    return documents.value
  }
  return documents.value.filter(doc => doc.status === currentFilter.value)
})

// 按状态统计数量
const getCountByStatus = (status) => {
  if (status === 'all') return documents.value.length
  return documents.value.filter(doc => doc.status === status).length
}

// 加载文稿列表
const loadDocuments = async () => {
  try {
    const { getAllDocuments } = await import('../db/index.js')
    documents.value = getAllDocuments()
  } catch (error) {
    console.error('加载文稿失败:', error)
  }
}

// 选择文稿
const selectDocument = (doc) => {
  selectedDocId.value = selectedDocId.value === doc.id ? null : doc.id
  // 通知父组件
  const selectedDoc = selectedDocId.value ? doc : null
  emit('document-selected', selectedDoc)
  
  // 同步更新 store 以便右侧编辑区同步显示
  if (selectedDoc) {
    appStore.currentDocument = selectedDoc
  }
}

// 切换版本面板
const toggleVersionPanel = () => {
  emit('toggle-version-panel')
}

// 创建新文稿
const createNewDocument = async () => {
  try {
    const { createDocument } = await import('../db/index.js')
    const id = createDocument({
      title: '未命名文稿',
      content: '',
      status: 'draft'
    })
    await loadDocuments()
    selectedDocId.value = id
  } catch (error) {
    console.error('创建文稿失败:', error)
  }
}

// 打开编辑
const openDocument = () => {
  if (!selectedDocId.value) return
  const doc = documents.value.find(d => d.id === selectedDocId.value)
  if (doc) {
    // 设置当前文稿到 store，让 MainContent 可以读取
    appStore.currentDocument = doc
  }
}

// 复制文稿
const duplicateDocument = async () => {
  if (!selectedDocId.value) return
  const doc = documents.value.find(d => d.id === selectedDocId.value)
  if (!doc) return
  
  try {
    const { createDocument } = await import('../db/index.js')
    createDocument({
      title: doc.title + ' (副本)',
      content: doc.content,
      paradigmId: doc.paradigm_id,
      status: 'draft',
      tags: doc.tags
    })
    await loadDocuments()
  } catch (error) {
    console.error('复制文稿失败:', error)
  }
}

// 确认删除
const confirmDelete = () => {
  if (!selectedDocId.value) return
  showDeleteConfirm.value = true
}

// 删除文稿
const deleteSelectedDocument = async () => {
  if (!selectedDocId.value) return
  
  try {
    const { deleteDocument } = await import('../db/index.js')
    deleteDocument(selectedDocId.value)
    selectedDocId.value = null
    showDeleteConfirm.value = false
    await loadDocuments()
  } catch (error) {
    console.error('删除文稿失败:', error)
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })
}

// 切换页面
const switchPage = (page) => {
  appStore.setCurrentPage(page)
}

onMounted(() => {
  loadDocuments()
})
</script>

<style scoped>
/* ========== 使用设计令牌系统 ========== */

/* 侧边栏容器 */
.docs-panel {
  width: 400px;
  height: 100vh;
  display: flex;
  flex-direction: column;
  border-right: 1px solid var(--border-default);
  background: var(--bg-secondary);
  flex-shrink: 0;
}

/* 头部 */
.docs-header {
  padding: var(--space-4);
  border-bottom: 1px solid var(--border-default);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.docs-header-title {
  font-weight: var(--font-semibold);
  font-size: var(--text-lg);
  color: var(--text-primary);
  display: flex;
  align-items: center;
  gap: var(--space-2);
}

/* 工具栏 */
.docs-toolbar {
  padding: var(--space-4);
  border-bottom: 1px solid var(--border-default);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* 筛选按钮 */
.filter-btn {
  font-size: var(--text-xs);
  padding: var(--space-2) var(--space-3);
  border-radius: var(--radius-md);
  transition: all var(--transition-fast);
}

.filter-btn.active {
  background: var(--accent-primary);
  color: var(--text-inverse);
}

.filter-btn:not(.active) {
  background: var(--bg-elevated);
  color: var(--text-secondary);
}

.filter-btn:not(.active):hover {
  background: var(--bg-sunken);
  color: var(--text-primary);
}

/* 文稿列表 */
.docs-list {
  flex: 1;
  overflow-y: auto;
  padding: var(--space-4);
}

/* 文稿卡片 */
.doc-card {
  padding: var(--space-3);
  border-radius: var(--radius-lg);
  border: 1px solid var(--border-default);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.doc-card.selected {
  background: var(--info-bg);
  border-color: var(--accent-primary);
}

.doc-card:not(.selected) {
  background: var(--bg-primary);
}

.doc-card:not(.selected):hover {
  border-color: var(--border-strong);
}

/* 状态徽章 */
.status-badge {
  font-size: var(--text-xs);
  padding: 2px 6px;
  border-radius: var(--radius-sm);
}

.status-badge.draft {
  background: var(--warning-bg);
  color: var(--accent-warning);
}

.status-badge.published {
  background: var(--success-bg);
  color: var(--accent-success);
}

.status-badge.archived {
  background: var(--bg-elevated);
  color: var(--text-secondary);
}

/* 底部操作区 */
.docs-footer {
  padding: var(--space-4);
  border-top: 1px solid var(--border-default);
}

/* 操作按钮 */
.action-btn {
  flex: 1;
  font-size: var(--text-xs);
  padding: var(--space-2);
  border-radius: var(--radius-md);
  transition: all var(--transition-fast);
}

.action-btn.primary {
  background: var(--accent-primary);
  color: var(--text-inverse);
}

.action-btn.primary:hover {
  background: var(--accent-primary-hover);
}

.action-btn.secondary {
  background: var(--bg-elevated);
  color: var(--text-primary);
}

.action-btn.secondary:hover {
  background: var(--bg-sunken);
}

.action-btn.danger {
  background: var(--danger-bg);
  color: var(--accent-danger);
}

.action-btn.danger:hover {
  background: rgba(248, 113, 113, 0.2);
}

.action-btn.success {
  background: var(--accent-success);
  color: var(--text-inverse);
}

.action-btn.success:hover {
  opacity: 0.9;
}

/* 新建按钮 */
.create-btn {
  font-size: var(--text-xs);
  padding: var(--space-2) var(--space-3);
  border-radius: var(--radius-md);
  background: var(--accent-success);
  color: var(--text-inverse);
  transition: all var(--transition-fast);
}

.create-btn:hover {
  background: #22c55e;
}

/* 确认弹窗 */
.confirm-modal-backdrop {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: var(--z-modal-backdrop);
}

.confirm-modal {
  background: var(--bg-secondary);
  border-radius: var(--radius-lg);
  padding: var(--space-6);
  width: 320px;
  border: 1px solid var(--border-default);
}

.confirm-modal-title {
  font-size: var(--text-lg);
  font-weight: var(--font-semibold);
  color: var(--text-primary);
  margin-bottom: var(--space-4);
}

.confirm-modal-text {
  font-size: var(--text-sm);
  color: var(--text-secondary);
  margin-bottom: var(--space-6);
}

.confirm-modal-actions {
  display: flex;
  gap: var(--space-3);
}
</style>
