function centerImageAndGetHeight(containerElement) {
    console.log("centerImageAndGetHeight called", containerElement);
    const imageElement = containerElement.querySelector('img');

    return new Promise((resolve, reject) => {
        if (!imageElement) {
            console.error("Image element not found.");
            return reject("Image element not found.");
        }

        const successHandler = () => {
            // Find the carousel's main element
            const carouselViewport = imageElement.closest('.mud-carousel');
            if (!carouselViewport) {
                // Failsafe if not in a carousel, just return height
                console.log("Not in carousel, height:", imageElement.clientHeight);
                resolve(imageElement.clientHeight);
                return;
            }

            // Get the displayed widths
            const parentWidth = carouselViewport.clientWidth;
            const imageWidth = imageElement.clientWidth;

            // Calculate the padding needed to center the image
            const paddingLeft = Math.max(0, (parentWidth - imageWidth) / 2);

            // Apply the padding directly to the image
            imageElement.style.paddingLeft = `${paddingLeft}px`;

            // Calculate height based on aspect ratio to avoid getting stuck in a tall container
            const ratio = imageElement.naturalHeight / imageElement.naturalWidth;
            const calculatedHeight = imageWidth * ratio;

            console.log("Image measurement:", { 
                naturalWidth: imageElement.naturalWidth, 
                naturalHeight: imageElement.naturalHeight,
                imageWidth: imageWidth,
                calculatedHeight: calculatedHeight
            });

            resolve(calculatedHeight);

            removeListeners();
        };

        const errorHandler = () => {
            console.error("Could not load image.");
            reject("Could not load image.");
        };
        const removeListeners = () => {
            imageElement.removeEventListener("load", successHandler);
            imageElement.removeEventListener("error", errorHandler);
        };

        // If the image is already loaded (from cache), trigger the handler manually
        if (imageElement.complete && imageElement.naturalHeight > 0) {
            successHandler();
        } else {
            imageElement.addEventListener("load", successHandler);
            imageElement.addEventListener("error", errorHandler);
        }
    });
}

function getElementHeight(element) {
    console.log("getElementHeight called", element);
    if (!element) {
        console.warn("getElementHeight: element is null");
        return 0;
    }
    const height = element.clientHeight;
    console.log("getElementHeight returns", height);
    return height;
}