"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProfileCacheContext = void 0;
exports.ProfileCacheProvider = ProfileCacheProvider;
exports.useProfileCache = useProfileCache;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const streamplace_store_1 = require("../streamplace-store");
exports.ProfileCacheContext = (0, react_1.createContext)(null);
function ProfileCacheProvider({ children, }) {
    const agent = (0, streamplace_store_1.useUnauthenticatedBlueskyAppViewAgent)();
    const [profiles, setProfiles] = (0, react_1.useState)({});
    const agentRef = (0, react_1.useRef)(agent);
    agentRef.current = agent;
    const profilesRef = (0, react_1.useRef)(profiles);
    profilesRef.current = profiles;
    const inFlight = (0, react_1.useRef)(new Set());
    const pending = (0, react_1.useRef)(new Set());
    const timer = (0, react_1.useRef)(null);
    const flush = (0, react_1.useCallback)(() => {
        timer.current = null;
        if (!agentRef.current)
            return;
        const toFetch = [...pending.current]
            .filter((d) => !(d in profilesRef.current) && !inFlight.current.has(d))
            .slice(0, 25);
        toFetch.forEach((d) => pending.current.delete(d));
        if (toFetch.length === 0)
            return;
        // If there are more beyond the batch limit, schedule the remainder
        if (pending.current.size > 0) {
            timer.current = setTimeout(flush, 0);
        }
        toFetch.forEach((d) => inFlight.current.add(d));
        agentRef.current
            .getProfiles({ actors: toFetch })
            .then((result) => {
            const newProfiles = {};
            result.data.profiles.forEach((p) => {
                newProfiles[p.did] = p;
            });
            setProfiles((prev) => ({ ...prev, ...newProfiles }));
        })
            .catch((e) => {
            console.error("Failed to fetch profiles", e);
        })
            .finally(() => {
            toFetch.forEach((d) => inFlight.current.delete(d));
        });
    }, []);
    const requestProfiles = (0, react_1.useCallback)((dids) => {
        const toQueue = dids.filter((d) => !(d in profilesRef.current) && !inFlight.current.has(d));
        if (toQueue.length === 0)
            return;
        toQueue.forEach((d) => pending.current.add(d));
        if (!timer.current) {
            timer.current = setTimeout(flush, 50);
        }
    }, [flush]);
    const value = (0, react_1.useMemo)(() => ({ profiles, requestProfiles }), [profiles, requestProfiles]);
    return ((0, jsx_runtime_1.jsx)(exports.ProfileCacheContext.Provider, { value: value, children: children }));
}
function useProfileCache() {
    const ctx = (0, react_1.useContext)(exports.ProfileCacheContext);
    if (!ctx) {
        throw new Error("useProfileCache must be used within ProfileCacheProvider");
    }
    return ctx;
}
//# sourceMappingURL=profile-cache.js.map