import { jsx as _jsx } from "react/jsx-runtime";
// (C) 2022-2026 GoodData Corporation
import { createContext, useContext, useLayoutEffect, useState } from "react";
import { v4 as uuid } from "uuid";
/**
 * @internal
 */
export const OverlayContext = createContext(undefined);
OverlayContext.displayName = "OverlayContext";
/**
 * Component for injecting {@link OverlayController} into all components in the application.
 *
 * @internal
 */
export function OverlayControllerProvider({ children, overlayController }) {
    return _jsx(OverlayContext.Provider, { value: overlayController, children: children });
}
/**
 * Hook to get current instance of the {@link OverlayController}
 *
 * @returns an instance of the {@link OverlayController}
 *
 * @internal
 */
export const useOverlayController = () => {
    return useContext(OverlayContext);
};
const FALLBACK_OVERLAY_Z_INDEX = 5001; // Same as in OverlayController
/**
 * Hook to get the css `z-index` property for given overlay.
 *
 * @param uuid - uuid of the overlay.
 *
 * @returns - `z-index` for given overlay.
 *
 * @internal
 */
export const useOverlayZIndex = (uuid) => {
    const overlayController = useContext(OverlayContext);
    return overlayController?.getZIndex(uuid) ?? FALLBACK_OVERLAY_Z_INDEX;
};
/**
 * Registers a new overlay and returns its z-index
 *
 * @returns the overlay's z-index
 *
 * @internal
 */
export function useOverlayZIndexWithRegister() {
    const [overlayId] = useState(uuid());
    const overlayController = useOverlayController();
    // Register on commit (before paint), then update local state so the
    // overlay re-renders with its registered z-index. Without this second
    // render, an overlay opened above an already-mounted one would render
    // with the controller's fallback z-index on first paint and slip below
    // the lower overlay (the controller does not trigger re-renders by
    // itself).
    const [zIndex, setZIndex] = useState(undefined);
    useLayoutEffect(() => {
        if (!overlayController) {
            setZIndex(FALLBACK_OVERLAY_Z_INDEX);
            return undefined;
        }
        overlayController.addOverlay(overlayId);
        setZIndex(overlayController.getZIndex(overlayId));
        return () => overlayController.removeOverlay(overlayId);
    }, [overlayController, overlayId]);
    return zIndex ?? FALLBACK_OVERLAY_Z_INDEX;
}
