"use client"

import { useEffect, useState } from "react"
import { useAuthStore } from "@/lib/api/auth-store"
import { useIsDemoApp } from "@/lib/demo/use-is-demo-app"

/** Wait for auth persist hydrate before enabling API queries. */
export function useAuthReady() {
  const isDemoApp = useIsDemoApp()
  // Always false on first render so SSR and hydration markup match; zustand
  // `hasHydrated()` can be true on the server (in-memory persist) before the
  // client has read localStorage.
  const [ready, setReady] = useState(false)
  const authenticated = useAuthStore((s) => s.isAuthenticated())

  useEffect(() => {
    if (isDemoApp) {
      setReady(true)
      return
    }
    if (useAuthStore.persist.hasHydrated()) {
      setReady(true)
      return
    }
    const unsub = useAuthStore.persist.onFinishHydration(() => setReady(true))
    return unsub
  }, [isDemoApp])

  return {
    ready: isDemoApp ? true : ready,
    authenticated: isDemoApp ? true : ready && authenticated,
  }
}
