<script setup lang="ts">
import type { DocksContext } from '@devframes/hub/client'
import type { DockLayout } from './dock-layout'
import { useEventListener } from '@vueuse/core'
import { onUnmounted } from 'vue'
import { sharedStateToRef } from '../../state/docks'
import { closeDockPopup, useIsDockPopupOpen } from '../../state/popup'
import { useIsRpcTrusted } from '../../utils/useIsRpcTrusted'
import CommandPalette from '../command-palette/CommandPalette.vue'
import Confirm from '../display/Confirm.vue'
import ToastOverlay from '../display/ToastOverlay.vue'
import FloatingElements from '../floating/FloatingElements.vue'
import ColorSchemeRoot from './ColorSchemeRoot.vue'
import Dock from './Dock.vue'
import DockEdge from './DockEdge.vue'
import DockPanel from './DockPanel.vue'

const props = defineProps<{
  context: DocksContext
  /** Override dock layout tunables (forwarded to the float-mode bar + panel). */
  layout?: Partial<DockLayout>
}>()

const isDockPopupOpen = useIsDockPopupOpen()
const settings = sharedStateToRef(props.context.docks.settings)

// Force float mode when unauthorized, regardless of store setting
const isRpcTrusted = useIsRpcTrusted(props.context)

// Close the dock when clicking outside of it
useEventListener(window, 'mousedown', (e: MouseEvent) => {
  if (!settings.value.closeOnOutsideClick)
    return
  if (isDockPopupOpen.value)
    return
  if (!props.context.panel.store.open || props.context.panel.isDragging || props.context.panel.isResizing)
    return

  const matched = e.composedPath().find((_el) => {
    const el = _el as HTMLElement
    return [...(el.classList || [])].some(c => c.startsWith('devframes-'))
      || el.id?.startsWith('devframes-')
      || el.tagName?.toLowerCase() === 'iframe'
  })

  if (!matched)
    props.context.docks.switchEntry(null)
})

onUnmounted(() => {
  closeDockPopup()
})
</script>

<template>
  <ColorSchemeRoot>
    <template v-if="!isDockPopupOpen">
      <template v-if="isRpcTrusted && context.panel.store.mode === 'edge'">
        <DockEdge :context />
      </template>
      <template v-else>
        <Dock :context :layout="props.layout">
          <template #default="{ dockEl, panelMargins, selected, layout: dockLayout }">
            <DockPanel
              :context
              :selected
              :dock-el="dockEl!"
              :panel-margins="panelMargins"
              :layout="dockLayout"
            />
          </template>
        </Dock>
      </template>
      <FloatingElements />
    </template>
    <CommandPalette v-if="!isDockPopupOpen" :context />
    <ToastOverlay :context />
    <Confirm v-if="!isDockPopupOpen" />
  </ColorSchemeRoot>
</template>
