<template>
  <Button :isActive="isActive || contentEditorPanel" v-bind="{ ...item }" :onClick="onClick" :class="{ disabled: rightPanelButtonDisabled }" :title="$t('header.rightPanel')">
    <PanelRight />
  </Button>
</template>

<script setup>
  import { useViewerStore } from '@/stores/modules/viewer'
  import { computed, ref, watch } from 'vue'
  import core from '@/core'

  const useViewer = useViewerStore()
  const { item } = defineProps(['item'])

  const toolMode = computed(() => useViewer.getToolMode)
  const isActive = computed(() => {
    return useViewer.isElementOpen(item.element)
  })
  const contentEditorPanel = computed(() => useViewer.isElementOpen('contentEditorPanel'))
  const contentEditorType = computed(() => useViewer.getContentEditorType)
  const rightPanelButtonDisabled = computed(() => useViewer.getRightPanelButtonDisabled)

  let isDisabled = ref(true)
  let isEditorPanelDisabled = ref(true)

  watch(() => contentEditorPanel.value, (newValue, oldValue) => {
    isEditorPanelDisabled.value = !contentEditorPanel.value && !document.querySelector('.frame-container.selected')
  })

  watch(toolMode, (newValue, oldValue) => {
    if (oldValue === 'form' && newValue !== 'form') {
      useViewer.closeElement(item.element)
    }
  })

  watch([isDisabled, isEditorPanelDisabled, toolMode], (newValues, oldValues) => {
    const disabled = (newValues[0] && newValues[1]) || (newValues[2] !== 'form' && newValues[2] !== 'editor')
    useViewer.setRightPanelButtonDisabled(disabled)
  })

  watch([isActive, contentEditorPanel], (newValue, oldValue) => {
    if (newValue[0] || newValue[1]) {
      core.eventBus().dispatch('isRightSidePanelOpened', true)
    } else {
      core.eventBus().dispatch('isRightSidePanelOpened', false)
    }
  })

  watch(rightPanelButtonDisabled, (newValue, oldValue) => {
    core.eventBus().dispatch('isRightSidePanelBtnDisabled', newValue)
  })

  const onClick = () => {
    setTimeout(() => {
      isDisabled.value = document.getElementsByClassName('outline-container').length === 0

      if (toolMode.value === 'form' && isDisabled.value && document.getElementsByClassName('right-panel')[0].className.indexOf('closed') !== -1) return

      if (toolMode.value === 'form') {
        useViewer.toggleElement(item.element)
      } else if (toolMode.value === 'editor') {
        useViewer.toggleElement('contentEditorPanel')
      }
    }, 1);
  }

  const changeDisabled = (val) => {
    isEditorPanelDisabled.value = val
    isDisabled.value = document.getElementsByClassName('outline-container').length === 0
  }
  core.addEvent('changeRightPanelBtnDisabled', changeDisabled)
</script>
