/**
 * SiteStaffr Tooltip System
 *
 * Provides tooltip functionality for all admin pages.
 * Handles hover, click, and keyboard interactions for accessibility.
 * Uses event delegation to support dynamically created triggers.
 *
 * @package    SiteStaffr
 * @subpackage SiteStaffr/admin/js
 * @since      0.5.7
 */

(function($) {
    'use strict';

    // Track active tooltip per trigger (keyed by DOM element)
    var activeTooltips = new WeakMap();

    function getTooltipState($trigger) {
        var el = $trigger[0];
        if (!activeTooltips.has(el)) {
            activeTooltips.set(el, { $tooltip: null, hideTimeout: null });
        }
        return activeTooltips.get(el);
    }

    function createTooltip(state, text) {
        if (state.$tooltip) return;
        state.$tooltip = $('<div class="sitestaffr-tooltip"></div>');
        state.$tooltip.text(text);
        $('body').append(state.$tooltip);
    }

    function showTooltip($trigger) {
        var tooltipText = $trigger.attr('data-tooltip');
        if (!tooltipText) return;

        var state = getTooltipState($trigger);
        if (!state.$tooltip) createTooltip(state, tooltipText);

        clearTimeout(state.hideTimeout);

        // Position tooltip
        var triggerOffset = $trigger.offset();
        var triggerWidth = $trigger.outerWidth();
        var triggerHeight = $trigger.outerHeight();
        var tooltipWidth = state.$tooltip.outerWidth();
        var tooltipHeight = state.$tooltip.outerHeight();
        var scrollTop = $(window).scrollTop();

        // Prefer top placement; only fall back below when top has insufficient space.
        var spaceAbove = triggerOffset.top - scrollTop;
        var positionAbove = spaceAbove > tooltipHeight + 12;

        var top, left;

        if (positionAbove) {
            top = triggerOffset.top - tooltipHeight - 10;
            state.$tooltip.addClass('position-top').removeClass('position-bottom');
        } else {
            top = triggerOffset.top + triggerHeight + 10;
            state.$tooltip.addClass('position-bottom').removeClass('position-top');
        }

        // Center horizontally relative to trigger
        left = triggerOffset.left + (triggerWidth / 2) - (tooltipWidth / 2);

        // Keep within viewport
        var windowWidth = $(window).width();
        if (left < 10) left = 10;
        if (left + tooltipWidth > windowWidth - 10) {
            left = windowWidth - tooltipWidth - 10;
        }

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

        // Show with animation
        setTimeout(function() {
            if (state.$tooltip) state.$tooltip.addClass('show');
        }, 10);
    }

    function hideTooltip($trigger) {
        var state = getTooltipState($trigger);
        if (!state.$tooltip) return;

        state.hideTimeout = setTimeout(function() {
            if (!state.$tooltip) return;
            state.$tooltip.removeClass('show');
            var $tip = state.$tooltip;
            setTimeout(function() {
                $tip.remove();
                state.$tooltip = null;
            }, 150);
        }, 100);
    }

    $(document).ready(function() {
        // Delegated hover events
        $(document).on('mouseenter', '.sitestaffr-tooltip-trigger', function() {
            showTooltip($(this));
        });

        $(document).on('mouseleave', '.sitestaffr-tooltip-trigger', function() {
            hideTooltip($(this));
        });

        // Delegated click/keyboard events
        $(document).on('click keypress', '.sitestaffr-tooltip-trigger', function(e) {
            if (e.type === 'keypress' && e.which !== 13 && e.which !== 32) return;
            e.preventDefault();

            var $trigger = $(this);
            var state = getTooltipState($trigger);

            if (state.$tooltip && state.$tooltip.hasClass('show')) {
                hideTooltip($trigger);
            } else {
                showTooltip($trigger);
            }
        });

        // Close tooltips on outside click (mobile)
        $(document).on('click touchstart', function(e) {
            if (!$(e.target).closest('.sitestaffr-tooltip-trigger').length) {
                $('.sitestaffr-tooltip.show').each(function() {
                    $(this).removeClass('show');
                    var $tip = $(this);
                    setTimeout(function() {
                        $tip.remove();
                    }, 150);
                });
            }
        });
    });

})(jQuery);
