<template>
  <aside class="analysis-panel">
    <!-- 头部 -->
    <header class="analysis-header">
      <h1 class="analysis-header-title">
        <IconLibrary name="analysis" :size="20" />
        <span>写作范式分析</span>
      </h1>
      <span class="badge badge-primary">Pro版</span>
    </header>

    <!-- 标签页切换 -->
    <div class="analysis-tabs">
        <button
          :class="['analysis-tab', activeTab === 'paradigms' ? 'active' : '']"
          @click="activeTab = 'paradigms'"
        >
          <IconLibrary name="folder" :size="16" class="mr-1.5" />
          <span>范式库</span>
        </button>
        <button
          :class="['analysis-tab', activeTab === 'tools' ? 'active' : '']"
          @click="activeTab = 'tools'"
        >
          <IconLibrary name="search" :size="16" class="mr-1.5" />
          <span>分析工具</span>
        </button>
      </div>

      <!-- 内容区 -->
      <div class="analysis-content">
        <!-- 写作范式库 -->
        <section v-show="activeTab === 'paradigms'" class="analysis-section">
          <div class="flex items-center justify-between mb-4">
            <span class="text-xs text-muted">{{ paradigms.length }} 个范式</span>
            <div class="flex items-center gap-2">
              <button
                @click="openRequirementParser"
                class="btn btn-analysis btn-primary flex items-center gap-1.5"
                title="根据需求文档自动提取范式"
              >
                <IconLibrary name="sparkles" :size="14" />
                <span>AI 提取</span>
              </button>
              <button
                @click="openAddModal"
                class="btn btn-analysis btn-success flex items-center gap-1"
              >
                <span>+</span> 新增
              </button>
            </div>
          </div>

          <div class="space-y-3">
            <div
            v-for="paradigm in paradigms"
            :key="paradigm.id"
            @click="selectParadigm(paradigm)"
            :class="['paradigm-card', { 'selected': selectedParadigm?.id === paradigm.id }]"
          >
            <div class="paradigm-card-header">
              <h4 class="paradigm-card-title">
                <IconLibrary :name="paradigm.icon" :size="16" class="shrink-0" />
                {{ paradigm.name }}
                <span v-if="paradigm.isNew" class="badge-new animate-pulse">NEW</span>
                <span v-if="isCustomParadigm(paradigm)" class="badge-custom">自定义</span>
                <span v-if="paradigm.createdAt" class="text-[10px] text-muted ml-auto opacity-70">
                  {{ formatDate(paradigm.createdAt) }}
                </span>
              </h4>
              <div class="flex items-center gap-1">
                <button
                  @click.stop="openEditModal(paradigm)"
                  class="btn-action"
                  title="编辑范式"
                  aria-label="编辑范式"
                >
                  <IconLibrary name="edit" :size="14" />
                </button>
                <button
                  v-if="isCustomParadigm(paradigm)"
                  @click.stop="deleteParadigm(paradigm)"
                  class="btn-action danger"
                  title="删除范式"
                  aria-label="删除范式"
                >
                  <IconLibrary name="trash" :size="14" />
                </button>
                <button
                  v-if="selectedParadigm?.id === paradigm.id"
                  @click.stop="applyParadigm(paradigm)"
                  class="btn-action btn-action-text primary"
                >
                  应用到写作
                </button>
              </div>
            </div>
            <p class="text-xs text-muted mb-2">{{ paradigm.description }}</p>
            <div class="flex flex-wrap gap-1">
              <span
                v-for="tag in paradigm.tags"
                :key="tag"
                :class="['text-xs px-2 py-1 rounded', paradigm.tagClass]"
              >
                {{ tag }}
              </span>
            </div>
          </div>
          </div>
        </section>

        <!-- 范式分析工具 -->
        <section v-show="activeTab === 'tools'" class="analysis-section">
          <h3 class="text-sm font-medium text-secondary mb-4 flex items-center gap-2">
            <IconLibrary name="search" :size="16" />
            <span>范式分析工具</span>
          </h3>
          <textarea
            v-model="analysisText"
            class="analysis-textarea"
            placeholder="粘贴文章内容，分析其写作范式..."
          ></textarea>
          <div class="flex gap-2 mt-2">
            <button
              @click="analyzeArticle"
              :disabled="isAnalyzing || !analysisText"
              class="btn btn-analysis primary flex-1"
            >
              {{ isAnalyzing ? '正在分析...' : '分析文章范式' }}
            </button>
            <button
              @click="clearAnalysis"
              class="btn btn-analysis secondary"
            >
              清空
            </button>
          </div>

          <!-- 分析历史 -->
          <div v-if="analysisHistory.length > 0" class="mt-6">
            <h4 class="text-xs font-medium text-muted mb-3 flex items-center gap-2">
              <IconLibrary name="edit" :size="14" />
              <span>分析历史</span>
            </h4>
            <div class="space-y-2">
              <div
                v-for="(item, index) in analysisHistory"
                :key="index"
                @click="loadHistoryItem(item)"
                class="history-item"
              >
                <div class="flex justify-between items-center">
                  <span class="text-secondary">{{ item.paradigm }}</span>
                  <span class="text-muted">{{ formatDate(item.timestamp) }}</span>
                </div>
                <p class="text-muted mt-1 truncate">{{ item.preview }}</p>
              </div>
            </div>
          </div>
        </section>
    </div>

    <!-- 需求解析面板 -->
    <RequirementParserPanel
      v-if="showRequirementParser"
      @close="showRequirementParser = false"
      @paradigm-created="handleParadigmCreated"
    />
  </aside>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useAppStore } from '../stores/app'
import { useDatabaseStore } from '../stores/database.js'
import DeepSeekAPI from '../api/deepseek.js'
import { getParadigmList } from '../config/paradigms.js'
import RequirementParserPanel from './RequirementParserPanel.vue'
import IconLibrary from './icons/IconLibrary.vue'

const appStore = useAppStore()
const { analysisText, isAnalyzing } = storeToRefs(appStore)

// 数据库 Store
const dbStore = useDatabaseStore()
const { isInitialized: dbInitialized } = storeToRefs(dbStore)

// 选中的范式
const selectedParadigm = ref(null)

// 分析历史
const analysisHistory = ref([])

// 范式列表（响应式，支持编辑）
const paradigms = ref([])

const showEditModal = ref(false)
const isAddMode = ref(false)
const editingParadigmId = ref(null)
const showRequirementParser = ref(false)
const activeTab = ref('paradigms') // 'paradigms' or 'tools'

// 编辑表单
const editForm = reactive({
  icon: 'edit',
  name: '',
  description: '',
  tagsInput: '',
  tagClass: 'bg-blue-900/30 text-blue-300',
  // ⭐ 核心字段：完整 Prompt
  specializedPrompt: ''
})

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

// 颜色选项
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 initParadigms = () => {
  // 先加载默认范式
  const defaultParadigms = getParadigmList()
  
  // 从本地存储加载自定义修改
  const savedCustomizations = localStorage.getItem('paradigmCustomizations')
  const customizations = savedCustomizations ? JSON.parse(savedCustomizations) : {}
  
  // 从本地存储加载自定义范式
  const savedCustomParadigms = localStorage.getItem('customParadigms')
  const customParadigms = savedCustomParadigms ? JSON.parse(savedCustomParadigms) : []
  
  // 合并默认范式和自定义修改
  const mergedParadigms = defaultParadigms.map(p => {
    if (customizations[p.id]) {
      return { ...p, ...customizations[p.id] }
    }
    return p
  })
  
  // 添加自定义范式
  paradigms.value = [...mergedParadigms, ...customParadigms]
}

// 打开新增（在右侧面板显示）
const openAddModal = () => {
  // 更新 app store 中的编辑状态
  appStore.paradigmEditState.isEditing = true
  appStore.paradigmEditState.isAddMode = true
  appStore.paradigmEditState.editingParadigmId = null
  
  // 重置表单
  const form = appStore.paradigmEditState.editForm
  form.icon = 'edit'
  form.name = ''
  form.description = ''
  form.tagsInput = ''
  form.tagClass = 'bg-blue-900/30 text-blue-300'
  form.specializedPrompt = ''
}

// 打开需求解析面板
const openRequirementParser = () => {
  showRequirementParser.value = true
}

// 处理 AI 解析创建的范式
const handleParadigmCreated = (paradigm) => {
  // 刷新列表以显示新范式
  initParadigms()
  showRequirementParser.value = false
  // 自动选中新创建的范式
  const newRef = paradigms.value.find(p => p.id === paradigm.id)
  if (newRef) {
    selectParadigm(newRef)
  }
}

// 打开编辑（在右侧面板显示）
const openEditModal = (paradigm) => {
  // 更新 app store 中的编辑状态
  appStore.paradigmEditState.isEditing = true
  appStore.paradigmEditState.isAddMode = false
  appStore.paradigmEditState.editingParadigmId = paradigm.id
  
  // 填充表单数据
  const form = appStore.paradigmEditState.editForm
  form.icon = paradigm.icon || 'edit'
  form.name = paradigm.name || ''
  form.description = paradigm.description || ''
  form.tagsInput = (paradigm.tags || []).join(', ')
  form.tagClass = paradigm.tagClass || 'bg-blue-900/30 text-blue-300'
  form.specializedPrompt = paradigm.specializedPrompt || ''
}


// 关闭弹窗
const closeEditModal = () => {
  showEditModal.value = false
  resetEditForm()
}

// 重置表单
const resetEditForm = () => {
  editForm.icon = 'edit'
  editForm.name = ''
  editForm.description = ''
  editForm.tagsInput = ''
  editForm.tagClass = 'bg-blue-900/30 text-blue-300'
  // ⭐ 核心字段重置
  editForm.specializedPrompt = ''
}



// 保存范式
const saveParadigm = () => {
  const tags = editForm.tagsInput.split(',').map(t => t.trim()).filter(t => t)
  
  if (isAddMode.value) {
    // 新增自定义范式
    const newParadigm = {
      id: `custom-${Date.now()}`,
      icon: editForm.icon,
      name: editForm.name,
      description: editForm.description || editForm.specializedPrompt.substring(0, 100) + '...',
      tags,
      tagClass: editForm.tagClass,
      isCustom: true,
      createdAt: new Date().toISOString(),
      // ⭐ 核心字段：完整 Prompt
      specializedPrompt: editForm.specializedPrompt
    }
    
    paradigms.value.push(newParadigm)
    
    // 保存到本地存储
    const savedCustomParadigms = localStorage.getItem('customParadigms')
    const customParadigms = savedCustomParadigms ? JSON.parse(savedCustomParadigms) : []
    customParadigms.push(newParadigm)
    localStorage.setItem('customParadigms', JSON.stringify(customParadigms))
  } else {
    // 编辑现有范式
    const index = paradigms.value.findIndex(p => p.id === editingParadigmId.value)
    if (index !== -1) {
      const updatedParadigm = {
        ...paradigms.value[index],
        icon: editForm.icon,
        name: editForm.name,
        description: editForm.description,
        tags,
        tagClass: editForm.tagClass,
        // ⭐ 核心字段：完整 Prompt
        specializedPrompt: editForm.specializedPrompt
      }
      
      paradigms.value[index] = updatedParadigm
      
      // 根据是否是自定义范式决定存储位置
      if (updatedParadigm.isCustom) {
        // 更新自定义范式
        const savedCustomParadigms = localStorage.getItem('customParadigms')
        const customParadigms = savedCustomParadigms ? JSON.parse(savedCustomParadigms) : []
        const customIndex = customParadigms.findIndex(p => p.id === editingParadigmId.value)
        if (customIndex !== -1) {
          customParadigms[customIndex] = updatedParadigm
          localStorage.setItem('customParadigms', JSON.stringify(customParadigms))
        }
      } else {
        // 保存对默认范式的自定义修改
        const savedCustomizations = localStorage.getItem('paradigmCustomizations')
        const customizations = savedCustomizations ? JSON.parse(savedCustomizations) : {}
        customizations[editingParadigmId.value] = {
          icon: editForm.icon,
          name: editForm.name,
          description: editForm.description,
          tags,
          tagClass: editForm.tagClass,
          specializedPrompt: editForm.specializedPrompt
        }
        localStorage.setItem('paradigmCustomizations', JSON.stringify(customizations))
      }
    }
  }
  
  closeEditModal()
}

// 判断范式是否为自定义（兼容旧数据）
const isCustomParadigm = (paradigm) => {
  // 优先检查 isCustom 字段
  if (paradigm.isCustom) return true
  // 兼容旧数据：检查 type 字段或 id 前缀
  if (paradigm.type === 'custom') return true
  if (paradigm.id && paradigm.id.startsWith('custom-')) return true
  return false
}

// 删除自定义范式
const deleteParadigm = (paradigm) => {
  if (!isCustomParadigm(paradigm)) return
  
  if (!confirm(`确定要删除"${paradigm.name}"吗？`)) return
  
  // 从列表中移除
  paradigms.value = paradigms.value.filter(p => p.id !== paradigm.id)
  
  // 从本地存储中移除
  const savedCustomParadigms = localStorage.getItem('customParadigms')
  const customParadigms = savedCustomParadigms ? JSON.parse(savedCustomParadigms) : []
  const filtered = customParadigms.filter(p => p.id !== paradigm.id)
  localStorage.setItem('customParadigms', JSON.stringify(filtered))
  
  // 如果正在选中该范式，清除选中状态
  if (selectedParadigm.value?.id === paradigm.id) {
    selectedParadigm.value = null
  }
}

// 选择范式
const selectParadigm = (paradigm) => {
  selectedParadigm.value = paradigm
}

// 应用范式到写作（使用新的 loadParadigmPreset 方法）
const applyParadigm = (paradigm) => {
  appStore.loadParadigmPreset(paradigm.id)
  
  // 显示提示
  alert(`已应用"${paradigm.name}"到写作任务`)
}

// 分析文章
const analyzeArticle = async () => {
  try {
    const result = await appStore.analyzeArticleAction(analysisText.value, detectParadigm)
    // 添加到历史记录
    addToHistory(result.paradigm, analysisText.value, result.content)
  } catch (error) {
    alert(error.message)
  }
}

// 检测文章范式
const detectParadigm = (analysis) => {
  const text = analysis.toLowerCase()
  const list = paradigms.value
  
  // 根据 id 查找范式
  const findById = (id) => list.find(p => p.id === id)
  
  if (text.includes('民主生活会') || text.includes('对照检查') || text.includes('整改') || text.includes('党性')) {
    return findById('party-review') || list[0]
  } else if (text.includes('政府') || text.includes('工作报告') || text.includes('述职')) {
    return findById('gov-report') || list[0]
  } else if (text.includes('技术') || text.includes('代码') || text.includes('编程')) {
    return findById('tech') || list[0]
  } else if (text.includes('商业') || text.includes('市场') || text.includes('数据分析')) {
    return findById('business') || list[0]
  } else if (text.includes('产品') || text.includes('营销') || text.includes('用户')) {
    return findById('marketing') || list[0]
  } else if (text.includes('学术') || text.includes('研究') || text.includes('文献')) {
    return findById('academic') || list[0]
  }
  
  return list[0] // 默认第一个范式
}

// 添加到历史记录
const addToHistory = (paradigm, text, analysis) => {
  const historyItem = {
    paradigm,
    text,
    analysis,
    preview: text.substring(0, 50) + '...',
    timestamp: new Date()
  }
  
  // 限制历史记录数量
  analysisHistory.value.unshift(historyItem)
  if (analysisHistory.value.length > 10) {
    analysisHistory.value = analysisHistory.value.slice(0, 10)
  }
  
  // 保存到本地存储
  localStorage.setItem('analysisHistory', JSON.stringify(analysisHistory.value))
}

// 加载历史记录项
const loadHistoryItem = (item) => {
  analysisText.value = item.text
  appStore.analysisResult = {
    paradigm: item.paradigm,
    analysis: item.analysis,
    timestamp: item.timestamp
  }
}

// 清空分析
const clearAnalysis = () => {
  analysisText.value = ''
  appStore.analysisResult = null
  selectedParadigm.value = null
}

// 格式化日期
const formatDate = (date) => {
  const now = new Date()
  const diff = now - new Date(date)
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(diff / 3600000)
  const days = Math.floor(diff / 86400000)
  
  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`
  
  return new Date(date).toLocaleDateString()
}

// 返回上一页
const goBack = () => {
  appStore.setCurrentPage('writer')
}

// 监听保存事件并刷新
const handleParadigmSaved = () => {
  initParadigms()
}

// 组件挂载时加载历史记录和范式列表
onMounted(() => {
  // 初始化范式列表
  initParadigms()
  
  // 加载分析历史
  const saved = localStorage.getItem('analysisHistory')
  if (saved) {
    analysisHistory.value = JSON.parse(saved)
  }
  
  // 监听保存事件
  window.addEventListener('paradigm-saved', handleParadigmSaved)
})

onUnmounted(() => {
  window.removeEventListener('paradigm-saved', handleParadigmSaved)
})
</script>

<style scoped>
/* ========== 侧边栏面板 ========== */
.analysis-panel {
  width: 400px;
  display: flex;
  flex-direction: column;
  border-right: 1px solid var(--border-default);
  background: var(--bg-secondary);
  flex-shrink: 0;
  height: 100vh;
}

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

.analysis-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);
}

/* 返回按钮 */
.back-btn {
  padding: var(--space-2) var(--space-3);
  font-size: var(--text-sm);
  color: var(--text-muted);
  background: var(--bg-elevated);
  border: 1px solid var(--border-default);
  border-radius: var(--radius-md);
  cursor: pointer;
  transition: all var(--transition-fast);
}

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

/* 标签页 */
.analysis-tabs {
  display: flex;
  border-bottom: 1px solid var(--border-default);
  flex-shrink: 0;
}

.analysis-tab {
  flex: 1;
  padding: var(--space-3);
  font-size: var(--text-sm);
  color: var(--text-muted);
  background: transparent;
  border: none;
  cursor: pointer;
  transition: all var(--transition-fast);
  display: flex;
  align-items: center;
  justify-content: center;
}

.analysis-tab:hover {
  color: var(--text-primary);
  background: var(--bg-elevated);
}

.analysis-tab.active {
  color: var(--accent-primary);
  background: var(--bg-primary);
  border-bottom: 2px solid var(--accent-primary);
}

/* 内容区 */
.analysis-content {
  flex: 1;
  overflow-y: auto;
  padding: var(--space-4);
}

.analysis-section {
  margin-bottom: var(--space-6);
}

.analysis-section:last-child {
  margin-bottom: 0;
}

/* 右侧编辑面板内容 */
.edit-panel-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

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

.edit-panel-title {
  font-weight: var(--font-semibold);
  font-size: var(--text-lg);
  color: var(--text-primary);
}

.close-btn {
  padding: var(--space-2);
  font-size: var(--text-lg);
  color: var(--text-muted);
  background: transparent;
  border: none;
  cursor: pointer;
  transition: all var(--transition-fast);
}

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

.edit-panel-body {
  flex: 1;
  overflow-y: auto;
  padding: var(--space-6);
}

.edit-field {
  margin-bottom: var(--space-5);
}

.edit-field.prompt-field {
  flex: 1;
  display: flex;
  flex-direction: column;
}

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

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

.edit-input:focus {
  outline: none;
  border-color: var(--accent-primary);
}

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

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

/* 模态弹窗 */
.paradigm-modal-backdrop {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.paradigm-modal {
  width: 560px;
  max-width: 90vw;
  max-height: 85vh;
  background: var(--bg-secondary);
  border-radius: var(--radius-lg);
  border: 1px solid var(--border-default);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

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

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

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

/* 范式卡片 */
.paradigm-card {
  background: var(--bg-elevated);
  border-radius: var(--radius-lg);
  padding: var(--space-4);
  border: 1px solid var(--border-default);
  transition: all var(--transition-fast);
  cursor: pointer;
}

.paradigm-card:hover {
  border-color: var(--accent-primary);
}

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

.paradigm-card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: var(--space-2);
}

.paradigm-card-title {
  font-weight: var(--font-medium);
  color: var(--text-primary);
  display: flex;
  align-items: center;
  gap: var(--space-2);
}

/* 徽章 */
.badge-new {
  font-size: 10px;
  padding: 2px 6px;
  border-radius: var(--radius-sm);
  background: var(--accent-warning);
  color: var(--text-inverse);
  font-weight: var(--font-semibold);
}

.badge-custom {
  font-size: 10px;
  padding: 2px 6px;
  border-radius: var(--radius-sm);
  background: #a855f7;
  color: var(--text-inverse);
  font-weight: var(--font-semibold);
}

/* 分析历史项 */
.history-item {
  background: var(--bg-elevated);
  border-radius: var(--radius-md);
  padding: var(--space-3);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.history-item:hover {
  background: var(--bg-sunken);
}

/* 模态框 */
.paradigm-modal-backdrop {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: var(--z-modal-backdrop);
}

.paradigm-modal {
  background: var(--bg-secondary);
  border-radius: var(--radius-lg);
  width: 500px;
  max-height: 80vh;
  overflow-y: auto;
  border: 1px solid var(--border-default);
  box-shadow: var(--shadow-lg);
}

/* 图标选择器 */
.icon-selector {
  display: flex;
  gap: var(--space-2);
  flex-wrap: wrap;
}

.icon-option {
  width: 40px;
  height: 40px;
  border-radius: var(--radius-lg);
  font-size: var(--text-xl);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all var(--transition-fast);
}

.icon-option.selected {
  background: var(--accent-primary);
}

.icon-option:not(.selected) {
  background: var(--bg-elevated);
}

.icon-option:not(.selected):hover {
  background: var(--bg-sunken);
}

/* 颜色选择器 */
.color-option {
  padding: var(--space-1) var(--space-3);
  border-radius: var(--radius-md);
  font-size: var(--text-xs);
  transition: all var(--transition-fast);
}

.color-option.selected {
  box-shadow: 0 0 0 2px var(--text-primary);
}

/* 输入框 */
.analysis-input {
  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);
}

.analysis-input:focus {
  outline: none;
  border-color: var(--accent-primary);
  box-shadow: 0 0 0 2px var(--info-bg);
}

.analysis-textarea {
  width: 100%;
  height: 128px;
  background: var(--bg-primary);
  border: 1px solid var(--border-default);
  border-radius: var(--radius-lg);
  padding: var(--space-3);
  font-size: var(--text-sm);
  resize: none;
}

.analysis-textarea:focus {
  outline: none;
  border-color: var(--accent-primary);
  box-shadow: 0 0 0 2px var(--info-bg);
}

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

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

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

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

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

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

.btn-action {
  font-size: var(--text-xs);
  padding: var(--space-2);
  background: var(--bg-sunken); /* 统一使用较深背景，确保在所有状态下可见 */
  color: var(--text-primary);
  border-radius: var(--radius-md);
  transition: all var(--transition-fast);
  border: 1px solid var(--border-default);
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
}

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

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

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

/* 带文字的动作按钮（自适应宽度） */
.btn-action.btn-action-text {
  width: auto;
  height: auto;
  padding: var(--space-2) var(--space-3);
  white-space: nowrap;
}

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

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

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

.btn-action.success:hover {
  opacity: 0.9;
}
</style>
