<template>
  <div class="mimic-container">
    <!-- 左侧配置面板 -->
    <aside class="mimic-sidebar glass">
      <header class="sidebar-header">
        <h2 class="sidebar-title">
          <IconLibrary name="copy" :size="20" />
          <span>以稿写稿</span>
        </h2>
        <span class="badge badge-purple">AI 模仿</span>
      </header>

      <div class="sidebar-content custom-scrollbar">
        <!-- 1. 原稿输入 -->
        <section class="config-section">
          <div class="flex justify-between items-center mb-2">
            <label class="config-label">1. 提供原稿 (Reference)</label>
            <button @click="openDocSelector" class="text-xs text-accent-primary hover:underline flex items-center gap-1">
              <IconLibrary name="folder" :size="12" />
              文稿库导入
            </button>
          </div>
          <textarea
            v-model="mimicState.sourceArticle"
            placeholder="粘贴你要模仿的原稿内容..."
            class="mimic-textarea h-40"
          ></textarea>
          
          <button 
            @click="analyzeStyle" 
            :disabled="mimicState.isAnalyzing || !mimicState.sourceArticle"
            class="btn btn-secondary w-full mt-2 py-2 text-xs flex items-center justify-center gap-2"
          >
            <IconLibrary v-if="!mimicState.isAnalyzing" name="analysis" :size="14" />
            <span v-else class="animate-spin">↻</span>
            {{ mimicState.isAnalyzing ? '正在分析风格指纹...' : '分析原稿风格' }}
          </button>

          <!-- 风格分析结果展示 -->
          <div v-if="mimicState.styleAnalysis" class="style-result mt-3 glass-card p-3">
            <h4 class="text-[10px] text-muted uppercase tracking-wider mb-2 flex items-center gap-1">
              <IconLibrary name="sparkles" :size="10" />
              已提取风格指纹
            </h4>
            <div class="style-description" v-html="renderedStyleAnalysis"></div>
          </div>
        </section>

        <!-- 2. 写作方向 -->
        <section class="config-section">
          <label class="config-label mb-2 block">2. 写作方向 (User Direction)</label>
          <textarea
            v-model="mimicState.writingDirection"
            placeholder="描述你想写的新主题、核心内容或大纲..."
            class="mimic-textarea h-32"
          ></textarea>
        </section>

        <!-- 3. 高级配置 -->
        <section class="config-section">
          <label class="config-label mb-2 block">3. 模仿设置 (Options)</label>
          
          <!-- 风格强度 -->
          <div class="mb-4">
            <div class="flex justify-between items-center mb-1.5">
              <span class="text-xs text-muted">风格模仿强度</span>
              <span class="text-xs font-mono text-purple-400">{{ mimicState.styleIntensity }}%</span>
            </div>
            <input 
              type="range" 
              v-model.number="mimicState.styleIntensity" 
              min="0" max="100" 
              class="w-full h-1.5 bg-slate-800 rounded-lg appearance-none cursor-pointer accent-purple-500"
            >
          </div>

          <!-- 保留元素 -->
          <div class="space-y-2">
            <span class="text-xs text-muted block mb-1">重点保留元素</span>
            <div class="flex flex-wrap gap-2">
              <label 
                v-for="item in ['结构', '语气', '用词', '修辞', '行文节奏']" 
                :key="item"
                class="flex items-center gap-1.5 px-2.5 py-1.5 rounded-md bg-slate-800/50 border border-slate-700/50 cursor-pointer transition-all hover:bg-slate-700/50"
                :class="{ 'border-purple-500/50 bg-purple-500/10 text-purple-300': mimicState.preserveElements.includes(item) }"
              >
                <input 
                  type="checkbox" 
                  :value="item" 
                  v-model="mimicState.preserveElements"
                  class="hidden"
                >
                <span class="text-[11px]">{{ item }}</span>
              </label>
            </div>
          </div>
        </section>
      </div>

      <footer class="sidebar-footer">
        <!-- 段落进度显示 -->
        <div v-if="mimicState.totalParagraphs > 0" class="progress-bar mb-3">
          <div class="flex justify-between text-xs text-muted mb-1">
            <span>段落进度</span>
            <span>{{ mimicState.currentParagraphIndex + 1 }} / {{ mimicState.totalParagraphs }}</span>
          </div>
          <div class="h-1.5 bg-slate-800 rounded-full overflow-hidden">
            <div 
              class="h-full bg-gradient-to-r from-purple-500 to-pink-500 transition-all duration-300"
              :style="{ width: `${((mimicState.currentParagraphIndex + 1) / mimicState.totalParagraphs) * 100}%` }"
            ></div>
          </div>
        </div>
        
        <div class="grid grid-cols-2 gap-2">
          <button 
            @click="splitParagraphs"
            :disabled="!mimicState.sourceArticle.trim() || mimicState.isGenerating"
            class="split-button"
          >
            <IconLibrary name="analysis" :size="16" />
            <span>拆分段落</span>
          </button>
          
          <button 
            @click="startParagraphMimic"
            :disabled="isButtonDisabled || mimicState.paragraphs.length === 0"
            class="generate-button"
            :class="{ 'generating': mimicState.isGenerating }"
          >
            <IconLibrary v-if="!mimicState.isGenerating" name="copy" :size="16" />
            <span v-else class="animate-spin">↻</span>
            {{ mimicState.isGenerating ? `第${mimicState.currentParagraphIndex + 1}段...` : '分段仿写' }}
          </button>
        </div>
      </footer>
    </aside>

    <!-- 中间内容预览区 -->
    <main class="mimic-main">
      <div v-if="!mimicState.generatedContent && !mimicState.isGenerating" class="empty-preview">
        <div class="empty-icon-box">
          <IconLibrary name="copy" :size="48" />
        </div>
        <h3>准备好模仿了吗？</h3>
        <p>提供原稿并给出方向，AI 将为您复刻经典</p>
      </div>

      <div v-else class="preview-container custom-scrollbar">
        <header class="preview-header">
          <div class="flex items-center gap-3">
            <div class="preview-dot"></div>
            <h3 class="text-sm font-medium">生成结果预览 (Markdown)</h3>
            <span v-if="wordCount > 0" class="text-xs text-muted font-mono bg-slate-800/50 px-2 py-0.5 rounded">
              {{ wordCount }} 字
            </span>
          </div>
          <div class="flex items-center gap-2">
            <button @click="copyToClipboard" class="icon-btn" title="复制全文">
              <IconLibrary name="clipboard" :size="16" />
            </button>
            <button @click="saveToDocuments" class="icon-btn" title="保存到文稿库">
              <IconLibrary name="save" :size="16" />
            </button>
          </div>
        </header>

        <div class="markdown-body" v-html="renderedContent"></div>
      </div>
    </main>

    <!-- 右侧思考面板 -->
    <aside v-if="mimicState.thinkingContent" class="thinking-panel glass">
      <header class="thinking-header">
        <IconLibrary name="sparkles" :size="16" />
        <span>AI 思路分析</span>
      </header>
      <div class="thinking-content custom-scrollbar" v-html="renderedThinking"></div>
    </aside>

    <!-- 文稿选择对话框 -->
    <DocumentSelectorModal 
      v-if="showDocSelector" 
      @close="showDocSelector = false"
      @select="handleDocSelected"
    />
  </div>
</template>

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

const appStore = useAppStore()
const { mimicWriterState: mimicState } = storeToRefs(appStore)

const showDocSelector = ref(false)

// 计算属性
const isButtonDisabled = computed(() => {
  return mimicState.value.isGenerating || 
         !mimicState.value.sourceArticle.trim() || 
         !mimicState.value.writingDirection.trim()
})

const renderedContent = computed(() => {
  return mimicState.value.generatedContent ? marked(mimicState.value.generatedContent) : ''
})

const renderedThinking = computed(() => {
  return mimicState.value.thinkingContent ? marked(mimicState.value.thinkingContent) : ''
})

const renderedStyleAnalysis = computed(() => {
  return mimicState.value.styleAnalysis ? marked(mimicState.value.styleAnalysis) : ''
})

const wordCount = computed(() => {
  const content = mimicState.value.generatedContent || ''
  // 简单的中文字数 + 英文单词统计
  const cn = (content.match(/[\u4e00-\u9fa5]/g) || []).length
  const en = (content.match(/[a-zA-Z0-9]+/g) || []).length
  return cn + en
})

// 方法
const analyzeStyle = async () => {
  try {
    await appStore.analyzeMimicStyleAction()
  } catch (err) {
    alert('分析风格失败: ' + err.message)
  }
}

const generateContent = async () => {
  try {
    await appStore.mimicGenerateAction()
  } catch (err) {
    alert('生成内容失败: ' + err.message)
  }
}

const splitParagraphs = () => {
  const paragraphs = appStore.splitParagraphsAction()
  if (paragraphs.length === 0) {
    alert('未检测到有效段落，请检查原稿内容')
  }
}

const startParagraphMimic = async () => {
  try {
    await appStore.mimicAllParagraphsAction()
  } catch (err) {
    alert('分段仿写失败: ' + err.message)
  }
}

const openDocSelector = () => {
  showDocSelector.value = true
}

const handleDocSelected = (doc) => {
  mimicState.value.sourceArticle = doc.content
  showDocSelector.value = false
}

const copyToClipboard = () => {
  navigator.clipboard.writeText(mimicState.value.generatedContent)
    .then(() => alert('已复制到剪贴板'))
}

const saveToDocuments = () => {
  // 模拟保存逻辑，实际项目中可能需要调用 storage/database Action
  console.log('保存内容:', mimicState.value.generatedContent)
  alert('功能开发中：已将内容暂存')
}
</script>

<style scoped>
.mimic-container {
  display: flex;
  height: 100%;
  width: 100%;
  background: var(--bg-primary);
  color: var(--text-primary);
  overflow: hidden;
}

/* 侧边栏样式 */
.mimic-sidebar {
  width: 320px;
  border-right: 1px solid var(--border-default);
  display: flex;
  flex-direction: column;
  flex-shrink: 0;
  z-index: 10;
}

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

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

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

.config-section {
  margin-bottom: var(--space-8);
}

.config-label {
  font-size: var(--text-sm);
  font-weight: var(--font-semibold);
  color: var(--text-secondary);
}

.mimic-textarea {
  width: 100%;
  padding: var(--space-3);
  background: rgba(255, 255, 255, 0.03);
  border: 1px solid var(--border-default);
  border-radius: var(--radius-lg);
  color: var(--text-primary);
  font-size: var(--text-sm);
  resize: none;
  transition: all 0.2s;
}

.mimic-textarea:focus {
  outline: none;
  border-color: var(--accent-primary);
  background: rgba(255, 255, 255, 0.05);
}

.sidebar-footer {
  padding: var(--space-5) var(--space-6);
  border-top: 1px solid var(--border-default);
}

.generate-button {
  width: 100%;
  padding: var(--space-3.5);
  background: linear-gradient(135deg, #8b5cf6, #ec4899);
  color: white;
  border: none;
  border-radius: var(--radius-xl);
  font-weight: var(--font-bold);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--space-2);
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 4px 15px rgba(139, 92, 246, 0.3);
}

.continue-button {
  width: 100%;
  padding: var(--space-3.5);
  background: rgba(255, 255, 255, 0.1);
  color: var(--text-primary);
  border: 1px solid var(--border-default);
  border-radius: var(--radius-xl);
  font-weight: var(--font-bold);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--space-2);
  cursor: pointer;
  transition: all 0.3s;
}

.continue-button:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.15);
  border-color: var(--accent-primary);
}

.continue-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  filter: grayscale(1);
}

.split-button {
  width: 100%;
  padding: var(--space-3);
  background: rgba(255, 255, 255, 0.08);
  color: var(--text-primary);
  border: 1px solid var(--border-default);
  border-radius: var(--radius-lg);
  font-weight: var(--font-semibold);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--space-2);
  cursor: pointer;
  transition: all 0.2s;
  font-size: var(--text-sm);
}

.split-button:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.12);
  border-color: var(--accent-primary);
}

.split-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.generate-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(139, 92, 246, 0.4);
}

.generate-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  filter: grayscale(1);
}

.generate-button.generating {
  animation: pulse 2s infinite;
}

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

/* 主预览区样式 */
.mimic-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: rgba(15, 23, 42, 0.2);
  position: relative;
}

.empty-preview {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: var(--text-muted);
}

.empty-icon-box {
  width: 100px;
  height: 100px;
  border-radius: 30px;
  background: rgba(255, 255, 255, 0.02);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: var(--space-6);
  border: 1px solid rgba(255, 255, 255, 0.05);
  color: #8b5cf6;
}

.preview-container {
  flex: 1;
  padding: var(--space-8);
  overflow-y: auto;
}

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

.preview-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #8b5cf6;
  box-shadow: 0 0 8px #8b5cf6;
}

.icon-btn {
  padding: var(--space-2);
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid var(--border-default);
  border-radius: var(--radius-md);
  color: var(--text-secondary);
  cursor: pointer;
  transition: all 0.2s;
}

.icon-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  color: var(--text-primary);
  border-color: var(--accent-primary);
}

/* 思考面板样式 */
.thinking-panel {
  width: 300px;
  border-left: 1px solid var(--border-default);
  display: flex;
  flex-direction: column;
  flex-shrink: 0;
  background: rgba(15, 23, 42, 0.4);
}

.thinking-header {
  padding: var(--space-4) var(--space-5);
  border-bottom: 1px solid var(--border-default);
  display: flex;
  align-items: center;
  gap: var(--space-2);
  font-size: var(--text-xs);
  font-weight: var(--font-bold);
  color: var(--accent-warning);
  text-transform: uppercase;
  letter-spacing: 0.05em;
}

.thinking-content {
  flex: 1;
  padding: var(--space-5);
  overflow-y: auto;
  font-size: var(--text-xs);
  color: var(--text-secondary);
  line-height: 1.6;
}

.style-result {
  border-left: 2px solid #8b5cf6;
  background: rgba(139, 92, 246, 0.03);
}

.style-description {
  font-size: 11px;
  line-height: 1.5;
  color: var(--text-muted);
}

.style-description :deep(p) {
  margin-bottom: 4px;
}

/* Markdown 样式补偿 */
.markdown-body {
  color: var(--text-primary);
  line-height: 1.8;
}

.markdown-body :deep(h1), 
.markdown-body :deep(h2), 
.markdown-body :deep(h3) {
  margin-top: 1.5em;
  margin-bottom: 0.5em;
  font-weight: 600;
}

.markdown-body :deep(p) {
  margin-bottom: 1em;
}

/* Badge 样式 */
.badge-purple {
  background: rgba(139, 92, 246, 0.2);
  color: #a78bfa;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 10px;
  font-weight: 600;
}
</style>
