import {useSyncExternalStore} from 'react'

const INTERVAL_MS = 5000

// a shared ticker for cycling display content (consumers take it modulo
// their own length); the interval runs only while something is subscribed
let index = 0
let timer: ReturnType<typeof setInterval> | null = null
const listeners = new Set<() => void>()

const subscribe = (listener: () => void) => {
  listeners.add(listener)
  timer ??= setInterval(() => {
    index++
    for (const notify of listeners) notify()
  }, INTERVAL_MS)
  return () => {
    listeners.delete(listener)
    if (!listeners.size && timer) {
      clearInterval(timer)
      timer = null
    }
  }
}

export const useCycleIndex = (): number =>
  useSyncExternalStore(subscribe, () => index)
