'use client'
import { useEffect, useState, useSyncExternalStore } from 'react'
// Global ref-count store. Any page can call useTopLoader(active) and the
// shared (mounted once in the dashboard layout) will reflect it.
let activeCount = 0
const listeners = new Set<() => void>()
function emit() { listeners.forEach(l => l()) }
function subscribe(cb: () => void) { listeners.add(cb); return () => { listeners.delete(cb) } }
function getSnapshot() { return activeCount }
export function useTopLoader(active: boolean) {
useEffect(() => {
if (!active) return
activeCount += 1
emit()
return () => {
activeCount = Math.max(0, activeCount - 1)
emit()
}
}, [active])
}
// Short tail so a sub-100ms fetch still shows the strip briefly.
const TAIL_MS = 350
export function TopLoader() {
const count = useSyncExternalStore(subscribe, getSnapshot, () => 0)
const [tailing, setTailing] = useState(false)
useEffect(() => {
if (count > 0) { setTailing(true); return }
const t = setTimeout(() => setTailing(false), TAIL_MS)
return () => clearTimeout(t)
}, [count])
if (count === 0 && !tailing) return null
return (
)
}