import { useEffect } from 'react'
import { usePPTEditContext } from '../context'
import { useToolPostion } from './useToolPostion'
import type { UseInjectModeReturn } from '../hooks/useIframeMode'

export const useDiff = (
  useIframeReturn: UseInjectModeReturn,
  isDoc?: boolean,
) => {
  const editorContext = usePPTEditContext()
  const { selectedElement, editor, tipPosition } = useIframeReturn

  const docModeToolPosition = useToolPostion(editor, !!isDoc)

  useEffect(() => {
    const hasActive = editor?.EditorRegistry.hasActiveEditor()
    const reWriteState = { ...useIframeReturn }
    if (isDoc) {
      // 重写状态
      reWriteState.position = docModeToolPosition
      reWriteState.tipPosition = docModeToolPosition
      editorContext?.setState(reWriteState)
      return
    }
    if (hasActive && selectedElement) {
      // 有激活的实例且为当前的实例
      editorContext?.setState(reWriteState)
    } else if (!selectedElement && !hasActive) {
      // 失焦后清空所有状态，关闭tip
      reWriteState.position = null
      reWriteState.tipPosition = null
      editorContext?.setState(reWriteState)
    }
  }, [selectedElement, editor, tipPosition, isDoc, docModeToolPosition])
}
