<template>
  <main class="fusion-result-panel">
    <!-- 空状态 -->
    <div v-if="!hasResult && !isAnalyzing" class="empty-state">
      <div class="empty-icon">
        <IconLibrary name="sparkles" :size="48" />
      </div>
      <h3>文章融合</h3>
      <p>在左侧输入两篇文章，AI 将分析优劣并生成融合文章</p>
    </div>

    <!-- 分析/生成中 -->
    <div v-else-if="isAnalyzing" class="loading-state">
      <div class="loading-spinner"></div>
      <h3>{{ stageText }}</h3>
      <p class="loading-tip">{{ stageTip }}</p>
      
      <!-- 进度流式显示 -->
      <div v-if="thinkingContent" class="thinking-preview">
        <div class="thinking-header">
          <IconLibrary name="lightbulb" :size="14" />
          <span>AI 分析过程</span>
        </div>
        <div class="thinking-content" v-html="renderedThinking"></div>
      </div>
    </div>

    <!-- 结果展示 -->
    <div v-else class="result-container">
      <!-- 分析报告 -->
      <section class="analysis-section">
        <div class="section-header">
          <h2>
            <IconLibrary name="chart" :size="18" />
            优劣分析报告
          </h2>
          <button @click="toggleAnalysis" class="toggle-btn">
            {{ showAnalysis ? '收起' : '展开' }}
          </button>
        </div>
        
        <div v-show="showAnalysis" class="analysis-content">
          <!-- 文章 A 分析 -->
          <div class="article-analysis">
            <h3><span class="badge a">A</span> {{ fusionState.titleA || '文章 A' }}</h3>
            <div class="pros-cons">
              <div class="pros">
                <h4><IconLibrary name="check" :size="14" /> 优点</h4>
                <ul>
                  <li v-for="(pro, i) in analysisResult.articleA?.pros" :key="i">{{ pro }}</li>
                </ul>
              </div>
              <div class="cons">
                <h4><IconLibrary name="warning" :size="14" /> 不足</h4>
                <ul>
                  <li v-for="(con, i) in analysisResult.articleA?.cons" :key="i">{{ con }}</li>
                </ul>
              </div>
            </div>
          </div>

          <!-- 文章 B 分析 -->
          <div class="article-analysis">
            <h3><span class="badge b">B</span> {{ fusionState.titleB || '文章 B' }}</h3>
            <div class="pros-cons">
              <div class="pros">
                <h4><IconLibrary name="check" :size="14" /> 优点</h4>
                <ul>
                  <li v-for="(pro, i) in analysisResult.articleB?.pros" :key="i">{{ pro }}</li>
                </ul>
              </div>
              <div class="cons">
                <h4><IconLibrary name="warning" :size="14" /> 不足</h4>
                <ul>
                  <li v-for="(con, i) in analysisResult.articleB?.cons" :key="i">{{ con }}</li>
                </ul>
              </div>
            </div>
          </div>

          <!-- 融合策略 -->
          <div class="fusion-strategy">
            <h4><IconLibrary name="sparkles" :size="14" /> 融合策略</h4>
            <p>{{ analysisResult.fusionStrategy }}</p>
          </div>
        </div>
      </section>

      <!-- 融合结果 -->
      <section class="fusion-result-section">
        <div class="section-header">
          <h2>
            <IconLibrary name="article" :size="18" />
            融合文章
          </h2>
          <div class="header-actions">
            <span class="word-count">{{ wordCount }} 字</span>
            <button @click="copyResult" class="action-btn">
              <IconLibrary name="clipboard" :size="14" />
              复制
            </button>
          </div>
        </div>

        <div class="fusion-content">
          <!-- 段落级选择 -->
          <div 
            v-for="(para, index) in paragraphs" 
            :key="index"
            :class="['paragraph-item', { 'excluded': !para.included }]"
          >
            <div class="paragraph-controls">
              <input 
                type="checkbox" 
                v-model="para.included" 
                class="paragraph-checkbox"
              />
              <span class="paragraph-source" :class="para.source">
                {{ para.source === 'A' ? 'A' : para.source === 'B' ? 'B' : '融' }}
              </span>
            </div>
            <div class="paragraph-content" v-html="renderMarkdown(para.content)"></div>
          </div>
        </div>
      </section>

      <!-- 底部操作 -->
      <footer class="result-footer">
        <button @click="regenerate" class="btn secondary">
          <IconLibrary name="refresh" :size="14" />
          重新生成
        </button>
        <button @click="exportResult" class="btn primary">
          <IconLibrary name="download" :size="14" />
          导出文章
        </button>
      </footer>
    </div>
  </main>
</template>

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

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

// UI 状态
const showAnalysis = ref(true)

// 计算属性
const fusionState = computed(() => articleFusionState.value)
const isAnalyzing = computed(() => fusionState.value.isAnalyzing)
const hasResult = computed(() => fusionState.value.fusionResult)
const analysisResult = computed(() => fusionState.value.analysisResult || {})
const thinkingContent = computed(() => fusionState.value.thinkingContent || '')

const stageText = computed(() => {
  const stage = fusionState.value.stage
  if (stage === 'analyzing') return '正在分析两篇文章...'
  if (stage === 'generating') return '正在生成融合文章...'
  return '处理中...'
})

const stageTip = computed(() => {
  const stage = fusionState.value.stage
  if (stage === 'analyzing') return 'AI 正在识别每篇文章的优点和不足'
  if (stage === 'generating') return 'AI 正在融合两篇文章的精华内容'
  return ''
})

const renderedThinking = computed(() => {
  return marked.parse(thinkingContent.value)
})

// 段落处理
const paragraphs = computed(() => {
  if (!fusionState.value.fusionResult) return []
  
  // 将融合结果按段落分割，分析来源
  const text = fusionState.value.fusionResult
  const paras = text.split(/\n{2,}/).filter(p => p.trim())
  
  return paras.map((content, index) => ({
    id: index,
    content: content.trim(),
    included: true,
    source: detectSource(content, index) // A, B, or 'mixed'
  }))
})

const wordCount = computed(() => {
  const included = paragraphs.value.filter(p => p.included)
  return included.reduce((sum, p) => sum + p.content.replace(/[#*\n\s]/g, '').length, 0)
})

// 检测段落来源（简化逻辑）
const detectSource = (content, index) => {
  // 实际应用中可以通过 AI 标注或文本相似度判断
  // 这里简化为根据位置交替
  if (index % 3 === 0) return 'A'
  if (index % 3 === 1) return 'B'
  return 'mixed'
}

// 渲染 Markdown
const renderMarkdown = (text) => {
  return marked.parse(text || '')
}

// 切换分析报告显示
const toggleAnalysis = () => {
  showAnalysis.value = !showAnalysis.value
}

// 复制结果
const copyResult = () => {
  const included = paragraphs.value.filter(p => p.included)
  const text = included.map(p => p.content).join('\n\n')
  navigator.clipboard.writeText(text)
  alert('已复制到剪贴板')
}

// 重新生成
const regenerate = () => {
  appStore.regenerateFusionAction()
}

// 导出文章
const exportResult = async () => {
  const included = paragraphs.value.filter(p => p.included)
  const text = included.map(p => p.content).join('\n\n')
  
  try {
    const { Document, Packer, Paragraph, TextRun } = await import('docx')
    const { saveAs } = await import('file-saver')
    
    const children = text.split('\n\n').map(para => 
      new Paragraph({ children: [new TextRun(para)] })
    )
    
    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('导出失败')
  }
}
</script>

<style scoped>
.fusion-result-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: var(--bg-primary);
  overflow-y: auto;
}

.empty-state, .loading-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  color: var(--text-muted);
  padding: var(--space-8);
}

.empty-icon {
  width: 80px;
  height: 80px;
  border-radius: 20px;
  background: var(--bg-secondary);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: var(--space-4);
  opacity: 0.5;
}

.loading-spinner {
  width: 48px;
  height: 48px;
  border: 3px solid var(--border-default);
  border-top-color: var(--accent-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: var(--space-4);
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.loading-tip {
  font-size: var(--text-sm);
  margin-top: var(--space-2);
}

.thinking-preview {
  margin-top: var(--space-6);
  width: 100%;
  max-width: 600px;
  background: var(--bg-secondary);
  border-radius: var(--radius-lg);
  border: 1px solid var(--border-default);
  overflow: hidden;
}

.thinking-header {
  padding: var(--space-2) var(--space-3);
  background: var(--bg-elevated);
  border-bottom: 1px solid var(--border-default);
  display: flex;
  align-items: center;
  gap: var(--space-2);
  font-size: var(--text-sm);
  color: var(--text-secondary);
}

.thinking-content {
  padding: var(--space-3);
  font-size: var(--text-sm);
  color: var(--text-primary);
  max-height: 200px;
  overflow-y: auto;
}

.result-container {
  padding: var(--space-6);
  display: flex;
  flex-direction: column;
  gap: var(--space-6);
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: var(--space-4);
}

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

.toggle-btn {
  font-size: var(--text-xs);
  color: var(--text-muted);
  background: none;
  border: none;
  cursor: pointer;
}

.toggle-btn:hover {
  color: var(--text-primary);
}

.analysis-content {
  display: flex;
  flex-direction: column;
  gap: var(--space-4);
}

.article-analysis {
  background: var(--bg-secondary);
  border-radius: var(--radius-lg);
  padding: var(--space-4);
  border: 1px solid var(--border-default);
}

.article-analysis h3 {
  font-size: var(--text-base);
  font-weight: var(--font-medium);
  color: var(--text-primary);
  display: flex;
  align-items: center;
  gap: var(--space-2);
  margin-bottom: var(--space-3);
}

.badge {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  font-weight: bold;
  color: white;
}

.badge.a { background: linear-gradient(135deg, #3b82f6, #6366f1); }
.badge.b { background: linear-gradient(135deg, #10b981, #06b6d4); }

.pros-cons {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: var(--space-4);
}

.pros h4 { color: var(--success-text); }
.cons h4 { color: var(--warning-text); }

.pros h4, .cons h4 {
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
  display: flex;
  align-items: center;
  gap: var(--space-1);
  margin-bottom: var(--space-2);
}

.pros ul, .cons ul {
  list-style: none;
  padding: 0;
  margin: 0;
  font-size: var(--text-sm);
  color: var(--text-secondary);
}

.pros li, .cons li {
  padding: var(--space-1) 0;
  padding-left: var(--space-3);
  position: relative;
}

.pros li::before, .cons li::before {
  content: '•';
  position: absolute;
  left: 0;
}

.fusion-strategy {
  background: var(--info-bg);
  border-radius: var(--radius-md);
  padding: var(--space-3);
  border: 1px solid var(--accent-primary);
}

.fusion-strategy h4 {
  font-size: var(--text-sm);
  color: var(--accent-primary);
  display: flex;
  align-items: center;
  gap: var(--space-1);
  margin-bottom: var(--space-2);
}

.fusion-strategy p {
  font-size: var(--text-sm);
  color: var(--text-primary);
}

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

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

.action-btn {
  font-size: var(--text-xs);
  padding: var(--space-1) var(--space-2);
  background: var(--bg-secondary);
  border: 1px solid var(--border-default);
  border-radius: var(--radius-md);
  color: var(--text-secondary);
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: var(--space-1);
}

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

.fusion-content {
  display: flex;
  flex-direction: column;
  gap: var(--space-3);
}

.paragraph-item {
  display: flex;
  gap: var(--space-3);
  padding: var(--space-3);
  background: var(--bg-secondary);
  border-radius: var(--radius-md);
  border: 1px solid var(--border-default);
  transition: all var(--transition-fast);
}

.paragraph-item.excluded {
  opacity: 0.4;
  background: var(--bg-sunken);
}

.paragraph-controls {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: var(--space-2);
}

.paragraph-checkbox {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.paragraph-source {
  font-size: 10px;
  font-weight: bold;
  padding: 2px 6px;
  border-radius: 8px;
  color: white;
}

.paragraph-source.A { background: #6366f1; }
.paragraph-source.B { background: #10b981; }
.paragraph-source.mixed { background: #8b5cf6; }

.paragraph-content {
  flex: 1;
  font-size: var(--text-sm);
  color: var(--text-primary);
  line-height: 1.7;
}

.paragraph-content :deep(p) {
  margin: 0;
}

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

.btn {
  padding: var(--space-2) var(--space-4);
  border-radius: var(--radius-md);
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: var(--space-2);
  transition: all var(--transition-fast);
  border: none;
}

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

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

.btn.primary {
  background: linear-gradient(135deg, #8b5cf6, #ec4899);
  color: white;
}

.btn.primary:hover {
  opacity: 0.9;
}
</style>
