jQuery(document).ready(function () {
    jQuery('.iafwzcai-help-icon-wrapper').hover(function () {
        const tooltip = jQuery(this).find('.iafwzcai-help-tooltip');
        const wrapper = jQuery(this);

        // Get dimensions of the wrapper and tooltip
        const wrapperRect = wrapper.get(0).getBoundingClientRect();
        const tooltipWidth = tooltip.outerWidth();
        const tooltipHeight = tooltip.outerHeight();

        // Calculate default positions
        let tooltipTop = wrapperRect.top + wrapperRect.height + 10; // Below the icon with a gap of 10px
        let tooltipLeft = wrapperRect.left + (wrapperRect.width / 2) - (tooltipWidth / 2); // Center horizontally

        // Ensure tooltip does not go out of the viewport (adjust for overflow)
        if (tooltipLeft + tooltipWidth > window.innerWidth) {
            tooltipLeft = window.innerWidth - tooltipWidth - 10; // Adjust to fit on the right side
        }
        if (tooltipLeft < 0) {
            tooltipLeft = 10; // Adjust to fit on the left side
        }

        // If the tooltip is below the viewport, position it above
        if (tooltipTop + tooltipHeight > window.innerHeight) {
            tooltipTop = wrapperRect.top - tooltipHeight - 10; // Above the wrapper
        }

        // Apply calculated positions and ensure visibility
        tooltip.css({
            position: 'fixed', // Ensure it appears above overlay
            top: `${tooltipTop}px`,
            left: `${tooltipLeft}px`,
            zIndex: 10000, // Higher than overlay and popup
            visibility: 'visible',
            opacity: 1,
        });
    }, function () {
        // Hide the tooltip when hover ends
        jQuery(this).find('.iafwzcai-help-tooltip').css({
            visibility: 'hidden',
            opacity: 0,
        });
    });
});
