import Taro from '@tarojs/taro'
import type { MainTabKey } from '@/components/navigation/BottomTabBar/tabConfig'

// Lets a secondary page (e.g. publish → "去广场") ask the single-page host to
// switch to a specific tab after navigating back. The host consumes this on its
// next onShow.

let requested: MainTabKey | null = null
const HOME_TAB_REQUEST_EVENT = 'wq:homeTabRequest'

export function requestTab(key: MainTabKey) {
  requested = key
  Taro.eventCenter.trigger(HOME_TAB_REQUEST_EVENT, key)
}

export function consumeRequestedTab(): MainTabKey | null {
  const next = requested
  requested = null
  return next
}

export function onRequestedTab(handler: (key: MainTabKey) => void): () => void {
  Taro.eventCenter.on(HOME_TAB_REQUEST_EVENT, handler)
  return () => Taro.eventCenter.off(HOME_TAB_REQUEST_EVENT, handler)
}
