<template>
  <div class="translation-editor">
    <div class="translation-editor__toolbar">
      <div class="translation-editor__toolbar-group">
        <button type="button" class="translation-editor__btn" :class="{ 'is-active': editor?.isActive('heading', { level: 1 }) }" @click="setHeading(1)">H1</button>
        <button type="button" class="translation-editor__btn" :class="{ 'is-active': editor?.isActive('heading', { level: 2 }) }" @click="setHeading(2)">H2</button>
        <button type="button" class="translation-editor__btn" :class="{ 'is-active': editor?.isActive('heading', { level: 3 }) }" @click="setHeading(3)">H3</button>
        <button type="button" class="translation-editor__btn" :class="{ 'is-active': editor?.isActive('bulletList') }" @click="toggleBulletList">列表</button>
        <button type="button" class="translation-editor__btn" @click="insertParagraphAfter">新增段落</button>
        <button type="button" class="translation-editor__btn" @click="deleteCurrentBlock">删除段落</button>
        <button type="button" class="translation-editor__btn" @click="insertTable">表格</button>
      </div>
      <div class="translation-editor__toolbar-group">
        <span class="translation-editor__hint">块数 {{ blockCount }}</span>
        <span class="translation-editor__hint">只读块 {{ readonlyBlockCount }} 个</span>
      </div>
    </div>
    <div class="translation-editor__content">
      <div class="translation-editor__page-hint">当前联动页：第 {{ activePage }} 页</div>
      <div v-for="block in readonlyBlocks" :key="block.id" class="translation-editor__readonly-block">
        <div class="translation-editor__readonly-label">只读块 · {{ block.semanticType }}</div>
        <div class="translation-editor__readonly-text">{{ block.displayText || block.text || '未识别内容' }}</div>
      </div>
      <EditorContent v-if="editor" :editor="editor" />
    </div>
  </div>
</template>

<script setup>
import { onBeforeUnmount, ref, watch } from 'vue'
import { EditorContent, useEditor } from '@tiptap/vue-3'
import StarterKit from '@tiptap/starter-kit'
import { TextStyle } from '@tiptap/extension-text-style'
import { Highlight } from '@tiptap/extension-highlight'
import { Table } from '@tiptap/extension-table'
import { TableRow } from '@tiptap/extension-table-row'
import { TableHeader } from '@tiptap/extension-table-header'
import { TableCell } from '@tiptap/extension-table-cell'

const props = defineProps({
  doc: {
    type: Object,
    default: () => ({ type: 'doc', content: [] })
  },
  blockCount: {
    type: Number,
    default: 0
  },
  readonlyBlockCount: {
    type: Number,
    default: 0
  },
  readonlyBlocks: {
    type: Array,
    default: () => []
  },
  activePage: {
    type: Number,
    default: 1
  }
})

const emit = defineEmits(['update:doc'])
const updateTimer = ref(null)

function normalizeDoc(doc) {
  const safeContent = Array.isArray(doc?.content)
    ? doc.content.filter((node) => node && typeof node === 'object' && typeof node.type === 'string')
    : []
  return {
    type: 'doc',
    content: safeContent
  }
}

const editor = useEditor({
  content: normalizeDoc(props.doc),
  editable: true,
  extensions: [
    StarterKit.configure({
      heading: { levels: [1, 2, 3, 4, 5, 6] }
    }),
    TextStyle,
    Highlight,
    Table.configure({ resizable: true }),
    TableRow,
    TableHeader,
    TableCell
  ],
  onUpdate({ editor }) {
    if (updateTimer.value) {
      clearTimeout(updateTimer.value)
    }
    updateTimer.value = window.setTimeout(() => {
      emit('update:doc', normalizeDoc(editor.getJSON()))
    }, 120)
  }
})

watch(
  () => props.doc,
  (nextDoc) => {
    if (!editor.value) return
    editor.value.commands.setContent(normalizeDoc(nextDoc), false)
  },
  { deep: true }
)

function setHeading(level) {
  if (!editor.value) return
  editor.value.chain().focus().toggleHeading({ level }).run()
}

function toggleBulletList() {
  if (!editor.value) return
  editor.value.chain().focus().toggleBulletList().run()
}

function insertParagraphAfter() {
  if (!editor.value) return
  editor.value.chain().focus().insertContent({ type: 'paragraph' }).run()
}

function deleteCurrentBlock() {
  if (!editor.value) return
  if (!editor.value.state.selection.empty) {
    editor.value.chain().focus().deleteSelection().run()
    return
  }
  editor.value.chain().focus().deleteCurrentNode().run()
}

function insertTable() {
  if (!editor.value) return
  editor.value.chain().focus().insertTable({ rows: 2, cols: 2, withHeaderRow: true }).run()
}

onBeforeUnmount(() => {
  if (updateTimer.value) {
    clearTimeout(updateTimer.value)
    updateTimer.value = null
  }
  editor.value?.destroy()
})
</script>

<style scoped lang="scss">
.translation-editor {
  height: 100%;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.translation-editor__toolbar {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 12px 16px;
  border-bottom: 1px solid #e8ecf2;
  background: #fff;
}

.translation-editor__toolbar-group {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.translation-editor__btn {
  height: 32px;
  padding: 0 12px;
  border: 1px solid #d0d5dd;
  border-radius: 8px;
  background: #fff;
  cursor: pointer;
}

.translation-editor__btn.is-active {
  border-color: #2563eb;
  color: #2563eb;
  background: #eff6ff;
}

.translation-editor__hint {
  font-size: 13px;
  color: #667085;
}

.translation-editor__content {
  flex: 1;
  min-height: 0;
  overflow: auto;
  padding: 16px;
  box-sizing: border-box;
  background: #fcfcfd;
}

.translation-editor__page-hint {
  margin-bottom: 12px;
  padding: 8px 12px;
  border-radius: 8px;
  background: #eff6ff;
  color: #1d4ed8;
  font-size: 13px;
}

.translation-editor__readonly-block {
  margin-bottom: 12px;
  padding: 12px 14px;
  border: 1px dashed #d0d5dd;
  border-radius: 10px;
  background: #f8fafc;
}

.translation-editor__readonly-label {
  font-size: 12px;
  line-height: 18px;
  color: #667085;
  margin-bottom: 6px;
}

.translation-editor__readonly-text {
  font-size: 14px;
  line-height: 22px;
  color: #101828;
  white-space: pre-wrap;
  word-break: break-word;
}
</style>
