// Copyright 2026 The Lynx Authors. All rights reserved.
// Licensed under the Apache License Version 2.0 that can be found in the
// LICENSE file in the root directory of this source tree.
import { onFunctionCall } from './return-value.js';
import { isSdkVersionGt } from '../../utils.js';
import { WorkletEvents } from '../../worklet-runtime/bindings/events.js';
import { registerBackgroundFunctionCtx } from '../background-function/run-on-background.js';
export let delayedRunOnMainThreadData = [];
export function enqueueDelayedRunOnMainThreadData(data) {
    delayedRunOnMainThreadData.push(data);
}
export function takeDelayedRunOnMainThreadData() {
    const data = delayedRunOnMainThreadData;
    delayedRunOnMainThreadData = [];
    return data;
}
/**
 * @internal
 */
export function createRunOnMainThread(options) {
    return (fn) => {
        if (__LEPUS__) {
            throw new Error('runOnMainThread can only be used on the background thread.');
        }
        if (!isMainThreadFunctionSupported()) {
            throw new Error('runOnMainThread requires Lynx sdk version 2.14.');
        }
        return async (...params) => {
            return new Promise((resolve) => {
                const worklet = fn;
                prepareMainThreadFunctionCtx(worklet);
                const data = {
                    worklet,
                    params,
                    resolveId: onFunctionCall(resolve),
                };
                if (options.shouldDispatchRunOnMainThreadDirectly()) {
                    dispatchRunOnMainThreadEvent(data);
                    return;
                }
                enqueueDelayedRunOnMainThreadData(data);
            });
        };
    };
}
function isMainThreadFunctionSupported() {
    return isSdkVersionGt(2, 13);
}
function isRunOnBackgroundSupported() {
    return isSdkVersionGt(2, 15);
}
function isMainThreadFunctionCtx(value) {
    return value != null
        && typeof value === 'object'
        && !Array.isArray(value)
        && typeof value._wkltId === 'string';
}
function prepareMainThreadFunctionCtx(worklet) {
    if (isMainThreadFunctionCtx(worklet) && isRunOnBackgroundSupported()) {
        registerBackgroundFunctionCtx(worklet);
    }
}
function dispatchRunOnMainThreadEvent(data) {
    lynx.getCoreContext().dispatchEvent({
        type: WorkletEvents.runWorkletCtx,
        data: JSON.stringify(data),
    });
}
//# sourceMappingURL=main-thread.js.map