<template>
  <Button :isActive="isActive || contentEditorPanel" v-bind="{ ...item }" :onClick="onClick" :class="{disabled: (isDisabled && isEditorPanelDisabled) || (toolMode !== 'form' && toolMode !== 'editor')}" :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)

  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)
      core.toggleSidebar()
    }
  })

  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')
      }
      core.toggleSidebar()
    }, 1);
  }

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