<template>
  <aside class="outline-writer-panel">
    <!-- 头部 -->
    <header class="panel-header">
      <h1 class="panel-title">
        <IconLibrary name="folder" :size="20" />
        <span>提纲写作</span>
      </h1>
      <span class="badge badge-primary">新功能</span>
    </header>

    <!-- 内容区 -->
    <div class="panel-content">
      <!-- 1. 写作背景 -->
      <section class="panel-section">
        <label class="section-label">1. 写作背景（可选）</label>
        <textarea
          v-model="writingContext"
          class="context-textarea"
          placeholder="描述文章的整体目标、受众、风格要求..."
          rows="2"
        ></textarea>
      </section>

      <!-- 2. 素材库 -->
      <section class="panel-section">
        <div class="flex items-center justify-between mb-2">
          <label class="section-label">2. 素材库</label>
          <button 
            @click="addMaterial" 
            class="text-xs px-2 py-1 bg-purple-600 hover:bg-purple-500 text-white rounded"
          >
            + 添加素材
          </button>
        </div>
        
        <!-- 素材列表 -->
        <div v-if="materials.length > 0" class="materials-list">
          <div
            v-for="(mat, index) in materials"
            :key="mat.id"
            class="material-item"
          >
            <div class="material-info">
              <span class="material-icon">📄</span>
              <span class="material-name">{{ mat.name }}</span>
              <span class="material-size">({{ mat.content?.length || 0 }}字)</span>
            </div>
            <div class="material-actions">
              <button @click="editMaterial(mat)" class="text-blue-400 hover:text-blue-300 text-xs">编辑</button>
              <button @click="removeMaterial(index)" class="text-red-400 hover:text-red-300 text-xs">删除</button>
            </div>
          </div>
        </div>
        <p v-else class="text-xs text-slate-500 italic">暂无素材，点击"添加素材"导入参考资料</p>
        
        <!-- 上下文统计 -->
        <div v-if="materials.length > 0" class="context-stats">
          <div class="stats-row">
            <span>素材总字数：</span>
            <span :class="{ 'text-yellow-400': totalMaterialChars > 20000, 'text-red-400': totalMaterialChars > 40000 }">
              {{ totalMaterialChars.toLocaleString() }} 字
            </span>
            <span class="text-slate-500">≈ {{ estimatedTokens.toLocaleString() }} tokens</span>
          </div>
          <div v-if="totalMaterialChars > 20000" class="warning-box">
            <span v-if="totalMaterialChars > 40000" class="text-red-400">
              ⚠️ 素材过长，可能超出模型上下文限制，建议精简
            </span>
            <span v-else class="text-yellow-400">
              ⚡ 素材较长，生成时将自动截断
            </span>
          </div>
        </div>
      </section>

      <!-- 素材编辑弹窗 -->
      <div v-if="showMaterialModal" class="material-modal-overlay" @click.self="closeMaterialModal">
        <div class="material-modal">
          <div class="modal-header">
            <h3>{{ editingMaterial?.id ? '编辑素材' : '添加素材' }}</h3>
            <button @click="closeMaterialModal" class="text-slate-400 hover:text-white">×</button>
          </div>
          <div class="modal-body">
            <input
              v-model="editingMaterial.name"
              class="modal-input"
              placeholder="素材名称（如：政策文件、去年材料）"
            />
            <textarea
              v-model="editingMaterial.content"
              class="modal-textarea"
              placeholder="粘贴素材内容..."
              rows="12"
            ></textarea>
          </div>
          <div class="modal-footer">
            <button @click="closeMaterialModal" class="modal-btn secondary">取消</button>
            <button @click="saveMaterial" class="modal-btn primary">保存</button>
          </div>
        </div>
      </div>

      <!-- 3. 大纲输入 -->
      <section class="panel-section">
        <div class="flex items-center justify-between mb-2">
          <label class="section-label">3. 输入大纲</label>
          <div class="flex items-center gap-2">
            <button 
              @click="parseOutline" 
              class="text-xs px-2 py-1 bg-blue-600 hover:bg-blue-500 text-white rounded"
              :disabled="!rawOutline.trim()"
            >
              解析大纲
            </button>
          </div>
        </div>
        <textarea
          v-model="rawOutline"
          class="outline-textarea"
          placeholder="支持多种格式，例如：

一、引言
    1.1 背景介绍
    1.2 问题提出
二、主体论述
    2.1 论点一
    2.2 论点二
三、结论

或使用 # 标记层级：
# 一级标题
## 二级标题"
          rows="8"
        ></textarea>
        <p class="text-xs text-slate-500 mt-1">
          支持：一、二、... / 1. 1.1 / # ## / 缩进层级
        </p>
      </section>

      <!-- 3. 解析后的章节列表 -->
      <section v-if="parsedSections.length > 0" class="panel-section">
        <div class="flex items-center justify-between mb-2">
          <label class="section-label">3. 章节列表</label>
          <span class="text-xs text-slate-500">{{ flatSections.length }} 个章节</span>
        </div>
        
        <div class="sections-list">
          <div
            v-for="(section, index) in flatSections"
            :key="index"
            :class="['section-item', { 
              'active': currentSectionIndex === index,
              'generated': section.content
            }]"
            :style="{ paddingLeft: (section.level - 1) * 16 + 12 + 'px' }"
            @click="selectSection(index)"
          >
            <div class="section-header">
              <span class="level-badge" :class="'level-' + section.level">
                H{{ section.level }}
              </span>
              <span class="section-title">{{ section.title }}</span>
              <span v-if="section.content" class="status-dot generated"></span>
              <span v-else-if="section.isGenerating" class="status-dot generating"></span>
            </div>
            
            <!-- 展开的编辑区 -->
            <div v-if="currentSectionIndex === index" class="section-editor" @click.stop>
              <!-- 关联素材 -->
              <div v-if="materials.length > 0" class="linked-materials">
                <p class="text-xs text-slate-400 mb-1">📎 关联素材：</p>
                <div class="material-checkboxes">
                  <label 
                    v-for="mat in materials" 
                    :key="mat.id"
                    class="material-checkbox"
                  >
                    <input 
                      type="checkbox"
                      :checked="section.linkedMaterials?.includes(mat.id)"
                      @change="toggleSectionMaterial(section, mat.id)"
                    />
                    <span>{{ mat.name }}</span>
                  </label>
                </div>
              </div>
              
              <textarea
                v-model="section.hint"
                class="hint-textarea"
                placeholder="本节专属写作提示（可选）..."
                rows="2"
              ></textarea>
              <button
                @click="generateSection(index)"
                :disabled="section.isGenerating || isGenerating"
                class="generate-section-btn"
              >
                {{ section.isGenerating ? '生成中...' : (section.content ? '重新生成' : '生成本节') }}
              </button>
            </div>
          </div>
        </div>
      </section>
    </div>

    <!-- 底部操作区 -->
    <footer class="panel-footer">
      <button
        v-if="!isGenerating"
        @click="generateAll"
        :disabled="flatSections.length === 0"
        class="generate-all-btn"
      >
        一键生成全文
      </button>
      <button
        v-else
        @click="abortGeneration"
        class="abort-btn"
      >
        ⏹ 停止生成 ({{ currentSectionIndex + 1 }}/{{ flatSections.length }})
      </button>
    </footer>
  </aside>
</template>

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

const appStore = useAppStore()
const { outlineWriterState } = storeToRefs(appStore)

// Local refs synced to store
const rawOutline = computed({
  get: () => outlineWriterState.value.rawOutline,
  set: (v) => outlineWriterState.value.rawOutline = v
})
const writingContext = computed({
  get: () => outlineWriterState.value.writingContext,
  set: (v) => outlineWriterState.value.writingContext = v
})
const parsedSections = computed(() => outlineWriterState.value.parsedSections)
const currentSectionIndex = computed({
  get: () => outlineWriterState.value.currentSectionIndex,
  set: (v) => outlineWriterState.value.currentSectionIndex = v
})
const isGenerating = computed(() => outlineWriterState.value.isGenerating)

// 素材总字数和估算 tokens
const totalMaterialChars = computed(() => {
  return materials.value.reduce((sum, m) => sum + (m.content?.length || 0), 0)
})
const estimatedTokens = computed(() => {
  // 中文约 1.5 tokens/字
  return Math.round(totalMaterialChars.value * 1.5)
})

// 扁平化章节列表
const flatSections = computed(() => {
  const result = []
  const flatten = (sections) => {
    sections.forEach(s => {
      result.push(s)
      if (s.children && s.children.length > 0) {
        flatten(s.children)
      }
    })
  }
  flatten(parsedSections.value)
  return result
})

// 解析大纲
const parseOutline = () => {
  appStore.parseOutlineAction()
}

// 选择章节
const selectSection = (index) => {
  currentSectionIndex.value = currentSectionIndex.value === index ? -1 : index
}

// 生成单个章节
const generateSection = async (index) => {
  await appStore.generateOutlineSectionAction(index)
}

// 一键生成全文
const generateAll = async () => {
  await appStore.generateAllOutlineSectionsAction()
}

// 中断生成
const abortGeneration = () => {
  appStore.abortOutlineGenerationAction()
}

// ========== 素材管理 ==========
import { 
  getAllOutlineMaterials, 
  addOutlineMaterial, 
  updateOutlineMaterial, 
  deleteOutlineMaterial 
} from '../db/index.js'

const materials = computed(() => outlineWriterState.value.materials)
const showMaterialModal = computed({
  get: () => outlineWriterState.value.showMaterialModal,
  set: (v) => outlineWriterState.value.showMaterialModal = v
})
const editingMaterial = computed({
  get: () => outlineWriterState.value.editingMaterial,
  set: (v) => outlineWriterState.value.editingMaterial = v
})

// 加载素材（从数据库）
const loadMaterials = async () => {
  try {
    const dbMaterials = await getAllOutlineMaterials()
    outlineWriterState.value.materials = dbMaterials
    console.log('📦 从数据库加载素材:', dbMaterials.length, '条')
  } catch (e) {
    console.error('加载素材失败:', e)
  }
}

// 组件挂载时加载
import { onMounted } from 'vue'
onMounted(() => {
  loadMaterials()
})

// 添加新素材
const addMaterial = () => {
  editingMaterial.value = { id: '', name: '', content: '' }
  showMaterialModal.value = true
}

// 编辑素材
const editMaterial = (mat) => {
  editingMaterial.value = { ...mat }
  showMaterialModal.value = true
}

// 删除素材
const removeMaterial = async (index) => {
  const mat = materials.value[index]
  if (mat?.id) {
    await deleteOutlineMaterial(mat.id)
  }
  outlineWriterState.value.materials.splice(index, 1)
}

// 关闭弹窗
const closeMaterialModal = () => {
  showMaterialModal.value = false
  editingMaterial.value = null
}

// 保存素材
const saveMaterial = async () => {
  const mat = editingMaterial.value
  if (!mat.name.trim() || !mat.content.trim()) {
    alert('请填写素材名称和内容')
    return
  }
  
  if (mat.id) {
    // 更新已有素材
    await updateOutlineMaterial(mat.id, { name: mat.name, content: mat.content })
    const idx = materials.value.findIndex(m => m.id === mat.id)
    if (idx !== -1) {
      materials.value[idx] = { ...mat, word_count: mat.content.length }
    }
  } else {
    // 添加新素材
    const newId = await addOutlineMaterial({ name: mat.name, content: mat.content })
    mat.id = newId
    mat.word_count = mat.content.length
    materials.value.push(mat)
  }
  
  closeMaterialModal()
}

// 切换章节关联素材
const toggleSectionMaterial = (section, matId) => {
  if (!section.linkedMaterials) {
    section.linkedMaterials = []
  }
  const idx = section.linkedMaterials.indexOf(matId)
  if (idx !== -1) {
    section.linkedMaterials.splice(idx, 1)
  } else {
    section.linkedMaterials.push(matId)
  }
}
</script>

<style scoped>
.outline-writer-panel {
  width: 400px;
  height: 100vh;
  display: flex;
  flex-direction: column;
  border-right: 1px solid var(--border-default);
  background: var(--bg-secondary);
  flex-shrink: 0;
}

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

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

.panel-content {
  flex: 1;
  overflow-y: auto;
  padding: var(--space-4);
}

.panel-section {
  margin-bottom: var(--space-5);
}

.section-label {
  display: block;
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
  color: var(--text-secondary);
  margin-bottom: var(--space-2);
}

.context-textarea,
.outline-textarea {
  width: 100%;
  background: var(--bg-primary);
  border: 1px solid var(--border-default);
  border-radius: var(--radius-lg);
  padding: var(--space-3);
  font-size: var(--text-sm);
  color: var(--text-primary);
  font-family: monospace;
  resize: vertical;
}

.context-textarea:focus,
.outline-textarea:focus {
  outline: none;
  border-color: var(--accent-primary);
}

.sections-list {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid var(--border-default);
  border-radius: var(--radius-lg);
  background: var(--bg-primary);
}

.section-item {
  padding: var(--space-2) var(--space-3);
  border-bottom: 1px solid var(--border-default);
  cursor: pointer;
  transition: all 0.15s;
}

.section-item:last-child {
  border-bottom: none;
}

.section-item:hover {
  background: var(--bg-elevated);
}

.section-item.active {
  background: var(--bg-elevated);
  border-left: 2px solid var(--accent-primary);
}

.section-item.generated {
  background: rgba(34, 197, 94, 0.05);
}

.section-header {
  display: flex;
  align-items: center;
  gap: var(--space-2);
}

.level-badge {
  font-size: 10px;
  padding: 1px 4px;
  border-radius: var(--radius-sm);
  font-weight: bold;
}

.level-badge.level-1 {
  background: rgba(59, 130, 246, 0.2);
  color: #60a5fa;
}

.level-badge.level-2 {
  background: rgba(168, 85, 247, 0.2);
  color: #c084fc;
}

.level-badge.level-3 {
  background: rgba(34, 197, 94, 0.2);
  color: #4ade80;
}

.section-title {
  flex: 1;
  font-size: var(--text-sm);
  color: var(--text-primary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.status-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
}

.status-dot.generated {
  background: #22c55e;
}

.status-dot.generating {
  background: #f59e0b;
  animation: pulse 1s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

.section-editor {
  margin-top: var(--space-2);
  padding-top: var(--space-2);
  border-top: 1px dashed var(--border-default);
}

.hint-textarea {
  width: 100%;
  background: var(--bg-secondary);
  border: 1px solid var(--border-default);
  border-radius: var(--radius-md);
  padding: var(--space-2);
  font-size: var(--text-xs);
  color: var(--text-primary);
  resize: none;
  margin-bottom: var(--space-2);
}

.generate-section-btn {
  width: 100%;
  padding: var(--space-2);
  background: var(--accent-primary);
  color: white;
  border: none;
  border-radius: var(--radius-md);
  font-size: var(--text-xs);
  cursor: pointer;
  transition: all 0.15s;
}

.generate-section-btn:hover:not(:disabled) {
  background: var(--accent-primary-hover);
}

.generate-section-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.panel-footer {
  padding: var(--space-4);
  border-top: 1px solid var(--border-default);
  background: var(--bg-secondary);
}

.generate-all-btn {
  width: 100%;
  padding: var(--space-3);
  background: linear-gradient(135deg, var(--accent-primary), #6366f1);
  color: white;
  border: none;
  border-radius: var(--radius-lg);
  font-weight: var(--font-semibold);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--space-2);
  transition: all 0.2s;
}

.generate-all-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: var(--shadow-md);
}

.generate-all-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.generate-all-btn.generating {
  background: var(--bg-elevated);
  color: var(--text-muted);
}

.abort-btn {
  width: 100%;
  padding: var(--space-3);
  background: #ef4444; /* Tailwind red-500 */
  color: white;
  border: none;
  border-radius: var(--radius-lg);
  font-weight: var(--font-semibold);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--space-2);
  transition: all 0.2s;
}

.abort-btn:hover {
  background: #dc2626; /* Tailwind red-600 */
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);
}

/* ========== 素材库样式 ========== */
.materials-list {
  background: var(--bg-primary);
  border: 1px solid var(--border-default);
  border-radius: var(--radius-lg);
  overflow: hidden;
}

.material-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--space-2) var(--space-3);
  border-bottom: 1px solid var(--border-default);
}

.material-item:last-child {
  border-bottom: none;
}

.material-info {
  display: flex;
  align-items: center;
  gap: var(--space-2);
}

.material-icon {
  font-size: 14px;
}

.material-name {
  font-size: var(--text-sm);
  color: var(--text-primary);
}

.material-size {
  font-size: var(--text-xs);
  color: var(--text-muted);
}

.material-actions {
  display: flex;
  gap: var(--space-2);
}

/* 素材编辑弹窗 */
.material-modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.material-modal {
  width: 600px;
  max-height: 80vh;
  background: var(--bg-secondary);
  border: 1px solid var(--border-default);
  border-radius: var(--radius-xl);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

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

.modal-header h3 {
  font-size: var(--text-lg);
  font-weight: var(--font-semibold);
  color: var(--text-primary);
}

.modal-body {
  flex: 1;
  padding: var(--space-4);
  overflow-y: auto;
}

.modal-input {
  width: 100%;
  padding: var(--space-3);
  background: var(--bg-primary);
  border: 1px solid var(--border-default);
  border-radius: var(--radius-md);
  color: var(--text-primary);
  font-size: var(--text-sm);
  margin-bottom: var(--space-3);
}

.modal-textarea {
  width: 100%;
  padding: var(--space-3);
  background: var(--bg-primary);
  border: 1px solid var(--border-default);
  border-radius: var(--radius-md);
  color: var(--text-primary);
  font-size: var(--text-sm);
  resize: vertical;
  min-height: 200px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: var(--space-2);
  padding: var(--space-4);
  border-top: 1px solid var(--border-default);
}

.modal-btn {
  padding: var(--space-2) var(--space-4);
  border-radius: var(--radius-md);
  font-size: var(--text-sm);
  cursor: pointer;
  transition: all 0.15s;
}

.modal-btn.secondary {
  background: var(--bg-elevated);
  color: var(--text-secondary);
  border: 1px solid var(--border-default);
}

.modal-btn.primary {
  background: var(--accent-primary);
  color: white;
  border: none;
}

/* 章节关联素材 */
.linked-materials {
  margin-bottom: var(--space-2);
  padding: var(--space-2);
  background: rgba(139, 92, 246, 0.1);
  border-radius: var(--radius-md);
}

.material-checkboxes {
  display: flex;
  flex-wrap: wrap;
  gap: var(--space-2);
}

.material-checkbox {
  display: flex;
  align-items: center;
  gap: var(--space-1);
  font-size: var(--text-xs);
  color: var(--text-secondary);
  cursor: pointer;
}

.material-checkbox input {
  cursor: pointer;
}

/* 上下文统计 */
.context-stats {
  margin-top: var(--space-3);
  padding: var(--space-2);
  background: var(--bg-elevated);
  border-radius: var(--radius-md);
  font-size: var(--text-xs);
}

.stats-row {
  display: flex;
  align-items: center;
  gap: var(--space-2);
  color: var(--text-secondary);
}

.warning-box {
  margin-top: var(--space-2);
  padding: var(--space-2);
  background: rgba(234, 179, 8, 0.1);
  border-radius: var(--radius-sm);
  font-size: var(--text-xs);
}
</style>
