function centerImageAndGetHeight(containerElement) {
    const imageElement = containerElement.querySelector('img');

    return new Promise((resolve, reject) => {
        if (!imageElement) {
            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
                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`;

            // Resolve with the measured height for the parent component
            resolve(imageElement.clientHeight);

            removeListeners();
        };

        const errorHandler = () => 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);
        }
    });
}