<template>
  <div class="editor-container">
    <!-- 工具栏 -->
    <div class="toolbar" :class="{ visible: isToolbarVisible }" @mousedown.prevent @focusin="keepToolbarVisible" @focusout="handleToolbarFocusOut">
      <button v-for="tool in tools" :key="tool.name" :class="{ active: tool.active }" @click.stop="handleToolClick(tool.action, $event)" @mousedown.prevent @focusout.prevent class="toolbar-btn">
        <img :src="tool.icon" :alt="tool.name" class="toolbar-icon" />
      </button>
    </div>

    <!-- 编辑区域 -->
    <div ref="editorRef" contenteditable="true" class="editor-content" @input="handleInput" @keydown="handleKeydown" @click="updateToolbarState" @keyup="updateToolbarState" @focus="showToolbar" @blur="hideToolbar"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'

const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
})

const emit = defineEmits(['update:modelValue'])

const editorRef = ref(null)
const content = ref(props.modelValue || '')
const isToolbarVisible = ref(false)

// 初始化编辑器内容
onMounted(() => {
  console.log('RichTextEditor mounted, initial content:', props.modelValue)
  if (editorRef.value) {
    if (props.modelValue) {
      try {
        editorRef.value.innerHTML = props.modelValue
        content.value = props.modelValue
        console.log('Initial content set successfully')
      } catch (error) {
        console.error('Failed to set initial content:', error)
      }
    } else {
      // 即使没有初始内容，也要确保编辑器是可编辑的
      editorRef.value.contentEditable = true
      console.log('Editor initialized without initial content')
    }
  }
})

// 工具配置
const tools = ref([
  {
    name: 'bold',
    icon: '/assets/icons/drawable-xxhdpi/rtf_bold_normal.9.png',
    action: () => formatText('bold'),
    active: false,
  },
  {
    name: 'center',
    icon: '/assets/icons/drawable-xxhdpi/rtf_center_normal.9.png',
    action: () => formatText('justifyCenter'),
    active: false,
  },
  {
    name: 'todo',
    icon: '/assets/icons/drawable-xxhdpi/rtf_gtasks_normal.9.png',
    action: () => formatText('insertTodoList'),
    active: false,
  },
  {
    name: 'list',
    icon: '/assets/icons/drawable-xxhdpi/rtf_list_normal.9.png',
    action: () => formatText('insertUnorderedList'),
    active: false,
  },
  {
    name: 'header',
    icon: '/assets/icons/drawable-xxhdpi/rtf_header_normal.9.png',
    action: () => formatText('formatBlock', 'h2'),
    active: false,
  },
  {
    name: 'quote',
    icon: '/assets/icons/drawable-xxhdpi/rtf_quot_normal.9.png',
    action: () => insertQuote(),
    active: false,
  },
])

// 处理输入事件
const handleInput = () => {
  if (editorRef.value) {
    content.value = editorRef.value.innerHTML
    console.log('Input event handled, content:', content.value)
    emit('update:modelValue', content.value)
  }
}

// 检查当前选区是否已经在某种格式中
const isAlreadyInFormat = formatType => {
  const selection = window.getSelection()
  if (selection.rangeCount > 0) {
    const range = selection.getRangeAt(0)
    const container = range.commonAncestorContainer

    // 向上查找父元素，检查是否已经在指定格式中
    let current = container.nodeType === Node.TEXT_NODE ? container.parentElement : container
    while (current && current !== editorRef.value) {
      if (formatType === 'bold' && current.tagName === 'B') return true
      if (formatType === 'center' && current.style.textAlign === 'center') return true
      if (formatType === 'header' && current.tagName === 'H2') return true
      if (formatType === 'quote' && (current.tagName === 'BLOCKQUOTE' || current.classList.contains('quote-content'))) return true
      if (formatType === 'list' && (current.tagName === 'UL' || current.tagName === 'OL' || current.tagName === 'LI')) return true
      current = current.parentElement
    }
  }
  return false
}

// 检查是否在列表、引用或待办事项中（用于嵌套限制）
const isInListOrQuote = () => {
  const selection = window.getSelection()
  if (selection.rangeCount > 0) {
    const range = selection.getRangeAt(0)
    const container = range.commonAncestorContainer

    // 向上查找父元素，检查是否在列表、引用或待办事项中
    let current = container.nodeType === Node.TEXT_NODE ? container.parentElement : container
    while (current && current !== editorRef.value) {
      if (current.tagName === 'UL' || current.tagName === 'OL' || current.tagName === 'LI' || current.tagName === 'BLOCKQUOTE' || current.classList.contains('quote-content') || current.classList.contains('todo-container')) {
        return true
      }
      current = current.parentElement
    }
  }
  return false
}

// 格式化文本
const formatText = (command, value = null) => {
  // 检查是否已经应用了相同的格式，如果已应用则取消格式
  if (command === 'bold' && isAlreadyInFormat('bold')) {
    document.execCommand('bold', false, null)
    updateToolbarState()
    handleInput()
    return
  }

  if (command === 'justifyCenter' && isAlreadyInFormat('center')) {
    document.execCommand('justifyLeft', false, null)
    updateToolbarState()
    handleInput()
    return
  }

  if (command === 'formatBlock' && value === 'h2' && isAlreadyInFormat('header')) {
    document.execCommand('formatBlock', false, '<p>')
    updateToolbarState()
    handleInput()
    return
  }

  if (command === 'insertUnorderedList' && isAlreadyInFormat('list')) {
    document.execCommand('insertUnorderedList', false, null)
    updateToolbarState()
    handleInput()
    return
  }

  // 处理自定义待办事项
  if (command === 'insertTodoList') {
    insertTodoList()
    updateToolbarState()
    return
  }

  // 检查嵌套限制
  if ((command === 'insertUnorderedList' || (command === 'formatBlock' && value === 'blockquote')) && isInListOrQuote()) {
    return
  }

  document.execCommand(command, false, value)
  updateToolbarState()
  handleInput()
}

// 插入水平线
const insertHorizontalRule = () => {
  document.execCommand('insertHorizontalRule', false, null)
  handleInput()
}

// 插入引用格式
const insertQuote = () => {
  const selection = window.getSelection()
  if (selection.rangeCount > 0) {
    const range = selection.getRangeAt(0)

    // 检查是否已经在引用中
    const container = range.commonAncestorContainer
    let current = container.nodeType === Node.TEXT_NODE ? container.parentElement : container
    while (current && current !== editorRef.value) {
      if (current.tagName === 'BLOCKQUOTE' || (current.classList && current.classList.contains('quote-content'))) return
      current = current.parentElement
    }

    // 检查嵌套限制
    if (isInListOrQuote()) return

    // 创建引用容器
    const quoteContainer = document.createElement('div')
    quoteContainer.className = 'quote-container'

    // 创建图标元素
    const icon = document.createElement('img')
    icon.className = 'quote-icon'
    icon.src = '/assets/icons/drawable-xxhdpi/rag_quote.png'
    icon.alt = '引用'

    // 创建内容容器
    const contentSpan = document.createElement('div')
    contentSpan.className = 'quote-content'
    contentSpan.textContent = '引用内容'

    // 组装元素
    quoteContainer.appendChild(icon)
    quoteContainer.appendChild(contentSpan)

    // 插入到当前光标位置
    range.insertNode(quoteContainer)

    // 添加换行
    const br = document.createElement('br')
    quoteContainer.parentNode.insertBefore(br, quoteContainer.nextSibling)

    // 聚焦到内容区域（延迟执行，确保在handleToolClick处理完后再聚焦）
    setTimeout(() => {
      if (editorRef.value) {
        const newRange = document.createRange()
        newRange.selectNodeContents(contentSpan)
        newRange.collapse(false)
        const sel = window.getSelection()
        sel.removeAllRanges()
        sel.addRange(newRange)

        // 确保编辑器保持焦点状态
        editorRef.value.focus()
      }
    }, 0)

    // 添加事件监听器到内容区域，监听内容变化
    const checkContent = () => {
      // 延迟检查，确保内容已更新
      setTimeout(() => {
        if (contentSpan.textContent.trim() === '') {
          // 如果内容为空，移除整个引用容器
          quoteContainer.remove()
          handleInput()
        }
      }, 0)
    }

    contentSpan.addEventListener('input', checkContent)
    contentSpan.addEventListener('blur', checkContent)

    handleInput()
  }
}

// 插入待办事项列表
const insertTodoList = () => {
  const selection = window.getSelection()
  if (selection.rangeCount > 0) {
    const range = selection.getRangeAt(0)

    // 检查嵌套限制
    if (isInListOrQuote()) return

    // 创建待办事项容器
    const todoContainer = document.createElement('div')
    todoContainer.contentEditable = false
    todoContainer.className = 'todo-container'

    // 创建图标元素
    const icon = document.createElement('img')
    icon.className = 'todo-icon'
    icon.src = '/assets/icons/drawable-xxhdpi/rtf_icon_gtasks.png'
    icon.alt = '待办事项'

    // 创建内容容器
    const contentSpan = document.createElement('div')
    contentSpan.contentEditable = true
    contentSpan.className = 'todo-content'
    contentSpan.textContent = '待办事项'

    // 组装元素
    todoContainer.appendChild(icon)
    todoContainer.appendChild(contentSpan)

    // 插入到当前光标位置
    range.insertNode(todoContainer)

    // 添加换行
    const br = document.createElement('br')
    todoContainer.parentNode.insertBefore(br, todoContainer.nextSibling)

    // 聚焦到内容区域（延迟执行，确保在handleToolClick处理完后再聚焦）
    setTimeout(() => {
      if (editorRef.value) {
        const newRange = document.createRange()
        newRange.selectNodeContents(contentSpan)
        newRange.collapse(false)
        const sel = window.getSelection()
        sel.removeAllRanges()
        sel.addRange(newRange)

        // 重要：不要重新聚焦到编辑器，因为待办事项有自己的可编辑区域
        // 但我们仍需要确保当前可编辑区域有焦点
        contentSpan.focus()

        // 确保工具栏保持可见
        isToolbarVisible.value = true
      }
    }, 0)

    // 添加事件监听器到图标
    icon.addEventListener('click', function () {
      // 根据当前状态切换图标
      if (this.src.includes('rtf_icon_gtasks.png')) {
        this.src = '/assets/icons/drawable-xxhdpi/rtf_icon_gtasks_light.png'
        contentSpan.style.color = 'var(--text-tertiary)'
        contentSpan.style.textDecoration = 'line-through'
      } else {
        this.src = '/assets/icons/drawable-xxhdpi/rtf_icon_gtasks.png'
        contentSpan.style.color = 'var(--note-content)'
        contentSpan.style.textDecoration = 'none'
      }
      handleInput()
    })

    // 添加事件监听器到内容区域，监听内容变化和按键事件
    const checkContent = () => {
      // 延迟检查，确保内容已更新
      setTimeout(() => {
        if (contentSpan.textContent.trim() === '') {
          // 如果内容为空，移除整个待办事项容器
          todoContainer.remove()
          handleInput()
        }
      }, 0)
    }

    contentSpan.addEventListener('input', checkContent)
    contentSpan.addEventListener('blur', checkContent)

    // 添加焦点事件监听器，确保工具栏在待办事项获得焦点时保持可见
    contentSpan.addEventListener('focus', () => {
      isToolbarVisible.value = true
    })

    // 监听回车键，创建同级待办事项
    contentSpan.addEventListener('keydown', e => {
      if (e.key === 'Enter') {
        e.preventDefault()

        // 创建新的待办事项
        const newTodoContainer = document.createElement('div')
        newTodoContainer.contentEditable = false
        newTodoContainer.className = 'todo-container'

        // 创建图标元素
        const newIcon = document.createElement('img')
        newIcon.className = 'todo-icon'
        newIcon.src = '/assets/icons/drawable-xxhdpi/rtf_icon_gtasks.png'
        newIcon.alt = '待办事项'

        // 创建内容容器
        const newContentSpan = document.createElement('div')
        newContentSpan.contentEditable = true
        newContentSpan.className = 'todo-content'
        newContentSpan.textContent = ''

        // 组装元素
        newTodoContainer.appendChild(newIcon)
        newTodoContainer.appendChild(newContentSpan)

        // 插入到当前待办事项后面
        todoContainer.parentNode.insertBefore(newTodoContainer, todoContainer.nextSibling)

        // 添加换行
        const newBr = document.createElement('br')
        newTodoContainer.parentNode.insertBefore(newBr, newTodoContainer.nextSibling)

        // 聚焦到新内容区域
        const newRange = document.createRange()
        newRange.selectNodeContents(newContentSpan)
        newRange.collapse(false)
        selection.removeAllRanges()
        selection.addRange(newRange)

        // 添加事件监听器到新图标
        newIcon.addEventListener('click', function () {
          // 根据当前状态切换图标
          if (this.src.includes('rtf_icon_gtasks.png')) {
            this.src = '/assets/icons/drawable-xxhdpi/rtf_icon_gtasks_light.png'
            newContentSpan.style.color = 'var(--text-tertiary)'
            newContentSpan.style.textDecoration = 'line-through'
          } else {
            this.src = '/assets/icons/drawable-xxhdpi/rtf_icon_gtasks.png'
            newContentSpan.style.color = 'var(--note-content)'
            newContentSpan.style.textDecoration = 'none'
          }
          handleInput()
        })

        // 添加事件监听器到新内容区域
        const newCheckContent = () => {
          setTimeout(() => {
            if (newContentSpan.textContent.trim() === '') {
              newTodoContainer.remove()
              handleInput()
            }
          }, 0)
        }

        newContentSpan.addEventListener('input', newCheckContent)
        newContentSpan.addEventListener('blur', newCheckContent)

        // 添加焦点事件监听器，确保工具栏在待办事项获得焦点时保持可见
        newContentSpan.addEventListener('focus', () => {
          isToolbarVisible.value = true
        })

        // 监听新内容区域的回车键
        newContentSpan.addEventListener('keydown', e => {
          if (e.key === 'Enter') {
            e.preventDefault()

            // 创建新的待办事项
            const nextTodoContainer = document.createElement('div')
            nextTodoContainer.contentEditable = false
            nextTodoContainer.className = 'todo-container'

            // 创建图标元素
            const nextIcon = document.createElement('img')
            nextIcon.className = 'todo-icon'
            nextIcon.src = '/assets/icons/drawable-xxhdpi/rtf_icon_gtasks.png'
            nextIcon.alt = '待办事项'

            // 创建内容容器
            const nextContentSpan = document.createElement('div')
            nextContentSpan.contentEditable = true
            nextContentSpan.className = 'todo-content'
            nextContentSpan.textContent = ''

            // 组装元素
            nextTodoContainer.appendChild(nextIcon)
            nextTodoContainer.appendChild(nextContentSpan)

            // 插入到当前待办事项后面
            newTodoContainer.parentNode.insertBefore(nextTodoContainer, newTodoContainer.nextSibling)

            // 添加换行
            const nextBr = document.createElement('br')
            nextTodoContainer.parentNode.insertBefore(nextBr, nextTodoContainer.nextSibling)

            // 聚焦到新内容区域
            const nextRange = document.createRange()
            nextRange.selectNodeContents(nextContentSpan)
            nextRange.collapse(false)
            selection.removeAllRanges()
            selection.addRange(nextRange)

            // 添加事件监听器到新图标
            nextIcon.addEventListener('click', function () {
              // 根据当前状态切换图标
              if (this.src.includes('rtf_icon_gtasks.png')) {
                this.src = '/assets/icons/drawable-xxhdpi/rtf_icon_gtasks_light.png'
                nextContentSpan.style.color = 'var(--text-tertiary)'
                nextContentSpan.style.textDecoration = 'line-through'
              } else {
                this.src = '/assets/icons/drawable-xxhdpi/rtf_icon_gtasks.png'
                nextContentSpan.style.color = 'var(--note-content)'
                nextContentSpan.style.textDecoration = 'none'
              }
              handleInput()
            })

            // 添加事件监听器到新内容区域
            const nextCheckContent = () => {
              setTimeout(() => {
                if (nextContentSpan.textContent.trim() === '') {
                  nextTodoContainer.remove()
                  handleInput()
                }
              }, 0)
            }

            nextContentSpan.addEventListener('input', nextCheckContent)
            nextContentSpan.addEventListener('blur', nextCheckContent)

            // 添加焦点事件监听器，确保工具栏在待办事项获得焦点时保持可见
            nextContentSpan.addEventListener('focus', () => {
              isToolbarVisible.value = true
            })

            handleInput()
          }
        })

        handleInput()
      }
    })

    handleInput()
  }
}

// 插入图片
const insertImage = () => {
  // 创建文件输入元素
  const fileInput = document.createElement('input')
  fileInput.type = 'file'
  fileInput.accept = 'image/*'
  fileInput.style.display = 'none'

  // 添加到文档中
  document.body.appendChild(fileInput)

  // 监听文件选择事件
  fileInput.addEventListener('change', function (event) {
    const file = event.target.files[0]
    if (file && file.type.startsWith('image/')) {
      // 创建FileReader读取文件
      const reader = new FileReader()
      reader.onload = function (e) {
        // 获取图片数据URL
        const imageDataUrl = e.target.result

        // 获取当前选区
        const selection = window.getSelection()
        if (selection.rangeCount > 0) {
          const range = selection.getRangeAt(0)

          // 创建图片元素
          const img = document.createElement('img')
          img.src = imageDataUrl
          img.className = 'editor-image'
          img.style.maxWidth = '100%'
          img.style.height = 'auto'
          img.style.display = 'block'
          img.style.margin = '0 auto'

          // 插入图片到当前光标位置
          range.insertNode(img)

          // 添加换行
          const br = document.createElement('br')
          img.parentNode.insertBefore(br, img.nextSibling)

          // 触发输入事件更新内容
          handleInput()

          // 重新聚焦到编辑器
          if (editorRef.value) {
            editorRef.value.focus()
          }
        }
      }
      reader.readAsDataURL(file)
    }

    // 清理文件输入元素
    document.body.removeChild(fileInput)
  })

  // 触发文件选择对话框
  fileInput.click()
}

// 处理键盘事件
const handleKeydown = e => {
  // 处理Shift+Enter键换行
  if (e.key === 'Enter' && e.shiftKey) {
    e.preventDefault()
    document.execCommand('insertHTML', false, '<br><br>')
    handleInput()
    return
  }

  // 处理Tab键缩进
  if (e.key === 'Tab') {
    e.preventDefault()
    document.execCommand('insertHTML', false, '    ')
    handleInput()
    return
  }

  // 处理回车键创建新列表项
  if (e.key === 'Enter' && !e.shiftKey) {
    // 检查是否在列表中
    const selection = window.getSelection()
    if (selection.rangeCount > 0) {
      const range = selection.getRangeAt(0)
      const container = range.startContainer

      // 检查是否在ul或ol内
      let listElement = null
      let current = container.nodeType === Node.TEXT_NODE ? container.parentElement : container

      while (current && current !== editorRef.value) {
        if (current.tagName === 'LI') {
          listElement = current
          break
        }
        current = current.parentElement
      }

      // 如果在列表项中且为空，退出列表
      if (listElement) {
        const liContent = listElement.textContent.trim()
        if (liContent === '') {
          e.preventDefault()
          // 退出列表
          document.execCommand('outdent')
          handleInput()
        }
      }
    }
  }
}

// 更新工具栏状态
const updateToolbarState = () => {
  nextTick(() => {
    tools.value.forEach(tool => {
      if (tool.name === 'bold') {
        tool.active = document.queryCommandState('bold')
      } else if (tool.name === 'center') {
        tool.active = document.queryCommandState('justifyCenter')
      } else if (tool.name === 'list') {
        tool.active = document.queryCommandState('insertUnorderedList')
      } else if (tool.name === 'quote') {
        tool.active = document.queryCommandState('formatBlock')
      } else if (tool.name === 'header') {
        tool.active = document.queryCommandState('formatBlock')
      }
    })
  })
}

// 初始化编辑器内容
onMounted(() => {
  if (editorRef.value) {
    editorRef.value.innerHTML = content.value
  }
})

// 显示工具栏
const showToolbar = () => {
  isToolbarVisible.value = true
}

// 隐藏工具栏
const hideToolbar = () => {
  // 不立即隐藏工具栏，而是通过handleToolbarFocusOut处理
  // 添加延迟以确保点击工具栏按钮时不会立即隐藏
  setTimeout(() => {
    handleToolbarFocusOut()
  }, 200)
}

// 处理工具栏按钮点击事件
const handleToolClick = (action, event) => {
  // 阻止事件冒泡，防止触发编辑器失焦
  if (event) {
    event.preventDefault()
    event.stopPropagation()
  }

  // 执行工具操作
  action()

  // 对于待办事项，不需要重新聚焦到编辑器，因为它有自己的可编辑区域
  // 其他工具需要重新聚焦到编辑器
  const isTodoAction = action === insertTodoList
  if (!isTodoAction) {
    // 重新聚焦到编辑器
    setTimeout(() => {
      if (editorRef.value) {
        editorRef.value.focus()
      }
    }, 0)
  } else {
    // 对于待办事项，确保工具栏保持可见
    isToolbarVisible.value = true
  }
}

// 保持工具栏可见
const keepToolbarVisible = () => {
  isToolbarVisible.value = true
}

// 处理工具栏失焦
const handleToolbarFocusOut = () => {
  // 添加一个小延迟，以便处理工具栏按钮的点击事件
  setTimeout(() => {
    // 检查焦点是否在工具栏上
    const activeElement = document.activeElement
    const toolbarElement = document.querySelector('.toolbar')

    // 如果焦点不在工具栏上才隐藏
    if (!toolbarElement || !toolbarElement.contains(activeElement)) {
      // 额外检查是否有待办事项的内容区域有焦点
      const todoContentElements = document.querySelectorAll('.todo-content')
      let todoHasFocus = false
      for (let i = 0; i < todoContentElements.length; i++) {
        if (todoContentElements[i] === activeElement || todoContentElements[i].contains(activeElement)) {
          todoHasFocus = true
          break
        }
      }

      // 只有在没有待办事项获得焦点时才隐藏工具栏
      if (!todoHasFocus) {
        isToolbarVisible.value = false
      }
    }
  }, 200) // 增加延迟时间，确保有足够时间处理点击事件
}

// 暴露方法给父组件
defineExpose({
  getContent: () => content.value,
  setContent: newContent => {
    console.log('Setting content in editor:', newContent)
    content.value = newContent || ''
    if (editorRef.value) {
      try {
        editorRef.value.innerHTML = content.value
        console.log('Content set successfully in editorRef')
      } catch (error) {
        console.error('Failed to set innerHTML:', error)
        // 备选方案：使用textContent
        try {
          editorRef.value.textContent = content.value
          console.log('Content set using textContent')
        } catch (textContentError) {
          console.error('Failed to set textContent:', textContentError)
        }
      }
    } else {
      // 如果editorRef还不可用，延迟设置
      console.log('Editor ref is not available, will retry when mounted')
      setTimeout(() => {
        if (editorRef.value) {
          try {
            editorRef.value.innerHTML = content.value
            console.log('Content set successfully after delay')
          } catch (error) {
            console.error('Failed to set innerHTML after delay:', error)
          }
        }
      }, 100)
    }
  },
  insertImage,
})
</script>

<style scoped>
.editor-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: var(--background-card);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

.toolbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 8px 12px;
  border-top: 1px solid var(--border);
  background-color: var(--background-card);
  flex-shrink: 0;
  transform: translateY(100%);
  transition: transform 0.3s ease;
  z-index: 1000;
  /* 确保工具栏能正确获取焦点 */
  tabindex: 0;
}

.toolbar.visible {
  transform: translateY(0);
}

.toolbar-btn {
  padding: 6px;
  margin-right: 6px;
  border: none;
  background: transparent;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  /* 确保按钮能正确获取焦点 */
  tabindex: 0;
}

.toolbar-btn:hover {
  background-color: var(--background-secondary);
}

.toolbar-btn.active {
  background-color: var(--primary-light);
  border: 1px solid var(--border);
}

.toolbar-icon {
  width: 20px;
  height: 20px;
  opacity: 0.8;
}

.toolbar-btn.active .toolbar-icon {
  opacity: 1;
}

.editor-content {
  flex: 1;
  padding: 0 10px 60px 10px; /* 添加底部内边距，防止内容被工具栏遮挡 */
  outline: none;
  overflow-y: auto;
  font-size: var(--editor-font-size, 16px);
  line-height: var(--editor-line-height, 1.6);
  color: var(--note-content);
  min-height: 200px;
  background-color: var(--background-card);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  position: relative;
  /* 基准线样式 */
  background-image: linear-gradient(to bottom, var(--border) 1px, transparent 1px);
  background-size: 100% calc(var(--editor-font-size, 16px) * var(--editor-line-height, 1.6)); /* var(--editor-font-size) * var(--editor-line-height) */
  background-repeat: repeat-y;
  background-position: 0 calc((var(--editor-font-size, 16px) * var(--editor-line-height, 1.6) - var(--editor-font-size, 16px)) / 2);
}

.editor-content::before {
  display: none;
}

/* 统一处理所有直接子元素的间距 */
.editor-content > * {
  margin: 0;
  padding: 0;
}

.editor-content:focus,
.editor-content * {
  outline: none;
}

/* 优化段落样式，确保与基准线对齐 */
:deep(.editor-content p) {
  margin: 0 0 12px 0;
  line-height: var(--editor-line-height, 1.6);
  letter-spacing: 0.3px;
}

/* 自定义内容样式 - 统一行高和间距 */
:deep(.editor-content h2) {
  font-size: var(--editor-font-size, 16px);
  font-weight: 600;
  margin: 0 0 12px 0;
  color: var(--note-title);
  line-height: var(--editor-line-height, 1.6);
  letter-spacing: 0.3px;
  text-align: center;
  position: relative;
}

:deep(.editor-content blockquote) {
  border-left: 3px solid var(--primary);
  padding: 0 16px 0 16px;
  margin: 0 0 12px 0;
  color: var(--text-secondary);
  background-color: var(--background-secondary);
  font-style: italic;
  line-height: var(--editor-line-height, 1.6);
}

:deep(.quote-container) {
  position: relative;
  margin: 0 0 12px 0;
  line-height: var(--editor-line-height, 1.6);
}

:deep(.quote-icon) {
  position: absolute;
  left: 0;
  top: 0;
  width: var(--editor-font-size, 16px);
  height: var(--editor-font-size, 16px);
  margin-top: 3px;
}

:deep(.quote-content) {
  border-left: 3px solid var(--primary);
  padding: 0 var(--editor-font-size, 16px) 0 32px;
  margin-left: var(--editor-font-size, 16px);
  color: var(--text-secondary);
  background-color: var(--background-secondary);
  font-style: italic;
  line-height: var(--editor-line-height, 1.6);
}

:deep(.editor-content ul),
:deep(.editor-content ol) {
  margin: 0 0 12px 0;
  padding-left: 32px;
  position: relative;
  line-height: var(--editor-line-height, 1.6);
}

:deep(.editor-content li) {
  margin: 0;
  line-height: var(--editor-line-height, 1.6);
  padding: 0;
}

:deep(.editor-content strong) {
  color: var(--text-primary);
  font-weight: 600;
}

:deep(.editor-content em) {
  color: var(--text-secondary);
  font-style: italic;
}

:deep(.editor-content u) {
  text-decoration: none;
  border-bottom: 1px solid var(--text-primary);
}

:deep(.editor-content hr) {
  border: none;
  height: 1px;
  background-color: var(--border);
  margin: 12px 0;
}

.editor-content div[style*='text-align: center'] {
  text-align: center;
}



.editor-content img {
  max-width: 100%;
  height: auto;
  display: block;
  margin: 0 auto;
}

/* 待办事项样式 */
:deep(.todo-container) {
  display: flex;
  align-items: center;
  margin: 0;
  line-height: var(--editor-line-height, 1.6);
}

:deep(.todo-icon) {
  width: calc(var(--editor-font-size, 16px) * 2);
  height: calc(var(--editor-font-size, 16px) * 2);
  margin-right: 3px;
  margin-top: 0;
  cursor: pointer;
  flex-shrink: 0;
}

:deep(.todo-content) {
  flex: 1;
  outline: none;
  line-height: var(--editor-line-height, 1.6);
  padding: 0;
  margin: 0;
}
</style>
