// Tab-press fan-out. The tab bar emits a route-keyed press event; tab
// screens subscribe by route name and react (typically scroll-to-top +
// refetch). Mirrors `scrollStore` shape — a tiny ad-hoc pub/sub keeps us
// off react-navigation's `addListener('tabPress', …)` path, which doesn't
// fire reliably under expo-router's `Stack.Screen` interposition (the
// screen's `useNavigation()` returns the inner stack navigator, not the
// outer tabs navigator that emits the event).

type Listener = () => void

const listenersByRoute = new Map<string, Set<Listener>>()

export const tabPressStore = {
  emit(routeName: string) {
    const set = listenersByRoute.get(routeName)
    if (!set) return
    for (const l of set) l()
  },
  subscribe(routeName: string, listener: Listener) {
    let set = listenersByRoute.get(routeName)
    if (!set) {
      set = new Set()
      listenersByRoute.set(routeName, set)
    }
    set.add(listener)
    return () => {
      set?.delete(listener)
      if (set && set.size === 0) listenersByRoute.delete(routeName)
    }
  },
}
