const TAB_KEYS = ['nav.home', 'nav.ai', 'nav.message', 'nav.mine']

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

/** 运行时会改 TabBar 的 uni API（非 Tab 页调用会报 not TabBar page） */
const TABBAR_API_NAMES = [
  'setTabBarStyle',
  'setTabBarItem',
  'setTabBarBadge',
  'removeTabBarBadge',
  'showTabBarRedDot',
  'hideTabBarRedDot',
  'showTabBar',
  'hideTabBar',
  'setTabBarMidButton'
]

function readUniTabPagePaths() {
  try {
    const list =
      (typeof __uniConfig !== 'undefined' &&
        __uniConfig.tabBar &&
        __uniConfig.tabBar.list) ||
      []
    list.forEach((item) => {
      const path = normalizePageRoute(item.pagePath || '')
      if (path) {
        TAB_PAGE_PATHS.add(path)
      }
    })
  } catch (e) {
    // ignore
  }
}

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

function getCurrentPageRoute() {
  const stack = getCurrentPages()
  if (!stack.length) {
    return ''
  }
  const cur = stack[stack.length - 1]
  return cur.route || cur.$page?.route || cur.$page?.fullPath || ''
}

/**
 * 当前栈顶是否为原生 TabBar 页
 */
export function isTabBarPage() {
  const route = normalizePageRoute(getCurrentPageRoute())
  return !!route && TAB_PAGE_PATHS.has(route)
}

function noopTabBarResult(name) {
  return { errMsg: `${name}:ok` }
}

function finishNoopTabBarCall(name, options) {
  const result = noopTabBarResult(name)
  if (options && typeof options.success === 'function') {
    options.success(result)
  }
  if (options && typeof options.complete === 'function') {
    options.complete(result)
  }
  return Promise.resolve(result)
}

/**
 * H5 生产包中 addInterceptor 偶发拦不住框架内部调用，直接包装 uni API 更稳
 */
function wrapTabBarApi(name) {
  if (typeof uni === 'undefined' || typeof uni[name] !== 'function') {
    return
  }
  const raw = uni[name].bind(uni)
  uni[name] = function patchedTabBarApi(options) {
    const opts = options || {}
    if (!isTabBarPage()) {
      return finishNoopTabBarCall(name, opts)
    }
    try {
      const ret = raw(opts)
      if (ret && typeof ret.catch === 'function') {
        ret.catch((err) => {
          const msg = err && err.errMsg ? String(err.errMsg) : ''
          if (msg.includes('TabBar') && msg.includes('fail')) {
            return
          }
          throw err
        })
      }
      return ret
    } catch (err) {
      const msg = err && err.errMsg ? String(err.errMsg) : ''
      if (msg.includes('TabBar') && msg.includes('fail')) {
        return finishNoopTabBarCall(name, opts)
      }
      throw err
    }
  }
}

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

installTabBarApiGuard()

/**
 * 原生 tabBar 的 text 不能写进 pages.json 的 i18n，需在运行时按当前语言更新（仅 Tab 页）
 * @param {(key: string) => string} t  如 (k) => this.$t(k)
 */
export function syncTabBarText(t) {
  if (!isTabBarPage()) {
    return
  }
  TAB_KEYS.forEach((key, index) => {
    uni.setTabBarItem({
      index,
      text: t(key)
    })
  })
}
