import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2020-2025 GoodData Corporation
import { Component, createRef, version, } from "react";
import cx from "classnames";
import { bindAll, debounce, isEqual, pick } from "lodash-es";
import isReactEqual from "react-fast-compare";
import { Portal } from "react-portal";
import { v4 as uuid } from "uuid";
import { OverlayContext } from "./OverlayContext.js";
import { ENUM_KEY_CODE } from "../typings/utilities.js";
import { elementRegion, isFixedPosition } from "../utils/domUtilities.js";
import { DEFAULT_ALIGN_POINTS, getOptimalAlignment, getOverlayStyles } from "../utils/overlay.js";
const events = [
    {
        name: "click",
        handler: "closeOnOutsideClick",
        target: typeof document === "undefined" ? null : document,
    },
    {
        name: "mousedown",
        handler: "onDocumentMouseDown",
        target: typeof document === "undefined" ? null : document,
        requiredProp: "closeOnOutsideClick",
    },
    { name: "goodstrap.scrolled", handler: "closeOnParentScroll" },
    { name: "goodstrap.drag", handler: "closeOnMouseDrag" },
    { name: "keydown", handler: "closeOnEscape" },
];
const eventProps = events.map((event) => event.handler);
const ALIGN_TIMEOUT_MS = 10;
const INIT_STATE_ALIGN = -500;
export const POSITION_SAME_AS_TARGET = "sameAsTarget";
const OVERLAY_CONTENT_CLASS = "gd-overlay-content";
function exceedsThreshold(firstNumber, secondNumber) {
    return ((firstNumber === undefined && secondNumber !== undefined) ||
        (firstNumber !== undefined && secondNumber === undefined) ||
        Math.abs(firstNumber - secondNumber) > 2);
}
function alignExceedsThreshold(firstAlignment, secondAlignment) {
    return (exceedsThreshold(firstAlignment.top, secondAlignment.top) ||
        exceedsThreshold(firstAlignment.left, secondAlignment.left) ||
        exceedsThreshold(firstAlignment.right, secondAlignment.right) ||
        exceedsThreshold(firstAlignment.width, secondAlignment.width) ||
        exceedsThreshold(firstAlignment.height, secondAlignment.height));
}
const stopPropagation = (e) => {
    e.stopPropagation();
    const reactMajorVersion = parseInt(version?.split(".")[0], 10);
    // Propagate events to `document` for react 17
    // (We need to get them for other overlays to close and the events did not get there due to changes
    // introduced in https://reactjs.org/blog/2020/08/10/react-v17-rc.html#changes-to-event-delegation)
    if (reactMajorVersion >= 17) {
        const evt = new MouseEvent(e.nativeEvent.type, e.nativeEvent);
        Object.defineProperty(evt, "target", { value: e.nativeEvent.target, enumerable: true });
        document.dispatchEvent(evt);
    }
};
/**
 * @internal
 */
export class Overlay extends Component {
    static defaultProps = {
        alignPoints: DEFAULT_ALIGN_POINTS,
        alignTo: "body",
        children: false,
        className: "",
        containerClassName: "",
        positionType: "absolute",
        resizeObserverThreshold: 1,
        ignoreClicksOn: [],
        ignoreClicksOnByClass: [],
        ensureVisibility: false,
        shouldCloseOnClick: () => true,
        onClick: stopPropagation,
        onMouseOver: stopPropagation,
        onMouseUp: stopPropagation,
        onAlign: () => { },
        onClose: () => { },
    };
    id;
    overlayRef = createRef();
    containerRef = createRef();
    resizeHandler = debounce(() => {
        this.isInitialAlign = true;
        this.align();
    }, 100);
    portalNode = null;
    isComponentMounted;
    clickedInside;
    alignmentTimeoutId;
    isInitialAlign;
    static contextType = OverlayContext;
    observer;
    constructor(props) {
        super(props);
        this.state = {
            alignment: {
                align: props.alignPoints[0].align,
                left: INIT_STATE_ALIGN,
                top: INIT_STATE_ALIGN,
                right: 0,
                width: 0,
                height: 0,
            },
            initialVisiblePart: 0,
            observedHeight: 0,
        };
        this.observer = this.createResizeObserver();
        this.isComponentMounted = false;
        this.clickedInside = false;
        this.alignmentTimeoutId = 0;
        this.isInitialAlign = true;
        this.id = props.id ?? uuid();
        bindAll(this, events.map((event) => event.handler));
        this.createPortalNode();
    }
    UNSAFE_componentWillMount() {
        // reserve the zIndex via the context as soon as possible so that Overlays in the children get higher zIndex
        this.context?.addOverlay(this.id);
    }
    componentDidMount() {
        this.isComponentMounted = true;
        afterOverlayOpened();
        window.addEventListener("resize", this.resizeHandler);
        this.observer?.observe(this.overlayRef.current);
        this.addListeners(this.props);
        this.alignWithTimeout();
    }
    UNSAFE_componentWillReceiveProps(nextProps) {
        if (!isEqual(pick(this.props, eventProps), pick(nextProps, eventProps))) {
            this.removeListeners(this.props);
            this.addListeners(nextProps);
        }
    }
    shouldComponentUpdate(nextProps, nextState) {
        const propsChanged = !isReactEqual(this.props, nextProps);
        const positionChanged = !isEqual(this.state.alignment, nextState.alignment);
        return propsChanged || positionChanged;
    }
    componentDidUpdate() {
        this.alignWithTimeout();
    }
    componentWillUnmount() {
        this.isComponentMounted = false;
        this.clearAlignmentTimeout();
        window.removeEventListener("resize", this.resizeHandler);
        this.observer?.disconnect();
        this.removeListeners(this.props);
        this.removePortalNodeAfterAllTreeUnmount();
        this.context?.removeOverlay(this.id);
        afterOverlayClosed();
    }
    render() {
        // Need stop propagation of events from Portal thats new behavior of react 16
        // https://github.com/facebook/react/issues/11387
        return (_jsx("span", { "data-testid": "portal-scroll-anchor", className: "s-portal-scroll-anchor", ref: this.containerRef, children: _jsx(Portal, { node: this.portalNode, children: _jsxs("div", { id: this.id, className: cx(this.props.containerClassName, OVERLAY_CONTENT_CLASS), onClick: this.props.onClick, onMouseOver: this.props.onMouseOver, onMouseUp: this.props.onMouseUp, children: [this.renderMask(), _jsx("div", { ref: this.overlayRef, style: this.getOverlayStyles(), className: this.getOverlayClasses(), children: this.props.children })] }) }) }));
    }
    align = () => {
        const { alignPoints, alignTo, positionType } = this.props;
        const overlay = this.overlayRef.current;
        if (!alignPoints || !overlay) {
            return;
        }
        const isSameAsTarget = this.isSameAsTargetPosition(positionType);
        const optimalAlign = getOptimalAlignment({
            targetRegion: elementRegion(alignTo, isSameAsTarget),
            selfRegion: elementRegion(overlay),
            alignPoints,
            ignoreScrollOffsets: isSameAsTarget,
        });
        // process also if visiblePart is 1 to get dimensions of the overlay
        const shouldApplyConstraints = this.props.ensureVisibility && optimalAlign.visiblePart > 0;
        const constrainedAlignment = shouldApplyConstraints
            ? this.calculateConstrainedAlignment(optimalAlign.alignment, overlay, positionType === "fixed")
            : optimalAlign.alignment;
        if (alignExceedsThreshold(this.state.alignment, constrainedAlignment)) {
            this.setState({
                alignment: constrainedAlignment,
                initialVisiblePart: this.isInitialAlign
                    ? optimalAlign.visiblePart
                    : this.state.initialVisiblePart,
            }, () => {
                this.isInitialAlign = false;
                this.props.onAlign(constrainedAlignment);
            });
        }
        else {
            this.props.onAlign(optimalAlign.alignment);
        }
    };
    calculateConstrainedAlignment = (alignment, overlay, ignoreScrollOffsets) => {
        const overlayRegion = elementRegion(overlay);
        const { width: originalWidth, height: originalHeight } = overlayRegion;
        const viewportWidth = window.visualViewport?.width || window.innerWidth;
        const viewportHeight = window.visualViewport?.height || window.innerHeight;
        const scrollTop = ignoreScrollOffsets
            ? 0
            : window.visualViewport?.pageTop || window.scrollY || document.documentElement.scrollTop;
        const scrollLeft = ignoreScrollOffsets
            ? 0
            : window.visualViewport?.pageLeft || window.scrollX || document.documentElement.scrollLeft;
        // Calculate the minimum allowed dimensions (50% of original)
        const minWidth = originalWidth * 0.5;
        const minHeight = originalHeight * 0.5;
        const constrainedAlignment = { ...alignment };
        if (constrainedAlignment.left < 0 + scrollLeft) {
            constrainedAlignment.left = 0 + scrollLeft;
        }
        if (constrainedAlignment.top < 0 + scrollTop) {
            constrainedAlignment.top = 0 + scrollTop;
        }
        // Step 2: Calculate if the overlay extends beyond viewport
        const rightEdge = constrainedAlignment.left + originalWidth;
        const bottomEdge = constrainedAlignment.top + originalHeight;
        const exceedsRight = rightEdge > scrollLeft + viewportWidth;
        const exceedsBottom = bottomEdge > scrollTop + viewportHeight;
        if (exceedsRight) {
            const availableWidth = scrollLeft + viewportWidth - constrainedAlignment.left;
            const newWidth = Math.max(availableWidth, minWidth);
            constrainedAlignment.width = newWidth;
            constrainedAlignment.right = undefined;
        }
        else {
            constrainedAlignment.width = originalWidth;
        }
        if (exceedsBottom) {
            const availableHeight = scrollTop + viewportHeight - constrainedAlignment.top;
            const newHeight = Math.max(availableHeight, minHeight);
            constrainedAlignment.height = newHeight;
        }
        else {
            constrainedAlignment.height = originalHeight;
        }
        return constrainedAlignment;
    };
    clearAlignmentTimeout = () => {
        if (this.alignmentTimeoutId) {
            window.clearTimeout(this.alignmentTimeoutId);
        }
    };
    alignWithTimeout = () => {
        this.clearAlignmentTimeout();
        this.alignmentTimeoutId = window.setTimeout(() => {
            this.align();
        }, ALIGN_TIMEOUT_MS);
    };
    onMaskClick = (e) => {
        if (!this.props.closeOnOutsideClick) {
            e.stopPropagation();
        }
    };
    getZIndex() {
        return this.context ? this.context.getZIndex(this.id) : this.props.zIndex;
    }
    getOverlayStyles = () => {
        const { alignTo, positionType } = this.props;
        const { alignment } = this.state;
        const position = this.isSameAsTargetPosition(positionType)
            ? isFixedPosition(alignTo)
                ? "fixed"
                : "absolute"
            : positionType;
        // Base styles always applied
        return {
            position,
            left: alignment.left,
            top: alignment.top,
            zIndex: this.getZIndex(),
            visibility: this.isAligned() ? undefined : "hidden",
            ...(this.props.ensureVisibility &&
                alignment.width && {
                width: alignment.width,
            }),
            ...(this.props.ensureVisibility &&
                alignment.height && {
                height: alignment.height,
            }),
            width: this.props.width,
            maxWidth: this.props.maxWidth,
        };
    };
    getOverlayClasses = () => {
        return cx(this.props.className, this.getAlignClasses(), this.getVisibilityClass(), {
            "overlay-wrapper": true,
        });
    };
    /**
     * Add CSS classes to overlay wrapper, so they can be used
     * for position of arrows and stuff
     */
    getAlignClasses = () => {
        if (!this.isAligned()) {
            return "";
        }
        const align = this.state.alignment.align.split(" ");
        return `target-${align[0]} self-${align[1]}`;
    };
    getVisibilityClass = () => {
        if (!this.isAligned()) {
            return "";
        }
        return this.props.ensureVisibility && this.state.initialVisiblePart < 1 ? "truncated" : "";
    };
    createPortalNode() {
        this.portalNode = document.createElement("div");
        document.body.appendChild(this.portalNode);
    }
    removePortalNodeAfterAllTreeUnmount() {
        setTimeout(() => {
            if (this.portalNode && document.body.contains(this.portalNode)) {
                document.body.removeChild(this.portalNode);
            }
            this.portalNode = null;
        });
    }
    isSameAsTargetPosition = (positionType) => {
        return positionType === POSITION_SAME_AS_TARGET;
    };
    isEventOnParent = (event) => {
        const node = this.containerRef.current;
        const eventNode = event.detail?.node || event.target;
        return eventNode.contains(node);
    };
    shouldCloseOnClick = (e) => {
        if (!this.isComponentMounted) {
            return false;
        }
        if (!this.isAligned()) {
            return false;
        }
        // an ignored node has been clicked, always keep the overlay open
        if (this.hasClickedOnIgnoredNode(e)) {
            return false;
        }
        // non-ignored node clicked, give shouldCloseOnClick the chance
        // to override closing the dialog
        return this.props.shouldCloseOnClick(e);
    };
    hasClickedOnIgnoredNode = (e) => {
        if (e.defaultPrevented) {
            // Ignore event if it should be prevented (e.q. by click in child component)
            return true;
        }
        const clickedElement = e.target;
        if (this.isElementInChildOverlay(clickedElement) || this.clickedInside) {
            return true;
        }
        const ignoredRefElements = [this.overlayRef.current, ...this.props.ignoreClicksOn];
        const clickInsideIgnoredRefElement = ignoredRefElements.some((ref) => {
            return ref?.contains(clickedElement);
        });
        if (clickInsideIgnoredRefElement) {
            return true;
        }
        return this.props.ignoreClicksOnByClass.some((selector) => clickedElement.closest(selector));
    };
    isAligned = () => {
        return this.state.alignment.left !== INIT_STATE_ALIGN && this.state.alignment.top != INIT_STATE_ALIGN;
    };
    // makes assumption that overlays later in the DOM are child overlays
    isElementInChildOverlay = (element) => {
        const overlays = Array.from(document.querySelectorAll(".overlay-wrapper"));
        const thisOverlayIndex = overlays.findIndex((overlay) => overlay === this.overlayRef.current);
        return overlays.slice(thisOverlayIndex + 1).some((overlay) => overlay.contains(element));
    };
    onDocumentMouseDown(e) {
        this.clickedInside = this.overlayRef.current.contains(e.target);
        if (this.clickedInside) {
            e.stopPropagation();
        }
    }
    closeOnParentScroll(e) {
        if (!this.isComponentMounted) {
            return;
        }
        if (this.isEventOnParent(e)) {
            this.props.onClose();
        }
    }
    closeOnMouseDrag = () => {
        if (!this.isComponentMounted) {
            return;
        }
        this.props.onClose();
    };
    closeOnOutsideClick(e) {
        if (this.shouldCloseOnClick(e)) {
            this.props.onClose();
        }
    }
    closeOnEscape(e) {
        if (this.isComponentMounted &&
            this.props.closeOnEscape &&
            e.keyCode === ENUM_KEY_CODE.KEY_CODE_ESCAPE) {
            this.props.onClose();
        }
    }
    updateListeners = (method, props) => {
        events.forEach((event) => {
            if (props[event.handler] || props[event.requiredProp]) {
                const handler = this[event.handler];
                if (handler) {
                    (event.target || window)[`${method}EventListener`](event.name, handler);
                }
            }
        });
    };
    addListeners = (props) => {
        this.updateListeners("add", props);
    };
    removeListeners = (props) => {
        this.updateListeners("remove", props);
    };
    renderMask = () => {
        const styles = {
            zIndex: this.context ? this.context.getZIndex(this.id) : null,
        };
        return this.props.isModal ? (_jsx("div", { className: "modalityPlugin-mask modalityPlugin-mask-visible", onClick: this.onMaskClick, style: styles })) : (false);
    };
    createResizeObserver() {
        // With 100% or more threshold, don't use ResizeObserver
        if (this.props.resizeObserverThreshold >= 1) {
            return undefined;
        }
        return new ResizeObserver((entries) => {
            const newHeightCandidate = entries[0].contentRect.height;
            const heightDiffersByThreshold = Math.abs(this.state.observedHeight - newHeightCandidate) / this.state.observedHeight >
                this.props.resizeObserverThreshold;
            if (heightDiffersByThreshold) {
                this.resizeHandler();
                this.setState({ observedHeight: newHeightCandidate });
            }
        });
    }
}
const overlayState = {
    opened: 0,
    body: {},
    html: {},
};
function afterOverlayOpened() {
    if (overlayState.opened === 0) {
        const styles = getOverlayStyles();
        overlayState.html = applyStyles(document.documentElement, styles.html);
        overlayState.body = applyStyles(document.body, styles.body);
    }
    overlayState.opened++;
}
function afterOverlayClosed() {
    overlayState.opened--;
    if (overlayState.opened === 0) {
        applyStyles(document.documentElement, overlayState.html);
        applyStyles(document.body, overlayState.body);
    }
}
function applyStyles(el, newStyles) {
    return Object.keys(newStyles).reduce((prev, key) => {
        const style = el.style;
        const oldValue = style[key];
        style[key] = newStyles[key];
        return { ...prev, [key]: oldValue };
    }, {});
}
//# sourceMappingURL=Overlay.js.map