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;
};
import { autoUpdate, offset as flOffset, flip, shift, useFloating, } from "@floating-ui/react";
import React, { forwardRef } from "react";
import { useModalContext } from "../modal/Modal.context.js";
import { omit, useClientLayoutEffect } from "../utils-external/index.js";
import { DismissableLayer } from "../utils/components/dismissablelayer/DismissableLayer.js";
import { cl } from "../utils/helpers/index.js";
import { useMergeRefs } from "../utils/hooks/index.js";
import PopoverContent from "./PopoverContent.js";
/**
 * 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>
 * ```
 */
export const Popover = 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 = useModalContext(false) !== undefined;
    const chosenStrategy = userStrategy !== null && userStrategy !== void 0 ? userStrategy : (isInModal ? "fixed" : "absolute");
    const { update, refs, placement: flPlacement, floatingStyles, } = useFloating({
        strategy: chosenStrategy,
        placement,
        open,
        middleware: [
            flOffset(offset !== null && offset !== void 0 ? offset : 8),
            _flip &&
                flip({
                    padding: 5,
                    fallbackPlacements: getOppositePlacement(placement),
                }),
            shift({ padding: 12 }),
        ],
    });
    useClientLayoutEffect(() => {
        refs.setReference(anchorEl);
    }, [anchorEl, refs]);
    const floatingRef = useMergeRefs(refs.setFloating, ref);
    useClientLayoutEffect(() => {
        if (!refs.reference.current || !refs.floating.current || !open)
            return;
        const cleanup = autoUpdate(refs.reference.current, refs.floating.current, update);
        return () => cleanup();
    }, [refs.floating, refs.reference, update, open, anchorEl]);
    return (React.createElement(DismissableLayer, { asChild: true, safeZone: {
            anchor: anchorEl,
        }, onDismiss: () => open && (onClose === null || onClose === void 0 ? void 0 : onClose()), enabled: open },
        React.createElement("div", Object.assign({ ref: floatingRef }, omit(restProps, ["arrow"]), { className: 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];
}
Popover.Content = PopoverContent;
export default Popover;
//# sourceMappingURL=Popover.js.map