// Positions .cfx-tooltip children using fixed coordinates so they escape
// overflow:auto scroll containers.  No Blazor interop required – this is
// a purely DOM-level enhancement driven by mouseenter / mouseleave on
// .cfx-tooltip-wrap elements.

(function () {
    const GAP = 6;          // px between the trigger element and the tooltip
    const EDGE_MARGIN = 8;  // min distance from viewport edges

    function show(wrap) {
        const tip = wrap.querySelector('.cfx-tooltip');
        if (!tip) return;

        const rect = wrap.getBoundingClientRect();

        // Place below the trigger by default
        let top = rect.bottom + GAP;
        let left = rect.left;

        // Measure the tooltip (make it visible but transparent for measuring)
        tip.style.left = '0px';
        tip.style.top = '0px';
        tip.classList.add('cfx-tooltip-visible');
        const tipRect = tip.getBoundingClientRect();
        tip.classList.remove('cfx-tooltip-visible');

        // If it would overflow the bottom, flip above
        if (top + tipRect.height > window.innerHeight - EDGE_MARGIN) {
            top = rect.top - tipRect.height - GAP;
        }

        // Clamp horizontal position
        if (left + tipRect.width > window.innerWidth - EDGE_MARGIN) {
            left = window.innerWidth - tipRect.width - EDGE_MARGIN;
        }
        if (left < EDGE_MARGIN) {
            left = EDGE_MARGIN;
        }

        tip.style.left = left + 'px';
        tip.style.top = top + 'px';
        tip.classList.add('cfx-tooltip-visible');
    }

    function hide(wrap) {
        const tip = wrap.querySelector('.cfx-tooltip');
        if (!tip) return;
        tip.classList.remove('cfx-tooltip-visible');
    }

    // Use event delegation on document so dynamically-rendered Blazor
    // content is automatically covered.
    document.addEventListener('mouseenter', function (e) {
        const wrap = e.target.closest('.cfx-tooltip-wrap');
        if (wrap) show(wrap);
    }, true);

    document.addEventListener('mouseleave', function (e) {
        const wrap = e.target.closest('.cfx-tooltip-wrap');
        if (wrap) hide(wrap);
    }, true);
})();
