import { ContextConsumer } from "@pie-players/pie-context";
import { assessmentToolkitHostRuntimeContext, assessmentToolkitRegionScopeContext, assessmentToolkitShellContext, assessmentToolkitRuntimeContext, } from "./assessment-toolkit-context.js";
function connectConsumerWithProviderRetry(host, context, onValue) {
    let hasValue = false;
    const consumer = new ContextConsumer(host, {
        context,
        subscribe: true,
        onValue: (value) => {
            hasValue = true;
            onValue(value);
        },
    });
    consumer.connect();
    const onContextProvider = (event) => {
        if (event.context !== context)
            return;
        consumer.requestValue();
    };
    host.addEventListener("context-provider", onContextProvider);
    let attempts = 0;
    const maxAttempts = 200;
    const retryTimer = globalThis.setInterval(() => {
        if (hasValue || attempts >= maxAttempts) {
            globalThis.clearInterval(retryTimer);
            return;
        }
        attempts += 1;
        consumer.requestValue();
    }, 50);
    return () => {
        globalThis.clearInterval(retryTimer);
        host.removeEventListener("context-provider", onContextProvider);
        consumer.disconnect();
    };
}
/**
 * Connect a DOM host element to the shared assessment toolkit runtime context.
 * Returns a cleanup function that disconnects the underlying consumer.
 */
export function connectAssessmentToolkitRuntimeContext(host, onValue) {
    return connectConsumerWithProviderRetry(host, assessmentToolkitRuntimeContext, onValue);
}
export function connectAssessmentToolkitHostRuntimeContext(host, onValue) {
    return connectConsumerWithProviderRetry(host, assessmentToolkitHostRuntimeContext, onValue);
}
export function connectAssessmentToolkitShellContext(host, onValue) {
    return connectConsumerWithProviderRetry(host, assessmentToolkitShellContext, onValue);
}
export function connectAssessmentToolkitRegionScopeContext(host, onValue) {
    return connectConsumerWithProviderRetry(host, assessmentToolkitRegionScopeContext, onValue);
}
//# sourceMappingURL=runtime-context-consumer.js.map