import { ref } from 'vue'
import { onBackPress } from '@dcloudio/uni-app'

import { BEFORE_NAVIGATE_BACK_EVENT } from './back-events'

/**
 * 安全返回组合式函数。
 * 在页面 setup 中调用，自动注册 onBackPress 拦截。
 * 返回前先通过事件通知所有订阅组件（如 VideoPlayer）执行清理，
 * 延迟后再执行 navigateBack，避免 renderjs 组件销毁竞态。
 *
 * 用法：
 *   const { safeNavigateBack } = useSafeBack()
 *   // 配合 <nav-bar safe-back /> 即可，无需额外代码
 */
export function useSafeBack(options?: { delay?: number }) {
  const leaving = ref(false)
  const delay = options?.delay ?? 80

  const safeNavigateBack = () => {
    if (leaving.value) return
    leaving.value = true

    uni.$emit(BEFORE_NAVIGATE_BACK_EVENT)

    setTimeout(() => {
      uni.navigateBack()
    }, delay)
  }

  onBackPress((event: any) => {
    if (event?.from === 'navigateBack') {
      return false
    }
    if (leaving.value) {
      return true
    }
    safeNavigateBack()
    return true
  })

  return {
    leaving,
    safeNavigateBack,
  }
}
