<template>
  <div ref="textPopupRef">
    <div v-if="showPopup && textPopup.length" class="text-popup popup" :class="{ 'transform': isTranslateX }" :style="{ top: `${top}px`, left: `${left}px` }">
      <template v-for="(item, index) in textPopup" :key="`${item.dataElement || new Date()}-${index}`">
        <CustomButton v-if="item.name === 'customButton' && !item.hidden" :item="item" :data-element="item.dataElement" />
        <Button v-else-if="item.type === 'copy' && !item.hidden" @click="handlePopup('copy')" :title="$t('documentEditor.copy')" :data-element="item.dataElement"><CopyText /></Button>
        <Button v-else-if="item.type === 'highlight' && !item.hidden" @click="handlePopup('highlight')" :title="$t('header.highlight')" :data-element="item.dataElement"><HightlightGray /></Button>
        <Button v-else-if="item.type === 'underline' && !item.hidden" @click="handlePopup('underline')" :title="$t('header.underline')" :data-element="item.dataElement"><UnderlineGray /></Button>
        <Button v-else-if="item.type === 'strikeout' && !item.hidden" @click="handlePopup('strikeout')" :title="$t('header.strikeout')" :data-element="item.dataElement"><StrikeoutGray /></Button>
        <Button v-else-if="item.type === 'squiggly' && !item.hidden" @click="handlePopup('squiggly')" :title="$t('header.squiggly')" :data-element="item.dataElement"><SquiggleGray /></Button>
        <div v-else-if="['spacer', 'divider'].includes(item.type)" :class="item.type"></div>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, nextTick } from 'vue'
import core from '@/core'
import copy from 'copy-to-clipboard'

import { useViewerStore } from '@/stores/modules/viewer'
import { useDocumentStore } from '@/stores/modules/document'

const useViewer = useViewerStore()
const useDocument = useDocumentStore()

const textPopup = computed(() => useViewer.getPopupItems('textPopup'))

const showPopup = ref(false)
const top = ref(0)
const left = ref(0)
const textPopupRef = ref(null)
const isTranslateX = ref(true)
const selectedText = ref(null)

let documentContainer

const handlePopup = (tool) => {
  if (tool === 'copy' && selectedText.value) {
    copy(selectedText.value)
    showPopup.value = false
    selectedText.value = null
    return
  }

  const data = { tool }

  const color = useDocument[tool]?.color
  if (color) data.color = color

  core.handleTextPopup(data)
}

const updatePopupPosition = async (data) => {
  const { show, rect, text } = data

  showPopup.value = show
  selectedText.value = text
  await nextTick()

  if (rect && showPopup.value) {
    const popup = textPopupRef.value.children[0]
    if (!popup) return

    // 计算弹窗的初始位置
    let initialLeft = rect.left + (rect.right - rect.left) / 2
    let initialTop = rect.bottom

    const popupWidth = popup.offsetWidth
    const popupHeight = popup.offsetHeight + 10

    const windowWidth = window.innerWidth
    const windowHeight = window.innerHeight

    isTranslateX.value = true

    // 检查水平位置
    if (initialLeft - popupWidth / 2 < 0) {
      initialLeft = 0
      isTranslateX.value = false
    } else if (initialLeft + popupWidth / 2 > windowWidth) {
      initialLeft = windowWidth - popupWidth
      isTranslateX.value = false
    }

    // 检查垂直位置
    if (initialTop + popupHeight > windowHeight) {
      initialTop = Math.max(0, rect.top - popupHeight)
    }

    top.value = initialTop
    left.value = initialLeft
  }
}
core.addEvent('showTextPopup', updatePopupPosition)

const scrollHandler = () => {
  if (showPopup.value) showPopup.value = false
}

onMounted(() => {
  documentContainer = document.querySelector('.document-container')
  if (documentContainer) documentContainer.addEventListener('scroll', scrollHandler)
})

onUnmounted(() => {
  if (documentContainer) documentContainer.removeEventListener('scroll', scrollHandler)
})
</script>

<style lang="scss">
.popup {
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 4px 8px;
  z-index: 3;
  border-radius: 4px;
  background: var(--c-header-bg);
  box-shadow: 0 0 3px 0 #868e96;
  transform: translateY(5px);
  transition: transform 0.3s ease-in-out;

  &.transform {
    transform: translateX(-50%) translateY(5px);
  }

  .button:last-child {
    margin-right: 0
  }
}
@media screen and (min-width: 578px) {
  .popup {
    .button {
      &:not(.disabled):hover {
        background-color: var(--c-header-button-active);
      }
    }
  }
}
</style>