// 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 { backgroundElementTemplateInstanceManager } from '../background/manager.js';
const pendingEvents = [];
let queuePendingEvents = false;
function dispatchEvent(eventValue, data) {
    const handler = backgroundElementTemplateInstanceManager.getRawAttributeValueByEventValue(eventValue);
    if (typeof __ALOG__ !== 'undefined' && __ALOG__) {
        console.alog?.(`[ReactLynxDebug] ElementTemplate BTS received event:\n${JSON.stringify({
            eventValue,
            type: data.type,
            jsFunctionName: typeof handler === 'function' ? handler.name : '',
            hasHandler: typeof handler === 'function',
        }, null, 2)}`);
    }
    if (typeof handler !== 'function') {
        return false;
    }
    try {
        handler(data);
    }
    catch (error) {
        lynx.reportError(error);
    }
    return true;
}
export function clearEventState() {
    pendingEvents.length = 0;
    queuePendingEvents = false;
}
export function resetEventStateForRuntime() {
    clearEventState();
    queuePendingEvents = true;
}
export function getEventHandlerForEventValue(eventValue) {
    const handler = backgroundElementTemplateInstanceManager.getRawAttributeValueByEventValue(eventValue);
    return typeof handler === 'function' ? handler : undefined;
}
export function publishEvent(eventValue, data) {
    if (dispatchEvent(eventValue, data)) {
        return;
    }
    if (queuePendingEvents) {
        pendingEvents.push([eventValue, data]);
    }
}
export function publicComponentEvent(_componentId, eventValue, data) {
    publishEvent(eventValue, data);
}
export function flushPendingEvents() {
    queuePendingEvents = false;
    if (pendingEvents.length === 0) {
        return;
    }
    const events = pendingEvents.splice(0);
    for (const [eventValue, data] of events) {
        dispatchEvent(eventValue, data);
    }
}
//# sourceMappingURL=event.js.map