<template>
  <section class="doc-card" :class="{ 'is-collapsed': collapsedState }">
    <header class="doc-card__header">
      <div class="doc-card__badge">{{ typeLabel }}</div>
      <div class="doc-card__meta">
        <div class="doc-card__name">{{ docName }}</div>
        <div class="doc-card__time">{{ displayTime }}</div>
      </div>
      <div class="doc-card__actions">
        <button type="button" class="doc-card__btn" :title="'压缩文档'" @click="handleCompress">
          <svg v-if="compressState === 'idle' || compressState === 'completed'" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M4 14h6v7H4z"/>
            <path d="M14 9h6v12h-6z"/>
            <path d="M4 9h6v5H4z"/>
          </svg>
          <span v-if="compressState === 'queued' || compressState === 'processing'" class="doc-card__spinner"></span>
          <svg v-else-if="compressState === 'error'" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <circle cx="12" cy="12" r="10"/>
            <line x1="15" y1="9" x2="9" y2="15"/>
            <line x1="9" y1="9" x2="15" y2="15"/>
          </svg>
        </button>
        <span v-if="compressState === 'queued'" class="doc-card__status-label">排队中</span>
        <button type="button" class="doc-card__btn" :title="collapsedState ? '展开文件' : '折叠文件'" @click="toggleCollapse">
          <svg v-if="collapsedState" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <polyline points="9 18 15 12 9 6"/>
          </svg>
          <svg v-else width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <polyline points="6 9 12 15 18 9"/>
          </svg>
        </button>
        <button type="button" class="doc-card__btn doc-card__btn--danger" title="删除文件" @click="props.onDelete?.()">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M3 6h18"/>
            <path d="M8 6V4h8v2"/>
            <path d="M19 6l-1 14H6L5 6"/>
            <path d="M10 11v6"/>
            <path d="M14 11v6"/>
          </svg>
        </button>
      </div>
    </header>
    <div v-show="!collapsedState" class="doc-card__body">
      <div ref="editorRoot" class="doc-card__editor"></div>
    </div>
  </section>
</template>

<script setup>
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { replaceAll } from '@milkdown/kit/utils'
import { Crepe } from '@milkdown/crepe'
import { editorViewCtx } from '@milkdown/kit/core'
import { copilotPlugin, copilotConfigCtx, copilotGhostMark, setCopilotEnabled, clearGhostSuggestion } from '../plugins/copilotPlugin'
import { hiddenTextInputPlugin, hiddenTextNode, hiddenTextRemark, hiddenTextView } from '../plugins/hiddenTextPlugin'
import { fetchSuggestion, submitCompress, pollCompressStatus } from '../utils/api.js'
import { isDocumentVisible, getRecommendedDebounce, getRecommendedSyncInterval } from '../composables/useVisibility.js'

const COPILOT_TOGGLE_EVENT = 'llm-in-text:copilot-toggle'
const props = defineProps({
  docType: { type: String, default: 'txt' },
  docName: { type: String, default: 'document.txt' },
  uploadTime: { type: String, default: '' },
  content: { type: String, default: '' },
  collapsed: { type: Boolean, default: false },
  resolveSuggestionRequest: { type: Function, default: null },
  onUpdateContent: { type: Function, default: null },
  onUpdateCollapsed: { type: Function, default: null },
  onDelete: { type: Function, default: null },
  onCompress: { type: Function, default: null },
})

const editorRoot = ref(null)
const collapsedState = ref(Boolean(props.collapsed))
const currentContent = ref(props.content || '')
const compressState = ref('idle') // idle | queued | processing | error
let crepe = null
let syncTimer = null
let syncingExternal = false
let compressPoller = null
let copilotToggleHandler = null

const handleCompress = () => {
  if (compressState.value !== 'idle') return

  // 直接从嵌套编辑器获取最新内容，不依赖外部同步缓存
  const content = crepe?.getMarkdown() || ''
  if (!content.trim()) {
    compressState.value = 'error'
    setTimeout(() => { compressState.value = 'idle' }, 2000)
    return
  }

  submitCompress(content, props.docType).then((result) => {
    compressState.value = 'queued'

    if (compressPoller) compressPoller.stop()
    compressPoller = pollCompressStatus(result.task_id, (status, compressedContent, message) => {
      compressState.value = status

      if (status === 'completed') {
        // 压缩完成，直接更新嵌套编辑器的内容
        crepe.editor.action(replaceAll(compressedContent))
      } else if (status === 'error') {
        setTimeout(() => { compressState.value = 'idle' }, 3000)
      }
    })

    if (compressState.value === 'queued') {
      // Task already completed before polling started
    }
  }).catch(() => {
    compressState.value = 'error'
    setTimeout(() => { compressState.value = 'idle' }, 3000)
  })
}

const typeLabel = computed(() => {
  if (props.docType === 'docx') return 'DOCX'
  if (props.docType === 'pptx') return 'PPTX'
  if (props.docType === 'pdf') return 'PDF'
  return 'TXT'
})

const displayTime = computed(() => {
  if (!props.uploadTime) return '刚上传'
  const date = new Date(props.uploadTime)
  if (Number.isNaN(date.getTime())) return '刚上传'
  return date.toLocaleString('zh-CN', { hour12: false })
})

const toggleCollapse = () => {
  collapsedState.value = !collapsedState.value
  props.onUpdateCollapsed?.(collapsedState.value)
}

const syncContent = () => {
  if (!crepe) return
  // Skip content sync when tab is hidden (energy saving for nested editors)
  if (!isDocumentVisible()) return
  
  // Don't sync during compression to avoid overwriting compressed content
  if (compressState.value !== 'idle') return
  
  if (syncTimer) clearTimeout(syncTimer)
  const syncInterval = getRecommendedSyncInterval(120)
  syncTimer = setTimeout(async () => {
    if (!crepe || syncingExternal) return
    const markdown = await crepe.getMarkdown()
    currentContent.value = markdown
    props.onUpdateContent?.(markdown)
  }, syncInterval)
}

const syncExternalContent = async (nextValue) => {
  const value = nextValue || ''
  
  // Reject empty content to prevent accidental document clearing (e.g., from failed compression)
  if (!value || !value.trim()) {
    return
  }
  
  if (!crepe) {
    currentContent.value = value
    return
  }
  if (value === currentContent.value) return
  
  // Clear pending sync timer to prevent stale content from overwriting new content
  if (syncTimer) {
    clearTimeout(syncTimer)
    syncTimer = null
  }
  
  syncingExternal = true
  try {
    crepe.editor.action(replaceAll(value))
    currentContent.value = value
  } finally {
    syncingExternal = false
  }
}

watch(() => props.content, (nextValue) => {
  void syncExternalContent(nextValue)
})

watch(() => props.collapsed, (nextValue) => {
  collapsedState.value = Boolean(nextValue)
})

onMounted(async () => {
  if (!editorRoot.value) return
  crepe = new Crepe({
    root: editorRoot.value,
    defaultValue: props.content || '',
    features: {
      [Crepe.Feature.Latex]: true,
      [Crepe.Feature.ImageBlock]: true,
      [Crepe.Feature.Table]: true,
      [Crepe.Feature.ListCheck]: true,
    },
    config: {
      showLineNumber: false,
    },
  })

  crepe.editor.config((ctx) => {
    ctx.set(copilotConfigCtx.key, {
      fetchSuggestion: async (prefix, suffix, languageId, signal) => {
        const payload = props.resolveSuggestionRequest
          ? await props.resolveSuggestionRequest({ prefix, suffix, languageId })
          : { prefix, suffix, languageId, blocked: false }
        if (payload?.blocked) return ''
        return fetchSuggestion(payload?.prefix ?? prefix, payload?.suffix ?? suffix, payload?.languageId ?? languageId, signal)
      },
      debounceMs: getRecommendedDebounce(900),
    })
  })

  crepe.editor.use(copilotConfigCtx)
  crepe.editor.use(copilotGhostMark)
  crepe.editor.use(copilotPlugin)
  crepe.editor.use(hiddenTextRemark)
  crepe.editor.use(hiddenTextNode)
  crepe.editor.use(hiddenTextView)
  crepe.editor.use(hiddenTextInputPlugin)
  await crepe.create()

  crepe.on((listener) => {
    listener.updated(() => {
      syncContent()
    })
  })

  crepe.editor.action((ctx) => {
    const view = ctx.get(editorViewCtx)
    const enabled = typeof window !== 'undefined'
      ? window.__LLM_IN_TEXT_COPILOT_ENABLED__ !== false
      : true
    setCopilotEnabled(view, enabled)
    if (!enabled) {
      clearGhostSuggestion(view)
    }
  })

  copilotToggleHandler = (event) => {
    const enabled = Boolean(event?.detail?.enabled)
    crepe?.editor?.action((ctx) => {
      const view = ctx.get(editorViewCtx)
      setCopilotEnabled(view, enabled)
      if (!enabled) {
        clearGhostSuggestion(view)
      }
    })
  }
  window.addEventListener(COPILOT_TOGGLE_EVENT, copilotToggleHandler)
})

onUnmounted(() => {
  if (syncTimer) {
    clearTimeout(syncTimer)
    syncTimer = null
  }
  if (compressPoller) {
    compressPoller.stop()
    compressPoller = null
  }
  if (copilotToggleHandler) {
    window.removeEventListener(COPILOT_TOGGLE_EVENT, copilotToggleHandler)
    copilotToggleHandler = null
  }
  if (crepe) {
    crepe.editor.action((ctx) => {
      const view = ctx.get(editorViewCtx)
      clearGhostSuggestion(view)
    })
    crepe.destroy()
    crepe = null
  }
})
</script>

<style scoped>
.doc-card {
  width: 100%;
  max-width: 100%;
  margin: 8px 0;
  border-radius: 12px;
  border: 1px solid rgba(59, 130, 246, 0.12);
  background: rgba(255, 255, 255, 0.8);
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.06), 0 1px 3px rgba(0, 0, 0, 0.04);
  overflow: hidden;
  backdrop-filter: blur(10px);
  position: relative;
}

:root[data-theme='dark'] .doc-card {
  background: rgba(26, 30, 39, 0.8);
  border-color: rgba(96, 165, 250, 0.15);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3), 0 1px 3px rgba(0, 0, 0, 0.2);
}

.doc-card__header {
  display: grid;
  grid-template-columns: auto minmax(0, 1fr) auto;
  gap: 10px;
  align-items: center;
  padding: 8px 12px;
  border-bottom: 1px solid rgba(59, 130, 246, 0.1);
  background: rgba(255, 255, 255, 0.8);
}

:root[data-theme='dark'] .doc-card__header {
  background: rgba(26, 30, 39, 0.8);
  border-bottom-color: rgba(96, 165, 250, 0.15);
}

.doc-card__badge {
  min-width: 48px;
  padding: 4px 10px;
  border-radius: 999px;
  background: linear-gradient(135deg, #3b82f6 0%, #60a5fa 100%);
  color: #fff;
  font-size: 10px;
  font-weight: 600;
  letter-spacing: 0.08em;
  text-align: center;
  box-shadow: 0 2px 6px rgba(59, 130, 246, 0.2);
}

.doc-card__meta {
  min-width: 0;
}

.doc-card__name {
  color: #1e293b;
  font-size: 13px;
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

:root[data-theme='dark'] .doc-card__name {
  color: #e5e7eb;
}

.doc-card__time {
  margin-top: 2px;
  color: #64748b;
  font-size: 10px;
}

:root[data-theme='dark'] .doc-card__time {
  color: #aeb6c5;
}

.doc-card__actions {
  display: flex;
  gap: 4px;
  align-items: center;
}

.doc-card__status-label {
  font-size: 10px;
  color: #f59e0b;
  white-space: nowrap;
}

.doc-card__spinner {
  width: 14px;
  height: 14px;
  border: 2px solid rgba(59, 130, 246, 0.2);
  border-top-color: #3b82f6;
  border-radius: 50%;
  animation: doc-card-spin 0.6s linear infinite;
}

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

.doc-card__btn {
  width: 26px;
  height: 26px;
  border: 1px solid rgba(59, 130, 246, 0.12);
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.5);
  color: #64748b;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.15s ease;
}

:root[data-theme='dark'] .doc-card__btn {
  background: rgba(34, 40, 52, 0.5);
  border-color: rgba(96, 165, 250, 0.15);
  color: #aeb6c5;
}

.doc-card__btn:hover {
  background: rgba(59, 130, 246, 0.1);
  border-color: rgba(59, 130, 246, 0.25);
  color: #3b82f6;
}

.doc-card__btn--danger:hover {
  background: rgba(239, 68, 68, 0.1);
  border-color: rgba(239, 68, 68, 0.2);
  color: #ef4444;
}

.doc-card__body {
  padding: 8px 10px;
  background: rgba(248, 250, 252, 0.8);
}

:root[data-theme='dark'] .doc-card__body {
  background: rgba(18, 22, 30, 0.8);
}

.doc-card__editor {
  min-height: 0;
  height: auto;
  max-height: none;
  overflow: auto;
  overscroll-behavior-y: contain;
  scrollbar-width: thin;
  scrollbar-color: var(--scrollbar-thumb) transparent;
  border-radius: 8px;
  border: 1px solid rgba(59, 130, 246, 0.08);
  background: rgba(255, 255, 255, 0.8);
}

:root[data-theme='dark'] .doc-card__editor {
  background: rgba(26, 30, 39, 0.8);
  border-color: rgba(96, 165, 250, 0.12);
}

.doc-card__editor :deep(.milkdown) {
  background: transparent !important;
  min-height: 0;
  height: auto !important;
}

.doc-card__editor :deep(.milkdown__main),
.doc-card__editor :deep(.milkdown__editor) {
  margin: 0 !important;
  padding: 0 !important;
  min-height: 0;
  height: auto !important;
}

.doc-card__editor :deep(.ProseMirror) {
  min-height: 0;
  height: auto !important;
  overflow-x: hidden;
  padding: 10px 12px 12px !important;
  font-size: 13px !important;
  line-height: 1.6;
}

.doc-card__editor :deep(.ProseMirror > *:last-child) {
  margin-bottom: 0;
}

.doc-card__editor :deep(.ProseMirror img) {
  max-width: min(100%, 520px);
  height: auto;
}

.doc-card__editor :deep(.ProseMirror p:first-child) {
  margin-top: 0;
}

.doc-card__editor :deep(.cm-scroller) {
  overflow-x: hidden;
  overflow-y: auto;
  overscroll-behavior-y: contain;
  scrollbar-width: thin;
  scrollbar-color: var(--scrollbar-thumb) transparent;
}

.doc-card__editor :deep(.cm-editor) {
  min-height: 0;
  height: 100%;
  overflow: hidden;
}

.doc-card__editor :deep(.milkdown__toolbar),
.doc-card__editor :deep(.milkdown__menu),
.doc-card__editor :deep(.milkdown__statusbar),
.doc-card__editor :deep(.milkdown-slate-toolbar),
.doc-card__editor :deep(.milkdown-bubble-menu) {
  display: none !important;
}
</style>
