"use client"

import { useEffect, useState } from "react"

type PersistApi = {
  hasHydrated: () => boolean
  onFinishHydration: (fn: () => void) => () => void
}

/** True after a zustand `persist` store has rehydrated from storage (client-only). */
export function usePersistHydrated(store: { persist: PersistApi }): boolean {
  const [hydrated, setHydrated] = useState(() => store.persist.hasHydrated())

  useEffect(() => {
    if (store.persist.hasHydrated()) {
      setHydrated(true)
      return
    }
    return store.persist.onFinishHydration(() => setHydrated(true))
  }, [store])

  return hydrated
}
