import { useEffect, useRef } from 'react'
import { useTabStore } from '../stores/tabStore'

/**
 * Keep-alive tabs never remount, so "load on mount" data goes stale.
 * Fires `callback` every time the given tab path becomes active again
 * (skips the initial mount, which pages already handle themselves).
 */
export function useOnTabActive(path: string, callback: () => void) {
  const activeKey = useTabStore((s) => s.activeKey)
  const first = useRef(true)
  const cbRef = useRef(callback)
  cbRef.current = callback

  useEffect(() => {
    if (activeKey !== path) return
    if (first.current) {
      first.current = false
      return
    }
    cbRef.current()
  }, [activeKey, path])
}
