<template>
  <main class="flex-1 flex flex-col bg-slate-950 relative h-screen min-h-0">
    <!-- Prompt调试面板 -->
    <div v-if="showPromptDebug && currentPage === 'writer'" class="absolute inset-0 bg-slate-950/95 z-20 p-8 overflow-auto backdrop-blur-sm">
      <div class="max-w-5xl mx-auto">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-bold text-yellow-500 flex items-center gap-2">
            <IconLibrary name="gear" :size="20" />
            构建的 Prompt 结构预览
          </h3>
          <button @click="showPromptDebug = false" class="text-sm text-slate-400 hover:text-white">关闭预览</button>
        </div>
        <div class="bg-black/50 p-6 rounded-lg border border-slate-700 font-mono text-sm text-green-400 whitespace-pre-wrap leading-relaxed shadow-inner">
          {{ constructedPrompt }}
        </div>
        <p class="mt-4 text-xs text-slate-500 text-center">此内容将直接发送给 API 接口</p>
      </div>
    </div>

    <!-- 顶部工具栏 -->
    <header class="h-14 border-b border-slate-800 flex items-center justify-between px-6 bg-slate-950 shrink-0">
      <span class="text-sm font-medium text-slate-400">
        {{ headerTitle }}
      </span>
      <!-- 写作页面工具栏 -->
      <div class="flex items-center gap-4" v-if="currentPage === 'writer'">
        <span class="text-xs text-slate-600">
          字数: {{ generatedContent.length }} {{ isGenerating ? '(生成中...)' : '' }}
        </span>
        <div class="flex gap-3">
          <button @click="copyContent" class="text-xs text-slate-400 hover:text-white flex items-center gap-1.5 transition">
            <IconLibrary name="copy" :size="14" />
            <span>复制 Markdown</span>
          </button>
          <button @click="clearContent" class="text-xs text-slate-400 hover:text-red-400 flex items-center gap-1.5 transition">
            <IconLibrary name="trash" :size="14" />
            <span>清空</span>
          </button>
        </div>
      </div>
      <!-- 文稿页面工具栏 -->
      <div class="flex items-center gap-4" v-if="currentPage === 'documents' && currentDocument">
        <span class="text-xs text-slate-600">
          字数: {{ documentContent.length }}
        </span>
        <div class="flex gap-3">
          <button @click="saveDocument" class="text-xs text-green-400 hover:text-green-300 flex items-center gap-1.5 transition">
            <IconLibrary name="save" :size="14" />
            <span>保存</span>
          </button>
          <button @click="copyDocContent" class="text-xs text-slate-400 hover:text-white flex items-center gap-1.5 transition">
            <IconLibrary name="copy" :size="14" />
            <span>复制</span>
          </button>
        </div>
      </div>
    </header>

    <!-- 主内容区 -->
    <div class="flex-1 overflow-y-auto p-8 md:p-12 min-h-0">
      <div class="max-w-5xl mx-auto pb-8">
        <!-- 写作页面内容 -->
        <div v-if="currentPage === 'writer'">
          <div v-if="!generatedContent && !isGenerating" class="h-full flex flex-col items-center justify-center text-slate-700 mt-20">
            <div class="w-20 h-20 flex items-center justify-center rounded-2xl bg-slate-800/50 border border-slate-700 mb-4 opacity-40">
              <IconLibrary name="edit" :size="48" />
            </div>
            <p>在左侧配置参数，点击生成开始写作</p>
          </div>

          <div v-else class="space-y-4">
            <!-- AI 思考过程折叠面板 -->
            <div v-if="thinkingContent || generationStage === 'thinking'" class="bg-indigo-950/30 rounded-lg border border-indigo-500/30 overflow-hidden">
              <button 
                @click="isThinkingExpanded = !isThinkingExpanded"
                class="w-full px-4 py-3 flex items-center justify-between text-left hover:bg-indigo-900/20 transition"
              >
                <div class="flex items-center gap-2">
                  <IconLibrary name="sparkles" :size="16" class="text-indigo-400" />
                  <span class="text-sm font-medium text-indigo-300">AI 思考路径</span>
                  <span v-if="generationStage === 'thinking'" class="text-xs px-2 py-0.5 rounded bg-indigo-500/20 text-indigo-400 animate-pulse">
                    分析中...
                  </span>
                  <span v-else class="text-xs text-slate-500">
                    (风格解构 + 大纲规划)
                  </span>
                </div>
                <span class="text-indigo-400 transition-transform" :class="{ 'rotate-180': isThinkingExpanded }">▼</span>
              </button>
              <div v-show="isThinkingExpanded" class="px-4 pb-4 border-t border-indigo-500/20">
                <div class="prose prose-invert prose-sm max-w-none mt-3 text-slate-300">
                  <div v-html="renderedThinking"></div>
                </div>
              </div>
            </div>

            <!-- 质检报告卡片（深度模式 + 范式预设时显示） -->
            <div v-if="qualityReport" class="bg-slate-800/50 rounded-lg border border-slate-600 overflow-hidden">
              <div class="px-4 py-3 border-b border-slate-700 flex items-center justify-between">
                <div class="flex items-center gap-2">
                  <IconLibrary name="search" :size="18" />
                  <span class="text-sm font-medium text-slate-200">质检报告</span>
                  <span 
                    class="text-xs px-2 py-0.5 rounded"
                    :class="{
                      'bg-green-500/20 text-green-400': qualityReport.overall === 'pass',
                      'bg-yellow-500/20 text-yellow-400': qualityReport.overall === 'warning',
                      'bg-red-500/20 text-red-400': qualityReport.overall === 'fail'
                    }"
                  >
                    {{ qualityReport.overall === 'pass' ? '通过' : qualityReport.overall === 'warning' ? '需关注' : '未通过' }}
                  </span>
                </div>
                <button 
                  @click="isQualityReportExpanded = !isQualityReportExpanded"
                  class="text-slate-400 hover:text-white transition"
                >
                  <span class="transition-transform inline-block" :class="{ 'rotate-180': isQualityReportExpanded }">▼</span>
                </button>
              </div>
              
              <div v-show="isQualityReportExpanded" class="p-4 space-y-3">
                <div 
                  v-for="check in qualityReport.checks" 
                  :key="check.key"
                  class="flex items-start gap-3 text-sm"
                >
                  <span class="shrink-0 mt-0.5">
                    <IconLibrary v-if="check.status === 'pass'" name="check" :size="14" class="text-green-400" />
                    <IconLibrary v-else-if="check.status === 'warning'" name="warning" :size="14" class="text-yellow-400" />
                    <IconLibrary v-else name="error" :size="14" class="text-red-400" />
                  </span>
                  <div>
                    <span class="font-medium" :class="{
                      'text-green-300': check.status === 'pass',
                      'text-yellow-300': check.status === 'warning',
                      'text-red-300': check.status === 'fail'
                    }">{{ check.title }}</span>
                    <p class="text-xs text-slate-500 mt-0.5">{{ check.message }}</p>
                  </div>
                </div>
                
                <div v-if="qualityReport.summary" class="pt-3 border-t border-slate-700 flex items-start gap-2">
                  <IconLibrary name="edit" :size="12" class="text-slate-400 mt-0.5" />
                  <p class="text-xs text-slate-400 italic">{{ qualityReport.summary }}</p>
                </div>
              </div>
            </div>

            <!-- 生成阶段指示器 -->
            <div v-if="isGenerating && generationStage" class="flex items-center gap-2 text-xs text-slate-500">
              <span class="w-2 h-2 rounded-full animate-pulse" :class="{
                'bg-indigo-500': generationStage === 'thinking',
                'bg-blue-500': generationStage === 'draft',
                'bg-amber-500': generationStage === 'inspect',
                'bg-yellow-500': generationStage === 'critique',
                'bg-green-500': generationStage === 'refine'
              }"></span>
              <span>{{ stageLabel }}</span>
            </div>

            <!-- 正文内容 -->
            <div class="prose prose-invert max-w-none">
              <div v-html="renderedMarkdown"></div>
              <span v-if="isGenerating" class="inline-block w-2 h-5 bg-blue-500 ml-1 animate-pulse align-middle"></span>
            </div>
          </div>
        </div>

        <!-- 文稿编辑页面内容 -->
        <div v-else-if="currentPage === 'documents'" class="h-full">
          <div v-if="!currentDocument" class="h-full flex flex-col items-center justify-center text-slate-700 mt-20">
            <div class="w-20 h-20 flex items-center justify-center rounded-2xl bg-slate-800/50 border border-slate-700 mb-4 opacity-40">
              <IconLibrary name="document" :size="48" />
            </div>
            <p>在左侧选择文稿进行编辑</p>
          </div>
          
          <div v-else class="h-full flex flex-col">
            <!-- 文稿标题 -->
            <div class="mb-4">
              <input 
                v-model="documentTitle"
                class="w-full text-2xl font-bold bg-transparent border-b border-slate-700 pb-2 text-white outline-none focus:border-blue-500 transition"
                placeholder="文稿标题..."
              >
            </div>
            
            <!-- 文稿内容编辑器 -->
            <div class="flex-1 min-h-[60vh]">
              <textarea 
                v-model="documentContent"
                class="w-full h-full bg-slate-900/50 border border-slate-700 rounded-lg p-4 text-slate-200 outline-none focus:border-blue-500 resize-none font-mono text-sm leading-relaxed"
                placeholder="开始写作..."
              ></textarea>
            </div>
            
            <!-- 文稿信息 -->
            <div class="mt-4 flex items-center justify-between text-xs text-slate-500">
              <div class="flex items-center gap-4">
                <span>状态: {{ currentDocument.status === 'draft' ? '草稿' : currentDocument.status === 'published' ? '已发布' : '已归档' }}</span>
                <span>创建: {{ formatDate(currentDocument.created_at) }}</span>
              </div>
              <div class="flex gap-2">
                <button 
                  @click="changeDocStatus('draft')"
                  :class="['px-2 py-1 rounded', currentDocument.status === 'draft' ? 'bg-yellow-900/50 text-yellow-300' : 'bg-slate-700 text-slate-400 hover:bg-slate-600']"
                >
                  草稿
                </button>
                <button 
                  @click="changeDocStatus('published')"
                  :class="['px-2 py-1 rounded', currentDocument.status === 'published' ? 'bg-green-900/50 text-green-300' : 'bg-slate-700 text-slate-400 hover:bg-slate-600']"
                >
                  发布
                </button>
                <button 
                  @click="changeDocStatus('archived')"
                  :class="['px-2 py-1 rounded', currentDocument.status === 'archived' ? 'bg-slate-600 text-slate-300' : 'bg-slate-700 text-slate-400 hover:bg-slate-600']"
                >
                  归档
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 范式写作页面内容 -->
        <div v-else-if="currentPage === 'paradigmWriter'" class="h-full flex flex-col">
          <div v-if="!totalGeneratedContent" class="h-full flex flex-col items-center justify-center text-slate-700 mt-20">
            <div class="w-20 h-20 flex items-center justify-center rounded-2xl bg-slate-800/50 border border-slate-700 mb-4 opacity-40">
              <IconLibrary name="sparkles" :size="48" />
            </div>
            <p>生成的内容将在这里实时预览</p>
            <p class="text-xs text-slate-500 mt-2">选择章节并点击「生成本节」开始</p>
          </div>
          
          <div v-else class="space-y-6">
            <!-- 统计信息 -->
            <div class="flex items-center justify-between text-sm text-slate-400">
              <span>{{ totalWordCount }} 字</span>
              <span>预计阅读 {{ Math.ceil(totalWordCount / 300) }} 分钟</span>
            </div>
            
            <!-- 生成内容预览 -->
            <div class="prose prose-invert max-w-none">
              <div 
                v-for="(section, index) in paradigmWriterState.sections" 
                :key="index"
                v-show="section.generatedContent"
                class="mb-6"
              >
                <h3 :class="section.type === 'h2' ? 'text-xl font-bold text-white mb-3' : 'text-lg font-semibold text-slate-200 mb-2'">
                  {{ section.title }}
                </h3>
                <div v-html="renderSectionMarkdown(section.generatedContent)"></div>
              </div>
            </div>
            
            <!-- 操作按钮 -->
            <div class="flex gap-3 pt-4 border-t border-slate-700">
              <button @click="copyParadigmContent" class="text-xs px-4 py-2 bg-slate-700 hover:bg-slate-600 text-white rounded transition flex items-center gap-2">
                <IconLibrary name="copy" :size="14" />
                <span>复制全文</span>
              </button>
              <button @click="exportParadigmToWord" class="text-xs px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded transition flex items-center gap-2">
                <IconLibrary name="download" :size="14" />
                <span>导出 Word</span>
              </button>
            </div>
          </div>
        </div>

        <!-- 范式分析页面内容 -->
        <div v-else-if="currentPage === 'analysis'" class="space-y-8">
          <!-- 范式编辑表单 -->
          <div v-if="paradigmEditState.isEditing" class="bg-slate-900 rounded-lg border border-slate-700 overflow-hidden">
            <div class="px-6 py-4 border-b border-slate-700 flex items-center justify-between">
              <h3 class="text-lg font-bold text-white flex items-center gap-2">
                <IconLibrary :name="paradigmEditState.isAddMode ? 'add' : 'edit'" :size="20" />
                {{ paradigmEditState.isAddMode ? '新增写作范式' : '编辑写作范式' }}
              </h3>
              <button
                @click="closeParadigmEdit"
                class="text-slate-400 hover:text-white transition"
              >
                <IconLibrary name="close" :size="18" />
              </button>
            </div>

            <div class="p-6 space-y-5">
              <!-- 图标选择 -->
              <div>
                <label class="block text-sm text-slate-400 mb-2">图标</label>
                <div class="flex flex-wrap gap-2">
                  <button
                    v-for="icon in iconOptions"
                    :key="icon"
                    @click="paradigmEditState.editForm.icon = icon"
                    :class="['w-10 h-10 rounded border transition flex items-center justify-center',
                      paradigmEditState.editForm.icon === icon
                        ? 'border-blue-500 bg-blue-500/20'
                        : 'border-slate-600 hover:border-slate-500']"
                  >
                    <IconLibrary :name="icon" :size="20" />
                  </button>
                </div>
              </div>

              <!-- 名称 -->
              <div>
                <label class="block text-sm text-slate-400 mb-2">范式名称</label>
                <input
                  v-model="paradigmEditState.editForm.name"
                  class="w-full px-4 py-3 bg-slate-800 border border-slate-600 rounded-lg text-white outline-none focus:border-blue-500"
                  placeholder="如：技术博客范式"
                />
              </div>

              <!-- 描述 -->
              <div>
                <label class="block text-sm text-slate-400 mb-2">描述</label>
                <textarea
                  v-model="paradigmEditState.editForm.description"
                  rows="2"
                  class="w-full px-4 py-3 bg-slate-800 border border-slate-600 rounded-lg text-white outline-none focus:border-blue-500 resize-none"
                  placeholder="简要描述此范式的适用场景"
                ></textarea>
              </div>

              <!-- 标签 -->
              <div>
                <label class="block text-sm text-slate-400 mb-2">标签（逗号分隔）</label>
                <input
                  v-model="paradigmEditState.editForm.tagsInput"
                  class="w-full px-4 py-3 bg-slate-800 border border-slate-600 rounded-lg text-white outline-none focus:border-blue-500"
                  placeholder="如：问题引入,解决方案,代码示例"
                />
                <div class="flex flex-wrap gap-1 mt-2" v-if="paradigmEditState.editForm.tagsInput">
                  <span
                    v-for="tag in paradigmEditState.editForm.tagsInput.split(',').map(t => t.trim()).filter(t => t)"
                    :key="tag"
                    :class="['text-xs px-2 py-1 rounded', paradigmEditState.editForm.tagClass]"
                  >
                    {{ tag }}
                  </span>
                </div>
              </div>

              <!-- 标签颜色 -->
              <div>
                <label class="block text-sm text-slate-400 mb-2">标签颜色</label>
                <div class="flex gap-2 flex-wrap">
                  <button
                    v-for="color in colorOptions"
                    :key="color.class"
                    @click="paradigmEditState.editForm.tagClass = color.class"
                    :class="['px-3 py-1 text-xs rounded border transition', color.class, 
                      paradigmEditState.editForm.tagClass === color.class 
                        ? 'ring-2 ring-white/50' 
                        : 'opacity-60 hover:opacity-100']"
                  >
                    {{ color.label }}
                  </button>
                </div>
              </div>

              <!-- ⭐ 核心字段：完整 Prompt -->
              <div>
                <label class="block text-sm text-slate-400 mb-2 flex items-center gap-2">
                  <IconLibrary name="sparkles" :size="14" class="text-yellow-400" />
                  <span>完整 Prompt（核心字段）</span>
                  <span class="text-xs text-slate-500">粘贴您的完整提示词</span>
                </label>
                <textarea
                  v-model="paradigmEditState.editForm.specializedPrompt"
                  rows="16"
                  class="w-full px-4 py-3 bg-slate-800 border border-slate-600 rounded-lg text-white outline-none focus:border-blue-500 resize-y font-mono text-sm leading-relaxed"
                  placeholder="在此粘贴您的完整 Prompt..."
                ></textarea>
                <p class="text-xs text-slate-500 mt-2 flex items-start gap-1.5">
                  <IconLibrary name="info" :size="12" class="mt-0.5" />
                  <span>提示：这是 AI 调用时的核心指令。完整的 Prompt 应包含角色、目标、步骤和输出格式。</span>
                </p>
              </div>
            </div>

            <div class="px-6 py-4 border-t border-slate-700 flex justify-end gap-3">
              <button
                @click="closeParadigmEdit"
                class="px-4 py-2 text-sm text-slate-400 hover:text-white transition"
              >
                取消
              </button>
              <button
                @click="saveParadigmEdit"
                :disabled="!paradigmEditState.editForm.name"
                class="px-6 py-2 text-sm bg-blue-600 hover:bg-blue-500 text-white rounded-lg transition disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {{ paradigmEditState.isAddMode ? '添加范式' : '保存修改' }}
              </button>
            </div>
          </div>

          <!-- 默认显示或分析结果 -->
          <template v-else>
            <div v-if="!analysisResult" class="h-full flex flex-col items-center justify-center text-slate-700 mt-20">
              <div class="w-20 h-20 flex items-center justify-center rounded-2xl bg-slate-800/50 border border-slate-700 mb-4 opacity-40">
                <IconLibrary name="chart" :size="48" />
              </div>
              <p>选择左侧的写作范式或使用分析工具</p>
            </div>
          
            <div v-else class="space-y-6">
              <div v-if="analysisResult.error" class="bg-red-900/20 rounded-lg p-6 border border-red-700">
                <h3 class="text-lg font-bold text-red-400 mb-4">分析失败</h3>
                <p class="text-red-300">{{ analysisResult.message }}</p>
              </div>
            
              <div v-else class="space-y-6">
                <!-- 分析结果头部 -->
                <div class="bg-slate-900 rounded-lg p-6 border border-slate-700">
                  <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-bold text-white">分析结果</h3>
                    <span class="text-xs px-3 py-1 rounded-full bg-blue-900/30 text-blue-300 border border-blue-700">
                      {{ analysisResult.paradigm }}
                    </span>
                  </div>
                
                  <!-- 分析内容 -->
                  <div class="prose prose-invert max-w-none">
                    <div v-html="marked.parse(analysisResult.analysis)"></div>
                  </div>
                
                  <!-- 操作按钮 -->
                  <div class="mt-6 flex gap-3">
                    <button
                      @click="copyAnalysis"
                      class="text-xs px-4 py-2 bg-slate-700 hover:bg-slate-600 text-white rounded transition flex items-center gap-2"
                    >
                      <IconLibrary name="copy" :size="14" />
                      <span>复制分析结果</span>
                    </button>
                    <button
                      @click="applyToWriting"
                      class="text-xs px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded transition flex items-center gap-2"
                    >
                      <IconLibrary name="edit" :size="14" />
                      <span>应用到写作</span>
                    </button>
                  </div>
                </div>
              
                <!-- 范式详情卡片 -->
                <div v-if="getParadigmDetails()" class="bg-slate-900/50 rounded-lg p-6 border border-slate-700">
                  <h4 class="text-md font-bold text-white mb-4">{{ getParadigmDetails().name }}特点</h4>
                  <div class="grid grid-cols-2 gap-4">
                    <div>
                      <h5 class="text-xs font-medium text-slate-400 mb-2">结构要素</h5>
                      <div class="flex flex-wrap gap-1">
                        <span 
                          v-for="tag in getParadigmDetails().tags" 
                          :key="tag"
                          :class="['text-xs px-2 py-1 rounded', getParadigmDetails().tagClass]"
                        >
                          {{ tag }}
                        </span>
                      </div>
                    </div>
                    <div>
                      <h5 class="text-xs font-medium text-slate-400 mb-2">适用场景</h5>
                      <p class="text-xs text-slate-300">{{ getParadigmDetails().description }}</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </div>

        <!-- 其他页面默认内容 -->
        <div v-else class="h-full flex flex-col items-center justify-center text-slate-700 mt-20">
          <div class="w-20 h-20 flex items-center justify-center rounded-2xl bg-slate-800/50 border border-slate-700 mb-4 opacity-40">
            <IconLibrary name="document" :size="48" />
          </div>
          <p>选择左侧面板查看内容</p>
        </div>
      </div>
    </div>
  </main>
</template>

<script setup>
import { computed, ref, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useAppStore } from '../stores/app'
import { buildPrompt } from '../utils/promptBuilder.js'
import { marked } from 'marked'
import IconLibrary from './icons/IconLibrary.vue'

const appStore = useAppStore()
const {
  currentPage,
  showPromptDebug,
  generatedContent,
  thinkingContent,
  generationStage,
  qualityReport,
  isGenerating,
  analysisResult,
  inputTask,
  selectedTags,
  customConstraint,
  references,
  paradigmEditState
} = storeToRefs(appStore)

// AI 思考过程折叠状态
const isThinkingExpanded = ref(false)
const isQualityReportExpanded = ref(true) // 质检报告默认展开

// 范式写作预览相关
const { paradigmWriterState } = storeToRefs(appStore)

// 获取总生成内容
const totalGeneratedContent = computed(() => {
  if (!paradigmWriterState.value?.sections) return ''
  return paradigmWriterState.value.sections
    .filter(s => s.generatedContent)
    .map(s => `## ${s.title}\n\n${s.generatedContent}`)
    .join('\n\n')
})

// 字数统计
const totalWordCount = computed(() => {
  return totalGeneratedContent.value.length
})

// 渲染章节 Markdown
const renderSectionMarkdown = (content) => {
  return marked.parse(content || '')
}

// 复制范式写作内容
const copyParadigmContent = () => {
  if (totalGeneratedContent.value) {
    navigator.clipboard.writeText(totalGeneratedContent.value)
    alert('已复制到剪贴板')
  }
}

// 导出 Word
const exportParadigmToWord = async () => {
  if (!totalGeneratedContent.value) return
  
  try {
    const { Document, Paragraph, TextRun, Packer, HeadingLevel } = await import('docx')
    const { saveAs } = await import('file-saver')
    
    const children = []
    paradigmWriterState.value.sections.forEach(section => {
      if (section.generatedContent) {
        children.push(
          new Paragraph({
            text: section.title,
            heading: section.type === 'h2' ? HeadingLevel.HEADING_2 : HeadingLevel.HEADING_3
          }),
          new Paragraph({
            children: [new TextRun(section.generatedContent)]
          })
        )
      }
    })
    
    const doc = new Document({
      sections: [{ properties: {}, children }]
    })
    
    const blob = await Packer.toBlob(doc)
    saveAs(blob, `范式写作_${new Date().toLocaleDateString()}.docx`)
  } catch (error) {
    console.error('导出失败:', error)
    alert('导出失败')
  }
}

// 图标选项 (使用 IconLibrary 图标名称)
const iconOptions = ['edit', 'document', 'chart', 'sparkles', 'folder', 'article', 'star', 'lightbulb', 'pin', 'clipboard']

// 颜色选项
const colorOptions = [
  { label: '蓝色', class: 'bg-blue-900/30 text-blue-300' },
  { label: '绿色', class: 'bg-green-900/30 text-green-300' },
  { label: '红色', class: 'bg-red-900/30 text-red-300' },
  { label: '紫色', class: 'bg-purple-900/30 text-purple-300' },
  { label: '橙色', class: 'bg-orange-900/30 text-orange-300' },
  { label: '青色', class: 'bg-cyan-900/30 text-cyan-300' }
]

// 关闭编辑
const closeParadigmEdit = () => {
  paradigmEditState.value.isEditing = false
  paradigmEditState.value.isAddMode = false
  paradigmEditState.value.editingParadigmId = null
}

// 保存范式编辑
const saveParadigmEdit = () => {
  const form = paradigmEditState.value.editForm
  
  // 构建范式对象
  const paradigm = {
    id: paradigmEditState.value.isAddMode 
      ? `custom_${Date.now()}` 
      : paradigmEditState.value.editingParadigmId,
    icon: form.icon,
    name: form.name,
    description: form.description,
    tags: form.tagsInput.split(',').map(t => t.trim()).filter(t => t),
    tagClass: form.tagClass,
    specializedPrompt: form.specializedPrompt,
    isCustom: true,
    createdAt: paradigmEditState.value.isAddMode ? new Date().toISOString() : undefined
  }

  // 保存到 localStorage
  const customParadigms = JSON.parse(localStorage.getItem('customParadigms') || '[]')
  
  if (paradigmEditState.value.isAddMode) {
    customParadigms.push(paradigm)
  } else {
    const index = customParadigms.findIndex(p => p.id === paradigm.id)
    if (index >= 0) {
      customParadigms[index] = { ...customParadigms[index], ...paradigm }
    } else {
      // 可能是系统范式的修改，添加为新的自定义范式
      customParadigms.push(paradigm)
    }
  }
  
  localStorage.setItem('customParadigms', JSON.stringify(customParadigms))
  
  // 关闭编辑
  closeParadigmEdit()
  
  // 触发刷新事件
  window.dispatchEvent(new CustomEvent('paradigm-saved'))
  
  alert('范式保存成功！')
}

// 文稿编辑状态
const currentDocument = ref(null)
const documentTitle = ref('')
const documentContent = ref('')

// 头部标题
const headerTitle = computed(() => {
  const titles = {
    'writer': '输出预览',
    'analysis': '范式分析结果',
    'documents': currentDocument.value ? `编辑: ${currentDocument.value.title}` : '文稿编辑',
    'materials': '素材详情',
    'settings': '设置'
  }
  return titles[currentPage.value] || ''
})

// 监听当前文稿变化（从 DocumentsPanel 传入）
watch(() => appStore.currentDocument, (doc) => {
  if (doc) {
    currentDocument.value = doc
    documentTitle.value = doc.title || ''
    documentContent.value = doc.content || ''
  }
}, { immediate: true })

// 保存文稿
const saveDocument = async () => {
  if (!currentDocument.value) return
  
  try {
    const { updateDocument } = await import('../db/index.js')
    updateDocument(currentDocument.value.id, {
      title: documentTitle.value,
      content: documentContent.value
    })
    currentDocument.value.title = documentTitle.value
    currentDocument.value.content = documentContent.value
    alert('保存成功')
  } catch (error) {
    console.error('保存失败:', error)
  }
}

// 复制文稿内容
const copyDocContent = () => {
  navigator.clipboard.writeText(documentContent.value)
  alert('已复制到剪贴板')
}

// 修改文稿状态
const changeDocStatus = async (status) => {
  if (!currentDocument.value) return
  
  try {
    const { updateDocument } = await import('../db/index.js')
    updateDocument(currentDocument.value.id, { status })
    currentDocument.value.status = status
  } 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' })
}

// 暴露设置当前文稿的方法（供 DocumentsPanel 调用）
const setCurrentDocument = (doc) => {
  currentDocument.value = doc
  if (doc) {
    documentTitle.value = doc.title || ''
    documentContent.value = doc.content || ''
  }
}

// 暴露给父组件
defineExpose({ setCurrentDocument })

// 范式定义
const paradigms = [
  {
    type: 'tech',
    name: '技术博客范式',
    description: '适用于技术分享、教程类文章',
    tags: ['问题引入', '解决方案', '代码示例', '总结'],
    tagClass: 'bg-blue-900/30 text-blue-300',
    prompt: '请按照技术博客的范式写作，包含：1) 问题背景引入 2) 具体解决方案 3) 代码示例说明 4) 总结与最佳实践',
    constraints: ['Markdown格式', '总分总结构', '数据支撑']
  },
  {
    type: 'business',
    name: '商业分析范式',
    description: '适用于行业分析、市场报告',
    tags: ['背景介绍', '数据支撑', '趋势分析', '建议'],
    tagClass: 'bg-green-900/30 text-green-300',
    prompt: '请按照商业分析的范式写作，包含：1) 行业背景介绍 2) 数据分析与支撑 3) 趋势预测 4) 战略建议',
    constraints: ['Markdown格式', '数据支撑', '引用权威来源']
  },
  {
    type: 'marketing',
    name: '产品文案范式',
    description: '适用于产品介绍、营销文案',
    tags: ['痛点切入', '价值主张', '功能亮点', '行动号召'],
    tagClass: 'bg-purple-900/30 text-purple-300',
    prompt: '请按照产品文案的范式写作，包含：1) 用户痛点切入 2) 核心价值主张 3) 产品功能亮点 4) 明确的行动号召',
    constraints: ['语气幽默', '严禁被动语态']
  },
  {
    type: 'academic',
    name: '学术论文范式',
    description: '适用于学术写作、研究报告',
    tags: ['摘要', '引言', '文献综述', '方法论', '结果'],
    tagClass: 'bg-orange-900/30 text-orange-300',
    prompt: '请按照学术论文的范式写作，包含：1) 摘要 2) 引言 3) 文献综述 4) 研究方法论 5) 结果与讨论 6) 结论',
    constraints: ['引用权威来源', '严禁被动语态']
  },
  {
    type: 'party-review',
    name: '民主生活会对照检查',
    description: '适用于党政机关民主生活会个人对照检查材料',
    tags: ['开篇引言', '对照查摆', '根源剖析', '整改措施', '表态'],
    tagClass: 'bg-red-900/30 text-red-300',
    prompt: '请按照民主生活会对照检查材料的范式写作',
    constraints: ['总分总结构', '引用权威来源']
  },
  {
    type: 'gov-report',
    name: '政府工作报告',
    description: '适用于政府工作总结、述职报告',
    tags: ['工作回顾', '成绩总结', '问题分析', '下步计划'],
    tagClass: 'bg-cyan-900/30 text-cyan-300',
    prompt: '请按照政府工作报告的范式写作',
    constraints: ['Markdown格式', '数据支撑', '总分总结构']
  }
]

// 计算构建的Prompt
const constructedPrompt = computed(() => {
  return buildPrompt(
    inputTask.value,
    [...selectedTags.value, customConstraint.value].filter(Boolean),
    references.value
  )
})

// 渲染Markdown
const renderedMarkdown = computed(() => {
  return marked.parse(generatedContent.value || '')
})

// 渲染 AI 思考过程
const renderedThinking = computed(() => {
  return marked.parse(thinkingContent.value || '')
})

// 生成阶段标签
const stageLabel = computed(() => {
  const labels = {
    'thinking': '风格解构 & 大纲规划中...',
    'draft': '正在撰写初稿...',
    'inspect': '正在进行质量检查...',
    'critique': 'AI 深度反思中...',
    'refine': '深度润色中...'
  }
  return labels[generationStage.value] || ''
})

// 复制内容
const copyContent = () => {
  navigator.clipboard.writeText(generatedContent.value)
  alert('已复制到剪贴板')
}

// 清空内容
const clearContent = () => {
  generatedContent.value = ''
}

// 复制分析结果
const copyAnalysis = () => {
  if (analysisResult.value) {
    navigator.clipboard.writeText(analysisResult.value.analysis)
    alert('分析结果已复制到剪贴板')
  }
}

// 应用到写作
const applyToWriting = () => {
  if (analysisResult.value) {
    // 1. 将原文添加为参考案例
    appStore.addReferenceFromAnalysis(
      `参考范文_${analysisResult.value.paradigm}`,
      appStore.analysisText
    )

    // 2. 将风格分析结果应用到自定义要求中
    appStore.customConstraint = `请模仿以下风格分析进行创作：\n${analysisResult.value.analysis}`

    // 3. 应用范式预设（可选，如果有匹配的预设）
    const paradigm = getParadigmDetails()
    if (paradigm) {
      inputTask.value = paradigm.prompt
      selectedTags.value = [...paradigm.constraints]
    }

    // 4. 切换页面
    appStore.switchPage('writer')
    alert(`已将分析结果及原文应用到写作工坊`)
  }
}

// 获取范式详情
const getParadigmDetails = () => {
  if (!analysisResult.value?.paradigmType) return null
  return paradigms.find(p => p.type === analysisResult.value.paradigmType)
}
</script>
