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'
])

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 getPublicPathPrefixes() {
  const prefixes = ['bqH5/', 'bqjy/']
  try {
    const envPath = String(import.meta.env.VITE_APP_PUBLIC_PATH || '')
      .trim()
      .replace(/^\/|\/$/g, '')
    if (envPath) {
      const withSlash = `${envPath}/`
      if (!prefixes.includes(withSlash)) {
        prefixes.unshift(withSlash)
      }
    }
  } catch (e) {
    // ignore
  }
  return prefixes
}

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

/**
 * 当前栈顶是否为 TabBar 页（与 ruoyi-jiaoyi 一致：按 route 判断，非 Tab 页拦截全部 TabBar API）
 */
export function isTabBarPage() {
  const stack = getCurrentPages()
  if (!stack.length) {
    return false
  }
  const cur = stack[stack.length - 1]
  const route = normalizePageRoute(cur.route || cur.$page?.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
        }
      }
    })
  })
}

readUniTabPagePaths()
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)
    })
  })
}
