import { PAGE_SEARCH_INDEX, PAGE_SEARCH_RESULT } from '@/utils/pageRoute'

/** 当前页路由（如 subpackage/search/result） */
function getCurrentRoute() {
  const pages = getCurrentPages()
  const page = pages[pages.length - 1]
  return (page && page.route) || ''
}

function isSearchResultRoute(route) {
  return route.includes('search/result')
}

function isSearchIndexRoute(route) {
  return route.includes('search/index')
}

/** 跳转搜索输入页 A */
export function goSearchInput(keyword) {
  const text = (keyword || '').trim()
  const url = text
    ? `${PAGE_SEARCH_INDEX}?keyword=${encodeURIComponent(text)}`
    : PAGE_SEARCH_INDEX

  const route = getCurrentRoute()
  // 从结果页「重新搜索」：替换当前页，避免栈变成 result → index 导致返回循环
  if (isSearchResultRoute(route)) {
    uni.redirectTo({ url })
    return
  }
  // 已在输入页：仅刷新当前页参数
  if (isSearchIndexRoute(route)) {
    uni.redirectTo({ url })
    return
  }
  uni.navigateTo({ url })
}

/** 跳转搜索结果页 B */
export function goSearchResult(keyword) {
  const text = (keyword || '').trim()
  if (!text) return
  const url = `${PAGE_SEARCH_RESULT}?keyword=${encodeURIComponent(text)}`

  const route = getCurrentRoute()
  // 已在结果页：改关键词时用替换，不叠一层
  if (isSearchResultRoute(route)) {
    uni.redirectTo({ url })
    return
  }
  uni.navigateTo({ url })
}

/** 输入页返回：若栈里下层仍是结果页，多退一层，防止 index ↔ result 循环 */
export function navigateBackFromSearchIndex() {
  const pages = getCurrentPages()
  if (pages.length >= 2) {
    const prev = pages[pages.length - 2]
    const prevRoute = (prev && prev.route) || ''
    if (isSearchResultRoute(prevRoute)) {
      uni.navigateBack({ delta: 2 })
      return
    }
  }
  uni.navigateBack({
    fail: () => {
      uni.switchTab({ url: '/pages/index/index' })
    }
  })
}
