"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MABL_INSERTED_ELEMENTS = exports.MABL_HIGHLIGHT_CAPTION_ID = exports.MABL_IGNORE_ELEMENT_CLASS = exports.MABL_OVERLAY_ATTENTION_CLASS = exports.MABL_OVERLAY_SUBTEXT_CLASS = exports.MABL_OVERLAY_TEXT_CLASS = exports.MABL_VISUAL_SELECTION_RECT_CLASS = exports.MABL_VISUAL_SELECTION_OVERLAY_CLASS = exports.MABL_OVERLAY_CLASS = exports.MABL_DRAGGABLE_DIV_ID = exports.MABL_SECONDARY_IFRAME_ID = exports.MABL_DRAGGABLE_IFRAME_ID = exports.MABL_IFRAME_ID = exports.MABL_WALKTHROUGH_OVERLAY_ID = exports.MABL_HIGHLIGHT_ID = exports.MABL_OVERLAY_SUBTEXT_ID = exports.MABL_OVERLAY_TEXT_ID = exports.MABL_VISUAL_SELECTION_OVERLAY_ID = exports.MABL_OVERLAY_ID = void 0;
exports.compareElements = compareElements;
exports.isIgnoredElement = isIgnoredElement;
exports.isSelect = isSelect;
exports.createIgnoredDomElement = createIgnoredDomElement;
exports.getTagNameFromElement = getTagNameFromElement;
exports.getElementValueFromElement = getElementValueFromElement;
exports.getSelectedIndexFromElement = getSelectedIndexFromElement;
exports.getSelectedTextFromElement = getSelectedTextFromElement;
exports.enablePointerEventForDisabledElements = enablePointerEventForDisabledElements;
exports.insertOverlayStyles = insertOverlayStyles;
exports.createHighlightBox = createHighlightBox;
exports.getElementsAtPosition = getElementsAtPosition;
exports.adjustTarget = adjustTarget;
exports.getSelectionRepeats = getSelectionRepeats;
exports.getElementMatchingSelectionTarget = getElementMatchingSelectionTarget;
exports.pixels = pixels;
exports.isThisAnIframe = isThisAnIframe;
exports.getInputTypeFromElement = getInputTypeFromElement;
exports.isHTMLElement = isHTMLElement;
exports.isHTMLInputElement = isHTMLInputElement;
exports.isHTMLSelectElement = isHTMLSelectElement;
exports.hasShadowRoot = hasShadowRoot;
exports.isInputField = isInputField;
exports.getAllElementsBySelectors = getAllElementsBySelectors;
exports.getElementToHighlightFromPoints = getElementToHighlightFromPoints;
exports.positionSelectionHighlight = positionSelectionHighlight;
exports.highlightElement = highlightElement;
exports.highlightSimilarElements = highlightSimilarElements;
exports.removeOverlayById = removeOverlayById;
exports.destroySelectionOverlay = destroySelectionOverlay;
exports.renderWalkthroughOverlay = renderWalkthroughOverlay;
exports.destroyWalkthroughOverlay = destroyWalkthroughOverlay;
exports.destroyElement = destroyElement;
exports.isFileInput = isFileInput;
exports.renderSelectionOverlay = renderSelectionOverlay;
exports.getIframesInfo = getIframesInfo;
const dom_util_1 = require("@mablhq-internal/mablscript-find/dom-util");
const mablscriptFind_1 = require("@mablhq/test-model/mablscriptFind");
const browser_1 = require("@mablhq-internal/mablscript-find/browser");
const walkthrough_1 = require("./walkthrough");
exports.MABL_OVERLAY_ID = 'mabl-selection-overlay-22b76b1b-4c57-4644-98ab-6f2ff555d1cc';
exports.MABL_VISUAL_SELECTION_OVERLAY_ID = 'mabl-visual-selection-overlay-043471e0-6b1a-4a99-b522-1e454031e2ee';
exports.MABL_OVERLAY_TEXT_ID = 'mabl-selection-overlay-text-22b76b1b-4c57-4644-98ab-6f2ff555d1cc';
exports.MABL_OVERLAY_SUBTEXT_ID = 'mabl-selection-overlay-subtext-22b76b1b-4c57-4644-98ab-6f2ff555d1cc';
exports.MABL_HIGHLIGHT_ID = 'mabl-selection-highlight-22b76b1b-4c57-4644-98ab-6f2ff555d1cc';
exports.MABL_WALKTHROUGH_OVERLAY_ID = 'mabl-walkthrough-overlay-22b76b1b-4c57-4644-98ab-6f2ff555d1cc';
exports.MABL_IFRAME_ID = 'mabl-floating-trainer-22b76b1b-4c57-4644-98ab-6f2ff555d1cc';
exports.MABL_DRAGGABLE_IFRAME_ID = 'mabl-draggable-iframe-22b76b1b-4c57-4644-98ab-6f2ff555d1cc';
exports.MABL_SECONDARY_IFRAME_ID = 'mabl-secondary-iframe-22b76b1b-4c57-4644-98ab-6f2ff555d1cc';
exports.MABL_DRAGGABLE_DIV_ID = 'mabl-draggable-div-22b76b1b-4c57-4644-98ab-6f2ff555d1cc';
exports.MABL_OVERLAY_CLASS = 'mabl-selection-overlay-22b76b1b-4c57-4644-98ab-6f2ff555d1cc';
exports.MABL_VISUAL_SELECTION_OVERLAY_CLASS = 'mabl-visual-selection-overlay-22b76b1b-4c57-4644-98ab-6f2ff555d1cc';
exports.MABL_VISUAL_SELECTION_RECT_CLASS = 'mabl-visual-selection-rect-22b76b1b-4c57-4644-98ab-6f2ff555d1cc';
exports.MABL_OVERLAY_TEXT_CLASS = 'mabl-selection-overlay-text-22b76b1b-4c57-4644-98ab-6f2ff555d1cc';
exports.MABL_OVERLAY_SUBTEXT_CLASS = 'mabl-selection-overlay-subtext-22b76b1b-4c57-4644-98ab-6f2ff555d1cc';
exports.MABL_OVERLAY_ATTENTION_CLASS = 'mabl-selection-overlay-attention-22b76b1b-4c57-4644-98ab-6f2ff555d1cc';
exports.MABL_IGNORE_ELEMENT_CLASS = 'mabl-element-ignore-actions';
const MABL_HIGHLIGHT_BOX_CLASS = 'mabl-selection-highlight-box-22b76b1b-4c57-4644-98ab-6f2ff555d1cc';
exports.MABL_HIGHLIGHT_CAPTION_ID = 'mabl-selection-highlight-caption-22b76b1b-4c57-4644-98ab-6f2ff555d1cc';
const MABL_WALKTHROUGH_OVERLAY_CLASS = 'mabl-walkthrough-overlay-22b76b1b-4c57-4644-98ab-6f2ff555d1cc';
const MABL_OVERLAY_CAPTION_CLASS = 'mabl-selection-overlay-caption-22b76b1b-4c57-4644-98ab-6f2ff555d1cc';
const MABL_OVERLAY_LABEL_CLASS = 'mabl-selection-overlay-label-22b76b1b-4c57-4644-98ab-6f2ff555d1cc';
const MABL_OVERLAY_ATTENTION_DURATION = '2s';
const MABL_OVERLAY_ATTENTION_DELAY = '15s';
const MABL_OVERLAY_ATTENTION_ITERATIONS = 'infinite';
const HIGHLIGHT_BOX_BORDER_WIDTH = 2;
exports.MABL_INSERTED_ELEMENTS = [
    exports.MABL_OVERLAY_ID,
    exports.MABL_OVERLAY_TEXT_ID,
    exports.MABL_OVERLAY_SUBTEXT_ID,
    exports.MABL_HIGHLIGHT_ID,
    exports.MABL_HIGHLIGHT_CAPTION_ID,
    exports.MABL_IFRAME_ID,
    exports.MABL_DRAGGABLE_IFRAME_ID,
    exports.MABL_SECONDARY_IFRAME_ID,
    exports.MABL_DRAGGABLE_DIV_ID,
];
const __mablElementsWithCustomPointerEvents = [];
function compareXPaths(a, b) {
    if (a === b) {
        return 0;
    }
    const elementA = (0, dom_util_1.getElementByXpath)(a);
    const elementB = (0, dom_util_1.getElementByXpath)(b);
    return compareElements(elementA, elementB);
}
function compareElements(a, b) {
    if (!a && !b) {
        return 0;
    }
    if (!a) {
        return -1;
    }
    if (!b) {
        return 1;
    }
    if (a.isSameNode && b.isSameNode && a.isSameNode(b)) {
        return 0;
    }
    if (a.compareDocumentPosition &&
        b.compareDocumentPosition &&
        a.compareDocumentPosition(b) & 2) {
        return 1;
    }
    return -1;
}
function isIgnoredElement(element) {
    return element.classList.contains(exports.MABL_IGNORE_ELEMENT_CLASS);
}
function isSelect(element) {
    return element.tagName.toLowerCase() === 'select';
}
function createIgnoredDomElement(elementName) {
    const ignoredElement = document.createElement(elementName);
    ignoredElement.classList.add(exports.MABL_IGNORE_ELEMENT_CLASS);
    return ignoredElement;
}
function getTagNameFromElement(element) {
    return element.tagName;
}
function getElementValueFromElement(element) {
    return (element
        .value ?? '');
}
function getSelectedIndexFromElement(element) {
    if (!isHTMLSelectElement(element)) {
        return -1;
    }
    return element.selectedIndex;
}
function getSelectedTextFromElement(element) {
    if (!isHTMLSelectElement(element) ||
        !element.selectedOptions ||
        element.selectedOptions.length < 1) {
        return;
    }
    return element.selectedOptions[0].label;
}
function enablePointerEventForDisabledElements(parentDocument) {
    const doc = parentDocument || document;
    const allElements = Array.from(doc.querySelectorAll('*:disabled'));
    for (const element of allElements) {
        if (!isHTMLElement(element)) {
            continue;
        }
        if (window.getComputedStyle(element).pointerEvents === 'none') {
            __mablElementsWithCustomPointerEvents.push({
                element,
                pointerEventsInStyle: element.style.pointerEvents,
            });
            element.style.pointerEvents = 'auto';
        }
        if (hasShadowRoot(element)) {
            enablePointerEventForDisabledElements(element.shadowRoot);
        }
    }
}
function insertOverlayStyles(parentElement) {
    const overlayStyles = createIgnoredDomElement('style');
    const generationOverlayInsetBoxBlurRadius = '20px';
    overlayStyles.textContent = `
  .${exports.MABL_OVERLAY_CLASS}
  {
     position: fixed;
     display: grid;
     justify-items: center;
     align-items: center;
     width: 100%;
     height: 100%;
     line-height: initial;
     top: 0;
     left: 0;
     right: 0;
     bottom: 0;
     background-color: rgba(24,197,207,0.25);
     z-index: 2147483646;
     cursor: pointer;
     padding: 0;
     margin: 0;
  }
  .${exports.MABL_OVERLAY_CLASS}.${exports.MABL_VISUAL_SELECTION_OVERLAY_CLASS}
  {
     cursor: crosshair;
  }
  .${exports.MABL_VISUAL_SELECTION_RECT_CLASS}
  {
     position: absolute;
      border: 2px dashed #007ACC;
      background: rgba(0, 122, 204, 0.1);
      display: none;
      pointer-events: none;
  }
  .${exports.MABL_OVERLAY_CLASS}.mabl-selection-overlay-generation-22b76b1b-4c57-4644-98ab-6f2ff555d1cc
  {
     background-color: unset !important;
     cursor: not-allowed;
     animation: mabl-generation-inset-pulse 2.5s infinite alternate;
     box-shadow: inset 0 0 ${generationOverlayInsetBoxBlurRadius} 0px #fce4f8;
  }
  @keyframes mabl-generation-inset-pulse {
    0% {
      box-shadow: inset 0 0 ${generationOverlayInsetBoxBlurRadius} 0px #fce4f8;
    }
    50% {
      box-shadow: inset 0 0 ${generationOverlayInsetBoxBlurRadius} 20px #fce4f8;
    }
    100% {
      box-shadow: inset 0 0 ${generationOverlayInsetBoxBlurRadius} 0px #fce4f8;
    }
  }
  .${exports.MABL_OVERLAY_CLASS}.walkthrough
  {
     z-index: 299999 !important;
     background-color: unset !important;
  }
  .${MABL_WALKTHROUGH_OVERLAY_CLASS}
  {
    position: fixed;
    width: 100vw;
    height: 100vh;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0,0,0,0.48);
    backdrop-filter: blur(2px);
    z-index: 299999;
    padding: 0;
    margin: 0;
  }
  @keyframes ${exports.MABL_OVERLAY_ATTENTION_CLASS}-shake {
    0% {
      transform: rotate(-2deg);
    }
    12.5% {
       transform: rotate(4deg) ;
    }
    25% {
       transform: rotate(-4deg);
    }
    47.5% {
       transform: rotate(2deg);
    }
    60% {
      transform: rotate(0deg);
    }
  }
  .${exports.MABL_OVERLAY_ATTENTION_CLASS}
  {
    animation: ${exports.MABL_OVERLAY_ATTENTION_CLASS}-shake ${MABL_OVERLAY_ATTENTION_DURATION};
    animation-delay: ${MABL_OVERLAY_ATTENTION_DELAY};
    animation-iteration-count: ${MABL_OVERLAY_ATTENTION_ITERATIONS};
  }
  .${exports.MABL_OVERLAY_TEXT_CLASS}
  {
    height: fit-content;
    width: fit-content;
    font-family: 'Open Sans', sans-serif;
    font-size: 50px;
    font-weight: normal;
    color: white;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 15px;
    padding-left: 15px;
    padding-right: 15px;
    border: 1px white;
    user-select: none;
    text-align: center;
  }
  .${exports.MABL_OVERLAY_SUBTEXT_CLASS}
  {
    height: fit-content;
    width: fit-content;
    font-size: 25px;
    margin-left: auto;
    margin-right: auto;
    display: block;
    user-select: none;
  }
  .${MABL_HIGHLIGHT_BOX_CLASS}
  {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    border-style: solid;
    border-color: black;
    border-width: ${HIGHLIGHT_BOX_BORDER_WIDTH}px;
    border-radius: 0;
    padding: 0;
    margin: 0;
  }
  .${MABL_OVERLAY_CAPTION_CLASS}
  {
    min-width: 100px;
    font-family: 'Open Sans', sans-serif;
    font-size: 13px;
    font-weight: normal;
    color: white;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 0 0 15px 15px;
    padding: 6px;
    margin: 0;
  }
  .${MABL_OVERLAY_LABEL_CLASS}
  {
    width: fit-content;
    font-family: 'Open Sans', sans-serif;
    font-size: 13px;
    font-weight: bold;
    color: white;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 0 0 15px 15px;
    padding: 6px;
    margin: 0;
  }
 `;
    parentElement.appendChild(overlayStyles);
}
function createHighlightBox(styleOverride = {}) {
    const highlightBox = createIgnoredDomElement('mablHighlight');
    highlightBox.classList.add(MABL_HIGHLIGHT_BOX_CLASS);
    highlightBox.id = exports.MABL_HIGHLIGHT_ID;
    Object.keys(styleOverride).forEach((key) => {
        if (styleOverride[key]) {
            highlightBox.style.setProperty(key, styleOverride[key]);
        }
    });
    return highlightBox;
}
function getElementsAtPosition(clientX, clientY, context, processedShadowRoots) {
    const queryContext = context ?? document;
    if (!processedShadowRoots) {
        processedShadowRoots = [];
    }
    const elements = queryContext.elementsFromPoint(clientX, clientY);
    const consideredElements = elements.filter((element) => !isIgnoredElement(element));
    const resultElements = [];
    for (const element of consideredElements) {
        if (hasShadowRoot(element) &&
            !processedShadowRoots.includes(element.shadowRoot)) {
            processedShadowRoots.push(element.shadowRoot);
            const shadowElements = getElementsAtPosition(clientX, clientY, element.shadowRoot, processedShadowRoots);
            resultElements.push(...shadowElements);
        }
        resultElements.push(element);
    }
    return resultElements;
}
function isTargetRootElement(target) {
    const tagName = getTagNameFromElement(target);
    return !!(tagName && tagName.toLowerCase() === 'html');
}
function adjustTargetForButtonInputParent(element, path) {
    const elementTagName = element.tagName.toLowerCase();
    if (elementTagName !== 'button' && elementTagName !== 'input') {
        let adjustIndex;
        path.forEach((pathItem, index) => {
            const tagName = pathItem.tagName ? pathItem.tagName.toLowerCase() : '';
            if (adjustIndex === undefined &&
                (tagName === 'button' || tagName === 'input')) {
                adjustIndex = index;
            }
        });
        if (adjustIndex !== undefined) {
            path = path.slice(adjustIndex);
        }
    }
    return path;
}
function adjustTarget(element, path) {
    let target = element;
    const containsShadowDoms = path.some((element) => element?.shadowRoot);
    if (containsShadowDoms) {
        target = path[0];
    }
    const isActionable = (target) => target !== undefined &&
        target instanceof Element &&
        target.nodeName !== 'SLOT';
    let newPath = path?.slice();
    while (!isActionable(target)) {
        const htmlTarget = target;
        target =
            htmlTarget.parentElement ?? htmlTarget.parentNode?.host;
        newPath?.pop();
    }
    const adjustedPath = adjustTargetForButtonInputParent(element, newPath);
    if (adjustedPath !== newPath) {
        target = adjustedPath[0];
        newPath = adjustedPath;
    }
    if (isTargetRootElement(target)) {
        return {
            path: undefined,
            target: undefined,
        };
    }
    return {
        path: newPath,
        target,
    };
}
async function getSelectionRepeats(selector, shadowRootContext) {
    const targetSelector = (0, mablscriptFind_1.getTargetSelector)(selector);
    const ancestorSelector = (0, mablscriptFind_1.getAncestorSelector)(selector);
    let repeats = [];
    const xpathLocator = function (xpath) {
        if (shadowRootContext) {
            return ((0, mablscriptFind_1.getElementInShadowRootByXpath)(xpath, shadowRootContext) ?? undefined);
        }
        return (0, dom_util_1.getElementByXpath)(xpath) ?? undefined;
    };
    if (targetSelector.repeat_xpaths) {
        const xpaths = [
            ...targetSelector.repeat_xpaths,
            targetSelector.xpath,
        ].filter((x) => !!x);
        xpaths.sort(compareXPaths);
        repeats = xpaths.reduce((result, xpath, index) => {
            const chosen = xpath === targetSelector.xpath;
            const element = xpathLocator(xpath);
            if (element) {
                const repeat = {
                    ancestorSelector,
                    availableAttrProps: (0, dom_util_1.getAttributePropertyMap)(element),
                    chosen,
                    groupSelectorRole: 'target',
                    index,
                    targetSelector: (0, mablscriptFind_1.elementToSelector)(element),
                };
                result.push(repeat);
            }
            return result;
        }, []);
    }
    else if (ancestorSelector?.repeat_xpaths) {
        const xpaths = [
            ...ancestorSelector.repeat_xpaths,
            ancestorSelector.xpath,
        ].filter((x) => !!x);
        repeats = (await Promise.all(xpaths.map(async (xpath) => {
            const ancestor = xpathLocator(xpath);
            const chosen = xpath === ancestorSelector.xpath;
            if (ancestor) {
                const findDescriptor = (0, mablscriptFind_1.toFindOneDescriptor)({
                    ...targetSelector,
                    [mablscriptFind_1.SELECTOR_CONTEXT_NODE_PROPERTY]: ancestor,
                });
                const findStrategy = (0, browser_1.createCoreLocatorsStrategy)(0);
                const findExecutionConfiguration = new browser_1.FindExecutionConfiguration();
                const targetFindResult = await findStrategy.find(findDescriptor, findExecutionConfiguration);
                if (targetFindResult.success) {
                    const element = targetFindResult.foundElement;
                    const repeat = {
                        ancestorSelector: (0, mablscriptFind_1.elementToSelector)(ancestor),
                        availableAttrProps: (0, dom_util_1.getAttributePropertyMap)(element),
                        chosen,
                        groupSelectorRole: 'ancestor',
                        index: -1,
                        targetSelector: (0, mablscriptFind_1.elementToSelector)(element),
                    };
                    return repeat;
                }
            }
            return undefined;
        })))
            .filter((repeat) => repeat !== undefined);
        repeats = repeats
            .filter((repeat, index, array) => array.findIndex((r) => repeat.targetSelector.xpath === r.targetSelector.xpath) === index);
        repeats.sort((repeatA, repeatB) => compareXPaths(repeatA.targetSelector.xpath ?? '', repeatB.targetSelector.xpath ?? ''));
        repeats.forEach((repeat, index) => (repeat.index = index));
    }
    return repeats;
}
function getElementMatchingSelectionTarget(target) {
    if (!target.findDescriptor) {
        return;
    }
    if (target.shadowParents?.length) {
        return getElementInShadowParents(target);
    }
    const targetSelector = (0, mablscriptFind_1.getFoundTargetSelector)(target.findDescriptor);
    if (targetSelector?.xpath) {
        const result = (0, dom_util_1.getElementByXpath)(targetSelector.xpath);
        return result ?? undefined;
    }
    return undefined;
}
function getElementInShadowParents(target) {
    const shadowParents = target.shadowParents;
    if (!shadowParents?.length) {
        return;
    }
    let root = shadowParents[0]?.shadowRoot ?? document;
    shadowParents.forEach((shadowParent) => {
        const childRoots = (0, mablscriptFind_1.getChildrenShadowRoots)(root);
        const foundRoot = childRoots.find((childRoot) => {
            const closestElPath = (0, mablscriptFind_1.getPathForElement)(childRoot);
            const closestXpath = (0, mablscriptFind_1.createXpathFromPathArrayForShadowDom)(closestElPath);
            return closestXpath === shadowParent.xpath;
        });
        if (foundRoot) {
            root = foundRoot;
        }
        return undefined;
    });
    const targetSelector = (0, mablscriptFind_1.getFoundTargetSelector)(target.findDescriptor);
    if (root && targetSelector?.xpath) {
        const result = (0, mablscriptFind_1.getElementInShadowRootByXpath)(targetSelector.xpath, root?.shadowRoot);
        return result ?? undefined;
    }
    return undefined;
}
function pixels(value) {
    return `${Math.round(value)}px`;
}
function isThisAnIframe() {
    return window.location !== window.parent.location;
}
function getInputTypeFromElement(element) {
    if (!isInputField(element)) {
        return;
    }
    return element.type || 'text';
}
function isHTMLElement(element) {
    return element instanceof HTMLElement;
}
function isHTMLInputElement(element) {
    return element instanceof HTMLInputElement;
}
function isHTMLSelectElement(element) {
    return element instanceof HTMLSelectElement;
}
function hasShadowRoot(element) {
    return element instanceof HTMLElement && !!element.shadowRoot;
}
function isInputField(element) {
    const tagName = getTagNameFromElement(element).toLowerCase();
    return tagName === 'input' || tagName === 'textarea';
}
function querySelectorAll(selector) {
    if (window.mablShadowDOMQuerySelectorAll) {
        return window.mablShadowDOMQuerySelectorAll(selector);
    }
    return document.querySelectorAll(selector);
}
function getAllElementsBySelectors(selectors) {
    try {
        if (selectors.css_query) {
            return [...querySelectorAll(selectors.value || selectors.css_query)];
        }
        else if (selectors.xpath) {
            const nodes = (0, dom_util_1.getAllElementsByXpath)(selectors.value || selectors.xpath);
            return nodes.filter((node) => node !== undefined);
        }
    }
    catch (e) {
        return;
    }
    return [];
}
function positionHighlightBox(highlightBox, boundingRect) {
    highlightBox.style.left = pixels(boundingRect.x - HIGHLIGHT_BOX_BORDER_WIDTH);
    highlightBox.style.top = pixels(boundingRect.y - HIGHLIGHT_BOX_BORDER_WIDTH);
    highlightBox.style.width = pixels(boundingRect.width + HIGHLIGHT_BOX_BORDER_WIDTH);
    highlightBox.style.height = pixels(boundingRect.height + HIGHLIGHT_BOX_BORDER_WIDTH);
}
function captionHighlightBox(highlightBox, boundingRect, captions, cssClass) {
    if (captions.length) {
        const highlightCaption = createIgnoredDomElement('div');
        highlightCaption.id = exports.MABL_HIGHLIGHT_CAPTION_ID;
        highlightCaption.classList.add(cssClass);
        highlightCaption.style.marginTop = pixels(boundingRect.height);
        highlightCaption.style.marginLeft = pixels(-HIGHLIGHT_BOX_BORDER_WIDTH);
        highlightCaption.style.width = `${boundingRect.width + HIGHLIGHT_BOX_BORDER_WIDTH}px`;
        captions.forEach((caption) => highlightCaption.appendChild(caption));
        highlightBox.appendChild(highlightCaption);
    }
}
function captionHighlightBoxWithAttrProps(highlightBox, boundingRect, attrProps) {
    const captions = [];
    if (attrProps.tagName) {
        const div = createIgnoredDomElement('div');
        div.textContent = `<${attrProps.tagName.toLowerCase()}>`;
        captions.push(div);
    }
    ['id', 'name', 'className', 'role', 'for', 'type', 'value', 'href']
        .filter((key) => attrProps[key] !== undefined && attrProps[key] !== '')
        .forEach((key) => {
        const div = createIgnoredDomElement('div');
        const strong = createIgnoredDomElement('strong');
        strong.textContent = `${key}: `;
        const text = document.createTextNode(`${attrProps[key]}`);
        div.appendChild(strong);
        div.appendChild(text);
        captions.push(div);
    });
    captionHighlightBox(highlightBox, boundingRect, captions, MABL_OVERLAY_CAPTION_CLASS);
}
function captionHighlightBoxWithOrdinalPosition(highlightBox, boundingRect, elementIndex) {
    if (elementIndex >= 0) {
        const caption = createIgnoredDomElement('div');
        const text = document.createTextNode(`${elementIndex + 1}`);
        caption.appendChild(text);
        captionHighlightBox(highlightBox, boundingRect, [caption], MABL_OVERLAY_LABEL_CLASS);
    }
}
function getElementToHighlightFromPoints(clientX, clientY, context, overlappingElementsIndex) {
    const queryContext = context ?? document;
    const consideredElements = getElementsAtPosition(clientX, clientY, queryContext);
    let indexIntoConsideredElements = overlappingElementsIndex
        ? overlappingElementsIndex % consideredElements.length
        : 0;
    if (overlappingElementsIndex && overlappingElementsIndex < 0) {
        indexIntoConsideredElements += consideredElements.length;
    }
    const elementToHighlight = consideredElements[indexIntoConsideredElements];
    return elementToHighlight;
}
function positionSelectionHighlight(clientPosition, isInWalkthrough = false, relativeElementIndex = 0) {
    const highlightBox = document.getElementById(exports.MABL_HIGHLIGHT_ID);
    if (!highlightBox) {
        return;
    }
    highlightBox.replaceChildren();
    const highlightedElement = getElementToHighlightFromPoints(clientPosition.clientX, clientPosition.clientY, undefined, relativeElementIndex);
    if (!highlightedElement) {
        return;
    }
    if (isInWalkthrough) {
        const isWalkthroughTarget = !!highlightedElement?.attributes?.[walkthrough_1.WALKTHROUGH_TARGET_ATTRIBUTE];
        if (!isWalkthroughTarget) {
            highlightBox.style.display = 'none';
            return;
        }
        highlightBox.style.display = '';
    }
    const boundingRect = highlightedElement.getBoundingClientRect();
    const attrProps = (0, dom_util_1.getAttributePropertyMap)(highlightedElement);
    positionHighlightBox(highlightBox, boundingRect);
    captionHighlightBoxWithAttrProps(highlightBox, boundingRect, attrProps);
    return highlightedElement;
}
function highlightElement(element, elementIndex, parentNode, styleOverride = {}, showPosition = false) {
    const boundingRect = element.getBoundingClientRect();
    const highlightBox = createHighlightBox(styleOverride);
    highlightBox.id = `${exports.MABL_HIGHLIGHT_ID}-${elementIndex}`;
    positionHighlightBox(highlightBox, boundingRect);
    if (showPosition) {
        captionHighlightBoxWithOrdinalPosition(highlightBox, boundingRect, elementIndex);
    }
    parentNode.appendChild(highlightBox);
}
function highlightSimilarElements(elementHighlights, labelIndividually) {
    const parentNodeId = `${exports.MABL_HIGHLIGHT_ID}-parent`;
    let parentNode = document.getElementById(parentNodeId);
    if (parentNode) {
        destroyElement(parentNode);
    }
    parentNode = createIgnoredDomElement('mablOverlay');
    parentNode.id = parentNodeId;
    let elementCount = 0;
    elementHighlights.forEach((elementHighlight) => {
        const { index, role, xpath } = elementHighlight;
        const element = elementHighlight.element || (xpath && (0, dom_util_1.getElementByXpath)(xpath));
        if (element && !isIgnoredElement(element)) {
            elementCount += 1;
            highlightElement(element, index, parentNode, role === 'other' ? { borderStyle: 'dashed' } : undefined, labelIndividually);
        }
    });
    const overlay = document.getElementById(exports.MABL_OVERLAY_ID);
    if (!labelIndividually) {
        const queryCountText = createIgnoredDomElement('mablCountText');
        queryCountText.innerText = `${elementCount} element${elementCount > 1 ? 's' : ''} found`;
        queryCountText.classList.add(exports.MABL_OVERLAY_TEXT_CLASS);
        parentNode.appendChild(queryCountText);
    }
    if (overlay) {
        overlay.appendChild(parentNode);
    }
}
function removeOverlayById(id) {
    const overlay = document.getElementById(id);
    if (overlay) {
        try {
            document.body.removeChild(overlay);
        }
        catch {
            document.documentElement.removeChild(overlay);
        }
    }
}
function restorePointerEvents() {
    for (const item of __mablElementsWithCustomPointerEvents) {
        try {
            if (item.element.style.pointerEvents === 'auto') {
                item.element.style.pointerEvents =
                    item.pointerEventsInStyle;
            }
        }
        catch (e) {
        }
    }
}
function destroySelectionOverlay() {
    restorePointerEvents();
    removeOverlayById(exports.MABL_OVERLAY_ID);
}
function renderWalkthroughOverlay() {
    const overlay = createIgnoredDomElement('div');
    insertOverlayStyles(overlay);
    overlay.id = exports.MABL_WALKTHROUGH_OVERLAY_ID;
    overlay.classList.add(MABL_WALKTHROUGH_OVERLAY_CLASS);
    try {
        document.body.appendChild(overlay);
    }
    catch {
        document.documentElement.appendChild(overlay);
    }
}
function destroyWalkthroughOverlay() {
    removeOverlayById(exports.MABL_WALKTHROUGH_OVERLAY_ID);
}
function destroyElement(element) {
    element.parentNode.removeChild(element);
}
function isFileInput(element) {
    if (element === undefined || element === null) {
        return false;
    }
    if (!isHTMLInputElement(element)) {
        return false;
    }
    return element.type?.toLowerCase() === 'file';
}
function renderSelectionOverlay({ innerTextDisplayed, requestAttention = false, isInWalkthrough = false, subtext, overlayClassname, addHighlightBox = true, overlayId = exports.MABL_OVERLAY_ID, }) {
    const overlay = createIgnoredDomElement('div');
    overlay.id = overlayId;
    overlay.classList.add(exports.MABL_OVERLAY_CLASS);
    if (overlayClassname) {
        overlay.classList.add(overlayClassname);
    }
    if (isInWalkthrough) {
        overlay.classList.add('walkthrough');
    }
    insertOverlayStyles(overlay);
    if (innerTextDisplayed && !isInWalkthrough) {
        const overlayText = createIgnoredDomElement('mablOverlayText');
        overlayText.id = exports.MABL_OVERLAY_TEXT_ID;
        overlayText.classList.add(exports.MABL_OVERLAY_TEXT_CLASS);
        if (requestAttention) {
            overlayText.classList.add(exports.MABL_OVERLAY_ATTENTION_CLASS);
        }
        overlayText.innerText = innerTextDisplayed;
        if (subtext) {
            const overlaySubtext = overlayText.appendChild(createIgnoredDomElement('mablOverlaySubtext'));
            overlaySubtext.id = exports.MABL_OVERLAY_SUBTEXT_ID;
            overlaySubtext.classList.add(exports.MABL_OVERLAY_SUBTEXT_CLASS);
            overlaySubtext.innerText = subtext;
        }
        overlay.appendChild(overlayText);
    }
    if (addHighlightBox) {
        const highlightBox = createHighlightBox();
        overlay.appendChild(highlightBox);
        enablePointerEventForDisabledElements();
    }
    try {
        document.body.appendChild(overlay);
    }
    catch {
        document.documentElement.appendChild(overlay);
    }
}
function getIframesInfo() {
    const iframeInfo = [];
    Array.from(document.getElementsByTagName('iframe')).forEach((iframeElement) => {
        if (!exports.MABL_INSERTED_ELEMENTS.includes(iframeElement.id)) {
            const xPath = (0, dom_util_1.createXPathFromElement)(iframeElement);
            const message = (0, dom_util_1.createBaseEventMessage)(iframeElement, 'record', 'switch-context-to', xPath);
            message.absoluteSrc = iframeElement.src;
            iframeInfo.push(message);
        }
    });
    return iframeInfo;
}
