(function ($) {
    'use strict';

    /**
     * 3-D Secure badge tooltip positioning.
     *
     * The tooltip is `position: fixed` in CSS so it escapes any ancestor
     * with `overflow: hidden` (WooCommerce order-edit metaboxes clip
     * absolutely-positioned descendants regardless of z-index). On hover or
     * focus we read the badge's viewport rectangle and apply matching
     * top/left to the tooltip. Above the badge by default; flips below when
     * there isn't room above.
     */
    $(function () {
        var MARGIN = 8;

        function positionTooltip($badge) {
            var $tip = $badge.find('.wcp-3ds-tooltip');
            if (!$tip.length) {
                return;
            }
            var badge = $badge[0].getBoundingClientRect();
            // Briefly render the tooltip to measure it without flicker — the
            // CSS keeps it off-screen until we set real coordinates.
            $tip.css({ visibility: 'hidden', display: 'block' });
            var tip = $tip[0].getBoundingClientRect();
            $tip.css({ visibility: '', display: '' });

            var top = badge.top - tip.height - MARGIN;
            if (top < MARGIN) {
                // Not enough room above; flip below the badge.
                top = badge.bottom + MARGIN;
            }
            var left = badge.left + (badge.width / 2) - (tip.width / 2);
            // Clamp to viewport horizontally.
            if (left < MARGIN) {
                left = MARGIN;
            }
            var maxLeft = window.innerWidth - tip.width - MARGIN;
            if (left > maxLeft) {
                left = maxLeft;
            }

            $tip.css({ top: top + 'px', left: left + 'px' });
        }

        $(document).on('mouseenter focusin', '.wcp-3ds-badge', function () {
            positionTooltip($(this));
        });

        // Reposition any visible tooltip on scroll/resize. Fixed positioning
        // doesn't track the anchor automatically; on a scrolling order list
        // an open tooltip would otherwise drift away from its badge.
        var rafToken = null;
        function rescheduleReposition() {
            if (rafToken !== null) {
                return;
            }
            rafToken = window.requestAnimationFrame(function () {
                rafToken = null;
                $('.wcp-3ds-badge').each(function () {
                    var $badge = $(this);
                    // Only reposition badges currently showing their tooltip.
                    if ($badge.is(':hover') || $badge.find(':focus').length || $badge.is(':focus')) {
                        positionTooltip($badge);
                    }
                });
            });
        }
        $(window).on('scroll resize', rescheduleReposition);
        $(document).on('scroll', '*', rescheduleReposition);
    });
})(jQuery);
