export const createModeRequestCoordinator = (initialMode) => {
    let selectedMode = initialMode;
    let activeRequest = null;

    return {
        getSelectedMode: () => selectedMode,

        run: async (mode, startRequest, { ensureFresh = false } = {}) => {
            selectedMode = mode;
            let requiresFresh = ensureFresh;

            while (activeRequest) {
                if (activeRequest.mode === mode && !requiresFresh) {
                    return activeRequest.promise;
                }

                try {
                    await activeRequest.promise;
                } catch {
                    // A conflicting or stale request must not block the requested mode.
                }
                requiresFresh = false;
            }

            const request = Promise.resolve().then(startRequest);
            const trackedRequest = request.finally(() => {
                if (activeRequest?.promise === trackedRequest) {
                    activeRequest = null;
                }
            });

            activeRequest = { mode, promise: trackedRequest };

            return trackedRequest;
        },
    };
};
