"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Popover = void 0;
const react_1 = require("@floating-ui/react");
const react_2 = __importStar(require("react"));
const Modal_context_1 = require("../modal/Modal.context");
const utils_external_1 = require("../utils-external");
const DismissableLayer_1 = require("../utils/components/dismissablelayer/DismissableLayer");
const helpers_1 = require("../utils/helpers");
const hooks_1 = require("../utils/hooks");
const PopoverContent_1 = __importDefault(require("./PopoverContent"));
/**
 * A component that displays a popover.
 *
 * @see [📝 Documentation](https://aksel.nav.no/komponenter/core/popover)
 * @see 🏷️ {@link PopoverProps}
 *
 * @example
 * ```jsx
 * <Button ref={buttonRef} onClick={() => setOpenState(true)}>
 *   Åpne popover
 * </Button>
 * <Popover
 *   open={openState}
 *   onClose={() => setOpenState(false)}
 *   anchorEl={buttonRef.current}
 * >
 *   <Popover.Content>Innhold her!</Popover.Content>
 * </Popover>
 * ```
 */
exports.Popover = (0, react_2.forwardRef)((_a, ref) => {
    var { className, children, anchorEl, open, onClose, placement = "top", offset, strategy: userStrategy, flip: _flip = true } = _a, restProps = __rest(_a, ["className", "children", "anchorEl", "open", "onClose", "placement", "offset", "strategy", "flip"]);
    const isInModal = (0, Modal_context_1.useModalContext)(false) !== undefined;
    const chosenStrategy = userStrategy !== null && userStrategy !== void 0 ? userStrategy : (isInModal ? "fixed" : "absolute");
    const { update, refs, placement: flPlacement, floatingStyles, } = (0, react_1.useFloating)({
        strategy: chosenStrategy,
        placement,
        open,
        middleware: [
            (0, react_1.offset)(offset !== null && offset !== void 0 ? offset : 8),
            _flip &&
                (0, react_1.flip)({
                    padding: 5,
                    fallbackPlacements: getOppositePlacement(placement),
                }),
            (0, react_1.shift)({ padding: 12 }),
        ],
    });
    (0, utils_external_1.useClientLayoutEffect)(() => {
        refs.setReference(anchorEl);
    }, [anchorEl, refs]);
    const floatingRef = (0, hooks_1.useMergeRefs)(refs.setFloating, ref);
    (0, utils_external_1.useClientLayoutEffect)(() => {
        if (!refs.reference.current || !refs.floating.current || !open)
            return;
        const cleanup = (0, react_1.autoUpdate)(refs.reference.current, refs.floating.current, update);
        return () => cleanup();
    }, [refs.floating, refs.reference, update, open, anchorEl]);
    return (react_2.default.createElement(DismissableLayer_1.DismissableLayer, { asChild: true, safeZone: {
            anchor: anchorEl,
        }, onDismiss: () => open && (onClose === null || onClose === void 0 ? void 0 : onClose()), enabled: open },
        react_2.default.createElement("div", Object.assign({ ref: floatingRef }, (0, utils_external_1.omit)(restProps, ["arrow"]), { className: (0, helpers_1.cl)("aksel-popover", className, {
                "aksel-popover--hidden": !open || !anchorEl,
            }), style: Object.assign(Object.assign({}, restProps.style), floatingStyles), "data-placement": flPlacement, "aria-hidden": !open || !anchorEl }), children)));
});
const oppositeSideMap = {
    top: "bottom",
    bottom: "top",
    left: "right",
    right: "left",
};
/**
 * If placement is side+alignment, we want to preserve the alignment
 * when flipping to the opposite side.
 */
function getOppositePlacement(placement) {
    /**
     * In most cases, the fallback for left/right should be top/bottom
     * as there is usually more space vertically than horizontally.
     */
    if (placement.startsWith("left") || placement.startsWith("right")) {
        return ["bottom", "top"];
    }
    const [side, alignment] = placement.split("-");
    const oppositeSide = oppositeSideMap[side];
    return [alignment ? `${oppositeSide}-${alignment}` : oppositeSide];
}
exports.Popover.Content = PopoverContent_1.default;
exports.default = exports.Popover;
//# sourceMappingURL=Popover.js.map