"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BACKGROUND_MESSAGE_HANDLERS = void 0;
const messages_1 = require("../sharedUtils/messages");
const recording_1 = require("./recording");
const domUtils_1 = require("../sharedUtils/domUtils");
const walkthrough_1 = require("../sharedUtils/walkthrough");
const eventMessages_1 = require("../sharedUtils/eventMessages");
const findTools_1 = require("./findTools");
const actions_1 = require("./actions");
const util_1 = require("./eventHandlers/util");
const GenerationCursorHandler_1 = __importDefault(require("./eventHandlers/GenerationCursorHandler"));
const PlaywrightBridge_1 = require("./PlaywrightBridge");
const mablscriptFind_1 = require("@mablhq/test-model/mablscriptFind");
exports.BACKGROUND_MESSAGE_HANDLERS = {
    [messages_1.SET_RECORDING_STATE]: (request) => {
        if ((0, eventMessages_1.isLegacyInboundMessageRequest)(request) &&
            typeof request?.updateValue === 'boolean') {
            recording_1.store.setRecordingState(request.updateValue);
        }
    },
    [messages_1.SET_REPLAY_STATE]: (request) => {
        if ((0, eventMessages_1.isLegacyInboundMessageRequest)(request) &&
            typeof request?.updateValue === 'boolean') {
            recording_1.store.setReplayState(request.updateValue);
        }
    },
    [messages_1.SET_WALKTHROUGH_STATE]: (request) => {
        if ((0, eventMessages_1.isLegacyInboundMessageRequest)(request) &&
            typeof request?.updateValue === 'string') {
            try {
                const walkthroughState = JSON.parse(request.updateValue);
                const { activeContext, isInProgress, isReplaying, shouldDisplaySelectionOverlay, } = walkthroughState;
                if (!isInProgress) {
                    return;
                }
                recording_1.store.setWalkthroughState(walkthroughState);
                if (window.mablFrameInfo.tabId !== 'initial') {
                    return;
                }
                if (isReplaying) {
                    return;
                }
                const isActiveContext = activeContext === walkthrough_1.ActiveWalkthroughContext.BROWSER;
                const handleOverlay = () => (0, recording_1.handleWalkthroughOverlay)(!isActiveContext, !!shouldDisplaySelectionOverlay);
                if (window.document.readyState === 'loading') {
                    window.document.addEventListener('readystatechange', (event) => {
                        if (event.target?.readyState === 'interactive') {
                            handleOverlay();
                        }
                    });
                }
                else {
                    handleOverlay();
                }
                if (window.__mablWalkthroughConfigured) {
                    return;
                }
                configureWalkthroughListeners();
                window.__mablWalkthroughConfigured = true;
            }
            catch (error) {
                throw new Error('Issue configuring guided walkthrough');
            }
        }
    },
    [messages_1.SET_HOVER_CAPTURE_STATE]: (request) => {
        if ((0, eventMessages_1.isLegacyInboundMessageRequest)(request) &&
            typeof request?.updateValue === 'boolean') {
            recording_1.store.setCaptureHoversState(request.updateValue);
        }
    },
    [messages_1.SET_HOVER_XPATH_TO_INDEX]: (request) => {
        if ((0, eventMessages_1.isLegacyInboundMessageRequest)(request) &&
            typeof request?.updateValue === 'object') {
            recording_1.store.setHoverXpathToIndexState(request.updateValue);
        }
    },
    [messages_1.INVALIDATE_TRAINING_STATUS]: recording_1.checkStatusOnReload,
    [messages_1.QUERY_OVERLAY]: recording_1.handleQueryOverlay,
    [messages_1.BLOCKING_OVERLAY]: recording_1.handleBlockingOverlay,
    [messages_1.GENERATION_BLOCKING_OVERLAY]: recording_1.handleGenerationCursor,
    [messages_1.SET_SELECTION_MODE]: (request) => (0, recording_1.handleSetSelectionListener)(request),
    [messages_1.START_LISTENERS]: recording_1.handleStartListeners,
    [messages_1.STOP_LISTENERS]: recording_1.stopRecordingListeners,
    [messages_1.FIND_ELEMENT_AT_LOCATION]: (request) => findElementAtLocation(request),
    [mablscriptFind_1.FIND_SCROLLABLE_ELEMENTS]: (request) => (0, mablscriptFind_1.findScrollableElements)(request),
    [messages_1.FIND_ALL_IFRAMES]: findAllIframes,
    [messages_1.INTERACT_WITH_CONTENT]: handleInteractWithContent,
};
if (window.__mablInit) {
    throw new Error('Script already loaded and initialized');
}
window.__mabltron = true;
window.addEventListener('beforeunload', () => {
    try {
        GenerationCursorHandler_1.default.forceCleanupAll();
        console.debug('Cleaned up cursor on page unload');
    }
    catch (error) {
        console.warn('Failed to cleanup cursor on page unload:', error);
    }
});
document.addEventListener('visibilitychange', () => {
    if (document.visibilityState === 'hidden') {
        window.setTimeout(() => {
            if (document.visibilityState === 'hidden') {
                try {
                    GenerationCursorHandler_1.default.forceCleanupAll();
                    console.debug('Cleaned up cursor on prolonged visibility hidden');
                }
                catch (error) {
                    console.warn('Failed to cleanup cursor on visibility change:', error);
                }
            }
        }, 5000);
    }
});
async function messageListener(request) {
    if ((0, eventMessages_1.isLegacyInboundMessageRequest)(request) && request.detail) {
        request = request.detail;
    }
    const handler = exports.BACKGROUND_MESSAGE_HANDLERS[request.action];
    if (handler) {
        const response = handler(request);
        if ((0, util_1.isPromise)(response)) {
            const resolvedResponse = await response;
            return resolvedResponse;
        }
    }
    return Promise.resolve();
}
try {
    configureWindowFocusListener();
}
catch (error) {
    throw new Error('Issue starting message listener');
}
const playwrightBridge = (0, PlaywrightBridge_1.createPlaywrightBridge)(messageListener);
window.__mabl = {
    bridge: playwrightBridge,
    messageListener,
};
try {
    if (window.__mablIsWalkthrough && window.mablFrameInfo.tabId === 'initial') {
        void (0, recording_1.fetchWalkthroughState)();
    }
}
catch (error) {
    throw new Error('Issue fetching walkthrough state');
}
if (document.readyState === 'complete') {
    void (0, recording_1.checkStatusOnReload)();
}
else {
    window.addEventListener('DOMContentLoaded', recording_1.checkStatusOnReload, true);
    void (0, recording_1.checkStatusOnReload)();
}
function findAllIframes(messageRequest) {
    if (!(0, eventMessages_1.isFindAllIframesRequest)(messageRequest)) {
        return Promise.resolve(undefined);
    }
    const iframeElements = document.querySelectorAll('iframe');
    const message = {
        message: {
            count: iframeElements.length,
            success: true,
        },
        iframes: [...iframeElements.values()],
    };
    return Promise.resolve(message);
}
function handleInteractWithContent(request) {
    if (!(0, eventMessages_1.isLegacyInboundMessageRequest)(request)) {
        return;
    }
    switch (request.actionType) {
        case 'enter_text':
            if (request.target && request.metadata?.inputData) {
                insertText(request.target, request.metadata.inputData).catch((error) => console.error('Could not interact with content [enter text]', error));
            }
    }
}
async function findElementAtLocation(request) {
    const selectorTarget = request.selectorTarget;
    if (isBoundingBoxSelectorTarget(selectorTarget)) {
        const eventMessage = await (0, findTools_1.findElementByLocation)({
            targetPoint: selectorTarget.targetPoint,
            boundingBox: selectorTarget.boundingBox,
            toolCall: selectorTarget.toolCall,
        });
        if (eventMessage) {
            eventMessage.payload = (0, actions_1.decorateEventMessage)(eventMessage.payload);
        }
        return eventMessage;
    }
    console.warn('Discarding misformatted find element by location request');
    return undefined;
}
function isBoundingBoxSelectorTarget(target) {
    return target.boundingBox !== undefined;
}
async function insertText(target, inputData) {
    const element = (0, domUtils_1.getElementMatchingSelectionTarget)(target);
    try {
        if (element) {
            recording_1.inputEventHandler.setSelectionTarget(target);
            if (target.variable) {
                await recording_1.inputEventHandler.recordInsertVariableValueAsText(element, inputData);
            }
            else {
                await recording_1.inputEventHandler.recordInsertText(element, inputData);
            }
        }
    }
    finally {
        recording_1.inputEventHandler.clearSelectionTarget();
    }
}
function configureWindowFocusListener() {
    window.addEventListener('focus', async () => {
        await playwrightBridge.sendToMain({
            action: messages_1.CONTENT_FOCUS_EVENT,
            frameInfo: window.mablFrameInfo,
        });
    }, false);
}
function configureWalkthroughListeners() {
    function processMessage(payload) {
        switch (payload?.message) {
            case walkthrough_1.WalkthroughMessage.WALKTHROUGH_PENDO_IS_READY:
            case walkthrough_1.WalkthroughMessage.WALKTHROUGH_PENDO_GUIDES_LOADED:
            case walkthrough_1.WalkthroughMessage.WALKTHROUGH_PENDO_GUIDES_FAILED:
            case walkthrough_1.WalkthroughMessage.SWITCH_CONTEXT:
                void playwrightBridge.sendToMain({
                    ...payload,
                    action: messages_1.WALKTHROUGH_MESSAGE,
                });
                break;
        }
    }
    window.addEventListener('message', (event) => {
        if (event.data?.messageType === walkthrough_1.PENDO_TO_ELECTRON_MESSAGE &&
            window.__mablWalkthroughAppUrl &&
            event.origin === window.__mablWalkthroughAppUrl) {
            event.stopImmediatePropagation();
            processMessage(event.data.payload);
        }
    }, true);
}
