import { onBeforeUnmount, onMounted, ref } from 'vue'

/** 工作台 TopBar 帮助气泡静态演示数据 */
export const TOPBAR_HELP_DEMO = {
  productName: 'Smart Expense Operations',
  version: 'v0.1.0',
  copyright: 'Copyright © 2024-2026 X-Financial. All Rights Reserved.',
  updatedAt: '2026-06-03'
}

export function useTopBarWorkbenchPopovers() {
  const notificationOpen = ref(false)
  const helpOpen = ref(false)
  const notificationWrapRef = ref(null)
  const helpWrapRef = ref(null)

  function toggleNotification() {
    const next = !notificationOpen.value
    notificationOpen.value = next
    if (next) {
      helpOpen.value = false
    }
  }

  function toggleHelp() {
    const next = !helpOpen.value
    helpOpen.value = next
    if (next) {
      notificationOpen.value = false
    }
  }

  function closeNotification() {
    notificationOpen.value = false
  }

  function closeHelp() {
    helpOpen.value = false
  }

  function isInsideWrap(wrapRef, target) {
    const root = wrapRef.value
    return Boolean(root && target instanceof Node && root.contains(target))
  }

  function handleTopBarPopoverOutside(event) {
    if (!notificationOpen.value && !helpOpen.value) {
      return
    }

    const target = event.target
    if (!(target instanceof Node)) {
      notificationOpen.value = false
      helpOpen.value = false
      return
    }

    if (notificationOpen.value && !isInsideWrap(notificationWrapRef, target)) {
      notificationOpen.value = false
    }

    if (helpOpen.value && !isInsideWrap(helpWrapRef, target)) {
      helpOpen.value = false
    }
  }

  onMounted(() => {
    if (typeof document !== 'undefined') {
      document.addEventListener('pointerdown', handleTopBarPopoverOutside, true)
    }
  })

  onBeforeUnmount(() => {
    if (typeof document !== 'undefined') {
      document.removeEventListener('pointerdown', handleTopBarPopoverOutside, true)
    }
  })

  return {
    notificationOpen,
    helpOpen,
    notificationWrapRef,
    helpWrapRef,
    topbarHelpDemo: TOPBAR_HELP_DEMO,
    toggleNotification,
    toggleHelp,
    closeNotification,
    closeHelp
  }
}
