"use client";
import { useEffect, useRef, useState } from "react";
import { useStigmer } from "../hooks";
import { toError } from "../internal/toError";
/**
 * Data hook that fetches the current authenticated user's
 * {@link IdentityAccount} via `identityAccount.whoAmI()`.
 *
 * The result is cached for the lifetime of the `Stigmer` client
 * instance — subsequent mounts and re-renders reuse the cached
 * value without additional network calls.
 *
 * Useful for self-protection in access management UIs (disabling
 * "remove" or "change role" on the current user) and displaying
 * a "You" indicator.
 *
 * @example
 * ```tsx
 * const { account } = useWhoAmI();
 * const myId = account?.metadata?.id;
 * ```
 */
export function useWhoAmI() {
    const stigmer = useStigmer();
    const [account, setAccount] = useState(null);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState(null);
    const cacheRef = useRef(null);
    useEffect(() => {
        if (cacheRef.current?.client === stigmer && cacheRef.current.account) {
            setAccount(cacheRef.current.account);
            setIsLoading(false);
            return;
        }
        const cancelled = { current: false };
        stigmer.identityAccount
            .whoAmI()
            .then((result) => {
            if (cancelled.current)
                return;
            cacheRef.current = { client: stigmer, account: result };
            setAccount(result);
            setIsLoading(false);
        }, (err) => {
            if (cancelled.current)
                return;
            setError(toError(err));
            setIsLoading(false);
        });
        return () => {
            cancelled.current = true;
        };
    }, [stigmer]);
    return { account, isLoading, error };
}
//# sourceMappingURL=useWhoAmI.js.map