"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.store = exports.inputEventHandler = void 0;
exports.initializeState = initializeState;
exports.handleQueryOverlay = handleQueryOverlay;
exports.handleBlockingOverlay = handleBlockingOverlay;
exports.handleGenerationCursor = handleGenerationCursor;
exports.handleWalkthroughOverlay = handleWalkthroughOverlay;
exports.setActiveClickEventHandler = setActiveClickEventHandler;
exports.handleSetSelectionListener = handleSetSelectionListener;
exports.handleStartListeners = handleStartListeners;
exports.startRecordingListeners = startRecordingListeners;
exports.stopRecordingListeners = stopRecordingListeners;
exports.checkStatusOnReload = checkStatusOnReload;
exports.fetchWalkthroughState = fetchWalkthroughState;
const iFrameTracking_1 = require("../sharedUtils/iFrameTracking");
const messages_1 = require("../sharedUtils/messages");
const mablscriptFind_1 = require("@mablhq/test-model/mablscriptFind");
const pdfUtils_1 = require("../sharedUtils/pdfUtils");
const customTestIdAttributesProvider_1 = require("../sharedUtils/customTestIdAttributesProvider");
const StateStore_1 = require("./StateStore");
const util_1 = require("./eventHandlers/util");
const MouseClickEventHandler_1 = __importDefault(require("./eventHandlers/MouseClickEventHandler"));
const MouseHoverEventHandler_1 = __importDefault(require("./eventHandlers/MouseHoverEventHandler"));
const InputEventHandler_1 = __importDefault(require("./eventHandlers/InputEventHandler"));
const BlockingOverlayHandler_1 = __importDefault(require("./eventHandlers/BlockingOverlayHandler"));
const KeyPressEventHandler_1 = __importDefault(require("./eventHandlers/KeyPressEventHandler"));
const PdfEventHandler_1 = __importDefault(require("./eventHandlers/PdfEventHandler"));
const QueryOverlayHandler_1 = __importDefault(require("./eventHandlers/QueryOverlayHandler"));
const SelectionClickEventHandler_1 = __importDefault(require("./eventHandlers/SelectionClickEventHandler"));
const WalkthroughOverlayHandler_1 = __importDefault(require("./eventHandlers/WalkthroughOverlayHandler"));
const eventMessages_1 = require("../sharedUtils/eventMessages");
const VisualSelectionHandler_1 = require("./eventHandlers/VisualSelectionHandler");
const GenerationCursorHandler_1 = __importDefault(require("./eventHandlers/GenerationCursorHandler"));
let selectorCache;
let listenersOn = false;
let keypressEventHandler;
let mouseClickEventHandler;
let mouseHoverEventHandler;
let queryOverlayHandler;
let walkthroughOverlayHandler;
let blockingOverlayHandler;
let generationCursor;
let selectionClickEventHandler;
let visualSelectionEventHandler;
let pdfEventHandler;
let activeClickEventHandler;
let listenersInitialized = false;
let walkthroughOverlayInitialized = false;
exports.store = new StateStore_1.StateStore();
window.__mablStore = exports.store;
(0, customTestIdAttributesProvider_1.setCustomTestIdAttributesProvider)(util_1.getCustomTestIdAttributes);
function initializeState() {
    exports.store = new StateStore_1.StateStore();
}
function handleQueryOverlay(request) {
    if ((0, eventMessages_1.isLegacyInboundMessageRequest)(request) && request.active) {
        initializeListenersIfNeeded();
        if (request.update) {
            queryOverlayHandler.update(request.selectorTarget);
        }
        else {
            setActiveClickEventHandler(queryOverlayHandler);
        }
    }
    else {
        setActiveClickEventHandler(mouseClickEventHandler);
    }
}
function handleBlockingOverlay(request) {
    if ((0, eventMessages_1.isLegacyInboundMessageRequest)(request) && request.active) {
        initializeListenersIfNeeded();
        setActiveClickEventHandler(blockingOverlayHandler);
    }
    else {
        setActiveClickEventHandler(mouseClickEventHandler);
    }
}
function handleGenerationCursor(request) {
    if (!(0, eventMessages_1.isLegacyInboundMessageRequest)(request)) {
        return;
    }
    if (request.active) {
        initializeListenersIfNeeded();
        setActiveClickEventHandler(generationCursor);
    }
    else {
        setActiveClickEventHandler(mouseClickEventHandler);
        try {
            GenerationCursorHandler_1.default.forceCleanupAll();
        }
        catch (error) {
            console.warn('[Recording] Failed to force cleanup cursor:', error);
        }
    }
}
function handleWalkthroughOverlay(activate, shouldDisplaySelectionOverlay) {
    if (activate) {
        if (!walkthroughOverlayInitialized) {
            walkthroughOverlayHandler = new WalkthroughOverlayHandler_1.default();
            walkthroughOverlayInitialized = true;
        }
        walkthroughOverlayHandler.register();
    }
    else {
        walkthroughOverlayHandler?.unregister();
    }
    if (shouldDisplaySelectionOverlay) {
        initializeListenersIfNeeded();
        setActiveClickEventHandler(selectionClickEventHandler);
    }
}
function setActiveClickEventHandler(listener) {
    if (activeClickEventHandler) {
        activeClickEventHandler.unregister();
    }
    activeClickEventHandler = listener;
    if (listener) {
        listener.register();
    }
}
function handleSetSelectionListener(request) {
    if (request.active) {
        initializeListenersIfNeeded();
        if (request.overlayHighlightType === 'visual') {
            if (!request.stepId) {
                console.error('Step ID is required for visual selection');
                if (visualSelectionEventHandler) {
                    visualSelectionEventHandler.deactivate();
                }
                if (mouseClickEventHandler) {
                    setActiveClickEventHandler(mouseClickEventHandler);
                }
                return;
            }
            visualSelectionEventHandler.activate(request.stepId);
        }
        else {
            selectionClickEventHandler.setSelectionModeCause(request.selectionModeCause);
            setActiveClickEventHandler(selectionClickEventHandler);
        }
    }
    else {
        if (visualSelectionEventHandler) {
            visualSelectionEventHandler.deactivate();
        }
        if (mouseClickEventHandler) {
            setActiveClickEventHandler(mouseClickEventHandler);
        }
    }
}
function handleStartListeners() {
    if (!listenersOn) {
        startRecordingListeners();
    }
}
function startRecordingListeners() {
    if (window.__mablListenersRegistered) {
        console.debug('[Recording] Listeners already registered, skipping duplicate registration');
        listenersOn = true;
        return;
    }
    initializeListenersIfNeeded();
    selectorCache = new mablscriptFind_1.ElementFullSelectorCache();
    mouseHoverEventHandler.register();
    setActiveClickEventHandler(mouseClickEventHandler);
    exports.inputEventHandler.register();
    keypressEventHandler.register();
    queryOverlayHandler = new QueryOverlayHandler_1.default(exports.store, selectorCache);
    blockingOverlayHandler = new BlockingOverlayHandler_1.default(exports.store, selectorCache);
    generationCursor = new GenerationCursorHandler_1.default();
    pdfEventHandler = new PdfEventHandler_1.default(exports.store);
    listenersOn = true;
    window.__mablListenersRegistered = true;
}
function initializeRecordingListeners() {
    selectorCache = new mablscriptFind_1.ElementFullSelectorCache();
    mouseHoverEventHandler = new MouseHoverEventHandler_1.default(exports.store, selectorCache);
    mouseClickEventHandler = new MouseClickEventHandler_1.default(mouseHoverEventHandler, exports.store, selectorCache);
    exports.inputEventHandler = new InputEventHandler_1.default(mouseHoverEventHandler, exports.store, selectorCache);
    keypressEventHandler = new KeyPressEventHandler_1.default(mouseHoverEventHandler, exports.store, selectorCache);
    selectionClickEventHandler = new SelectionClickEventHandler_1.default(mouseHoverEventHandler, exports.store, selectorCache);
    visualSelectionEventHandler = new VisualSelectionHandler_1.VisualSelectionEventHandler(exports.store);
    queryOverlayHandler = new QueryOverlayHandler_1.default(exports.store, selectorCache);
    blockingOverlayHandler = new BlockingOverlayHandler_1.default(exports.store, selectorCache);
    generationCursor = new GenerationCursorHandler_1.default();
    pdfEventHandler = new PdfEventHandler_1.default(exports.store);
    listenersInitialized = true;
}
function initializeListenersIfNeeded() {
    if (!listenersInitialized) {
        initializeRecordingListeners();
    }
}
function stopRecordingListeners() {
    [
        blockingOverlayHandler,
        exports.inputEventHandler,
        keypressEventHandler,
        mouseClickEventHandler,
        mouseHoverEventHandler,
        pdfEventHandler,
        selectionClickEventHandler,
        walkthroughOverlayHandler,
    ]
        .filter((handler) => handler)
        .forEach((handler) => handler.unregister());
    listenersOn = false;
    window.__mablListenersRegistered = false;
}
async function checkStatusOnReload() {
    const response = await window.__mabl.bridge.sendToMain({
        action: messages_1.CHECK_TRAINING_STATUS,
    });
    if (!(response.trainingStatusForTab || response.trainerIsActive)) {
        return;
    }
    window.__mablInit = true;
    if (!exports.store.state) {
        initializeState();
    }
    exports.store.setRecordingState(response.recordingStateActive);
    exports.store.setCaptureHoversState(response.captureHovers);
    exports.store.setCustomTestIdAttributes(response.customTestIdAttributes);
    exports.store.setReplayState(response.replayRunning);
    if (response.trackIframes) {
        (0, iFrameTracking_1.createFrameMessageListener)();
        (0, iFrameTracking_1.createParentFrameMessageListener)();
        (0, iFrameTracking_1.requestIframeInfoFromParent)();
    }
    (0, iFrameTracking_1.createFrameSpatialListener)();
    (0, iFrameTracking_1.requestFrameSpatialFromParent)();
    (0, iFrameTracking_1.createScrollSpatialRefreshListener)();
    if (response.recordingStateActive) {
        handleStartListeners();
    }
    (0, pdfUtils_1.patchRevokeObjectURL)();
    const frameElementInfo = (0, iFrameTracking_1.getIframeElementInfo)();
    if (response.trackIframes) {
        (0, iFrameTracking_1.ensureContentIsTracked)().catch((error) => {
            console.error('Issue ensuring content is tracked', error);
        });
    }
    await window.__mabl.bridge.sendToMain({
        action: messages_1.CONTENT_RELOADED,
        frameElementInfo,
        frameInfo: window.mablFrameInfo,
    });
}
async function fetchWalkthroughState() {
    await window.__mabl.bridge.sendToMain({ action: messages_1.CHECK_WALKTHROUGH_STATUS });
}
