/** 与 pages.json tabBar.list[].pagePath 一致（无开头 /） */
const TAB_PAGE_PATHS = new Set([
  'pages/home/index',
  'pages/order/index',
  'pages/market/index',
  'pages/mine/index'
])

const TABBAR_API_NAMES = [
  'setTabBarStyle',
  'setTabBarItem',
  'setTabBarBadge',
  'removeTabBarBadge',
  'showTabBarRedDot',
  'hideTabBarRedDot',
  'showTabBar',
  'hideTabBar',
  'setTabBarMidButton'
]

function normalizePageRoute(route) {
  if (!route) {
    return ''
  }
  let r = String(route).replace(/^\//, '')
  const prefixes = ['bqH5/', 'bqjy/']
  for (const prefix of prefixes) {
    if (r.startsWith(prefix)) {
      r = r.slice(prefix.length)
    }
  }
  return r
}

export function isTabBarPage() {
  const stack = getCurrentPages()
  if (!stack.length) {
    return false
  }
  const cur = stack[stack.length - 1]
  const route = normalizePageRoute(cur.route || '')
  return TAB_PAGE_PATHS.has(route)
}

function installTabBarApiGuard() {
  if (typeof uni === 'undefined' || !uni.addInterceptor) {
    return
  }
  TABBAR_API_NAMES.forEach((name) => {
    if (typeof uni[name] !== 'function') {
      return
    }
    uni.addInterceptor(name, {
      invoke() {
        if (!isTabBarPage()) {
          return false
        }
      }
    })
  })
}

installTabBarApiGuard()
