import { useEffect, useRef } from 'react'
import { shouldRefresh, type ResourceKey } from '@/store/dataBus'

/**
 * Refresh logic for a tab that lives inside the single-page host (`pages/home`).
 *
 * Tabs are kept mounted and toggled via `active`, so there is no page `onShow`
 * per tab. Instead we refresh when:
 *  - the tab becomes active again (user switched back to it), or
 *  - the host returns to the foreground (`showTick` bumps after navigating back
 *    from a secondary page like publish/detail/edit),
 * and only when the resource is actually stale.
 *
 * The very first mount is skipped (the view's own mount-load handles first paint).
 */
export function useTabRefresh(
  key: ResourceKey,
  active: boolean,
  showTick: number,
  refresh: () => void
) {
  const refreshRef = useRef(refresh)
  refreshRef.current = refresh
  const prevActive = useRef(active)
  const prevTick = useRef(showTick)

  useEffect(() => {
    const becameActive = active && !prevActive.current
    const reShown = active && showTick !== prevTick.current
    prevActive.current = active
    prevTick.current = showTick
    if ((becameActive || reShown) && shouldRefresh(key)) refreshRef.current()
  }, [active, showTick, key])
}
