"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CellPopup = void 0;
const tslib_1 = require("tslib");
const React = tslib_1.__importStar(require("react"));
const InfiniteTable_1 = require("../../../components/InfiniteTable");
const utils_1 = require("../../../components/OverlayTrigger/utils");
const AdaptableContext_1 = require("../../AdaptableContext");
const UIHelper_1 = require("../../UIHelper");
let portalElement;
const ensurePortalElement = (className) => {
    if (!(0, UIHelper_1.isBrowserDocumentAvailable)()) {
        return;
    }
    if (portalElement) {
        return;
    }
    portalElement = document.createElement('div');
    portalElement.style.position = 'absolute';
    portalElement.style.zIndex = '4'; // under the context menu
    portalElement.style.top = '0px';
    portalElement.style.left = '0px';
    if (className) {
        portalElement.className = className;
    }
    document.body.appendChild(portalElement);
};
exports.CellPopup = React.forwardRef((props, ref) => {
    ensurePortalElement(props.className);
    const adaptable = (0, AdaptableContext_1.useAdaptable)();
    const { showOverlay, clearAll: clearAllOverlays, hideOverlay, portal, } = (0, InfiniteTable_1.useOverlay)({
        portalContainer: portalElement,
    });
    const OVERLAY_ID = 'cell-overlay';
    const showCellPopupContent = () => {
        const cellSelector = `[row-id="${props.primaryKeyValue}"] [col-id="${props.columnId}"]`;
        const alignTo = document.querySelector(cellSelector);
        if (!alignTo) {
            adaptable.logger.consoleError(`Cell not found for selector "${cellSelector}". Unable to display popup.`);
            return;
        }
        const showOverlayOptions = {
            id: OVERLAY_ID,
            alignPosition: [
                // overlay - target
                ['TopLeft', 'TopRight'],
                ['TopRight', 'TopLeft'],
                ['TopCenter', 'BottomCenter'],
                ['BottomCenter', 'TopCenter'],
            ],
            constrainTo: adaptable.getAgGridContainerElement() ?? true,
            alignTo: (0, utils_1.getRect)(alignTo),
        };
        showOverlay(() => props.children, showOverlayOptions);
    };
    React.useEffect(() => {
        if (props.isOpen) {
            showCellPopupContent();
        }
        else {
            clearAllOverlays();
            hideOverlay(OVERLAY_ID);
        }
    }, [props.isOpen]);
    React.useImperativeHandle(ref, () => {
        return {
            refreshContent: () => showCellPopupContent(),
        };
    });
    return React.createElement(React.Fragment, null, portal);
});
