/**
 * Opti-Behavior Smart Tooltip Positioning
 *
 * Automatically repositions tooltips to prevent viewport overflow
 * Ensures tooltips are always fully visible to users
 * Dynamically positions arrow to point at tooltip icon
 *
 * @package OptiBehavior
 * @version 1.1.0
 */

(function() {
    'use strict';

    /**
     * Initialize smart tooltip positioning
     */
    function initSmartTooltips() {
        // Get all tooltip triggers
        const tooltips = document.querySelectorAll('.ob-tooltip');

        tooltips.forEach(function(tooltip) {
            // Add mouseenter listener
            tooltip.addEventListener('mouseenter', function() {
                positionTooltip(this);
                // Add class to parent card to raise z-index (fallback for browsers without :has())
                const parentCard = this.closest('.storage-stat-card, .stat-card');
                if (parentCard) {
                    parentCard.classList.add('tooltip-active');
                }
            });

            // Add mouseleave listener to remove the class
            tooltip.addEventListener('mouseleave', function() {
                const parentCard = this.closest('.storage-stat-card, .stat-card');
                if (parentCard) {
                    parentCard.classList.remove('tooltip-active');
                }
            });

            // Also handle focus for accessibility
            tooltip.addEventListener('focusin', function() {
                positionTooltip(this);
                const parentCard = this.closest('.storage-stat-card, .stat-card');
                if (parentCard) {
                    parentCard.classList.add('tooltip-active');
                }
            });

            // Handle focus out
            tooltip.addEventListener('focusout', function() {
                const parentCard = this.closest('.storage-stat-card, .stat-card');
                if (parentCard) {
                    parentCard.classList.remove('tooltip-active');
                }
            });
        });
    }

    /**
     * Position a tooltip to prevent viewport overflow
     * @param {HTMLElement} tooltipTrigger - The tooltip container element
     */
    function positionTooltip(tooltipTrigger) {
        const content = tooltipTrigger.querySelector('.ob-tooltip-content');
        const icon = tooltipTrigger.querySelector('.ob-tooltip-icon');
        if (!content) return;

        // Reset any previous positioning classes and inline styles
        tooltipTrigger.classList.remove('ob-tooltip-align-left', 'ob-tooltip-align-right');
        content.style.left = '';
        content.style.right = '';
        content.style.setProperty('--arrow-left', '');
        content.style.setProperty('--arrow-right', '');

        // Wait for display to be applied, then calculate
        requestAnimationFrame(function() {
            const triggerRect = tooltipTrigger.getBoundingClientRect();
            const contentRect = content.getBoundingClientRect();
            const viewportWidth = window.innerWidth;
            const viewportHeight = window.innerHeight;
            const padding = 20; // Minimum padding from viewport edge

            // Get icon position for arrow placement
            let iconCenterX = triggerRect.left + triggerRect.width / 2;
            if (icon) {
                const iconRect = icon.getBoundingClientRect();
                iconCenterX = iconRect.left + iconRect.width / 2;
            }

            // Check horizontal overflow
            const tooltipRight = triggerRect.left + contentRect.width;

            // Determine tooltip alignment
            let tooltipLeftEdge;
            let tooltipRightEdge;

            // If tooltip would overflow right edge
            if (tooltipRight > viewportWidth - padding) {
                // Try aligning to right side of trigger
                if (triggerRect.right - contentRect.width > padding) {
                    // Align right edge of tooltip with right edge of trigger
                    tooltipTrigger.classList.add('ob-tooltip-align-right');
                    content.style.left = 'auto';
                    content.style.right = '0';
                    tooltipLeftEdge = triggerRect.right - contentRect.width;
                    tooltipRightEdge = triggerRect.right;
                } else {
                    // Position tooltip from right edge of viewport
                    content.style.left = 'auto';
                    content.style.right = (viewportWidth - triggerRect.right + padding) + 'px';
                    tooltipRightEdge = triggerRect.right - padding;
                    tooltipLeftEdge = tooltipRightEdge - contentRect.width;
                }
            } else {
                // Default left alignment
                tooltipTrigger.classList.add('ob-tooltip-align-left');
                content.style.left = '0';
                content.style.right = 'auto';
                tooltipLeftEdge = triggerRect.left;
                tooltipRightEdge = triggerRect.left + contentRect.width;
            }

            // Calculate arrow position relative to tooltip content
            // Arrow should point to the center of the icon
            let arrowPosition = iconCenterX - tooltipLeftEdge;

            // Clamp arrow position to stay within tooltip bounds (with padding)
            const arrowPadding = 15; // Minimum distance from edge
            arrowPosition = Math.max(arrowPadding, Math.min(arrowPosition, contentRect.width - arrowPadding));

            // Set arrow position via CSS custom property
            content.style.setProperty('--arrow-position', arrowPosition + 'px');

            // Check vertical overflow and determine best position
            const isLeftOrRight = tooltipTrigger.classList.contains('ob-tooltip-left') ||
                                  tooltipTrigger.classList.contains('ob-tooltip-right');

            if (!isLeftOrRight) {
                const spaceAbove = triggerRect.top - padding;
                const spaceBelow = viewportHeight - triggerRect.bottom - padding;
                const tooltipHeight = contentRect.height + 12; // +12 for gap

                const isCurrentlyBottom = tooltipTrigger.classList.contains('ob-tooltip-bottom');

                if (isCurrentlyBottom) {
                    // Currently bottom — switch to top only if it doesn't fit below but fits above
                    if (spaceBelow < tooltipHeight && spaceAbove >= tooltipHeight) {
                        tooltipTrigger.classList.remove('ob-tooltip-bottom');
                    }
                } else {
                    // Currently top — switch to bottom only if it doesn't fit above but fits below
                    if (spaceAbove < tooltipHeight && spaceBelow >= tooltipHeight) {
                        tooltipTrigger.classList.add('ob-tooltip-bottom');
                    }
                }
            }
        });
    }

    /**
     * Reinitialize tooltips (useful after AJAX content loads)
     */
    window.reinitSmartTooltips = function() {
        initSmartTooltips();
    };

    // Initialize on DOM ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initSmartTooltips);
    } else {
        initSmartTooltips();
    }

    // Also reinitialize after a short delay to catch any late-loaded content
    setTimeout(initSmartTooltips, 1000);
    setTimeout(initSmartTooltips, 3000);

})();
