/**
 * VMPFence Status Modal JavaScript
 * 
 * Handles dynamic status modal display and calculations
 * 
 * @since 2.1.0
 * @since 2.1.2
 * @package VMPFence
 * @subpackage StatusModal
 */

(function($) {
    'use strict';

    /**
     * VMPFence Status Modal Handler
     */
    window.VMPFenceStatusModal = {
        
        /**
         * Cache for status data to avoid repeated AJAX calls
         */
        cache: {},
        
        /**
         * Timeout for hiding modal
         */
        hideTimeout: null,
        
        /**
         * Show modal for a specific status type
         */
        show: function(statusType, element) {
            var self = this;
            
            // Check cache first
            if (this.cache[statusType]) {
                this.render(this.cache[statusType], element);
                return;
            }
            
            // Fetch data from server via AJAX
            jQuery.ajax({
                url: vmpfenceStatusData.ajaxurl,
                type: 'POST',
                data: {
                    action: 'vmpfence_get_status',
                    nonce: vmpfenceStatusData.nonce,
                    status_type: statusType
                },
                success: function(response) {
                    if (response.success && response.data) {
                        // Cache the data
                        self.cache[statusType] = response.data;
                        // Render modal
                        self.render(response.data, element);
                    }
                },
                error: function(xhr, status, error) {
                    // Silent error handling
                }
            });
        },
        
        /**
         * Render modal with data
         */
        render: function(data, element) {
            var $modal = $('#vmpfence-status-modal');
            var percentage = Math.round(data.percentage * 100);
            
            // Update title
            $('#vmpfence-modal-title').text(data.title);
            
            // Update percentage circle
            this.updateCircle(percentage);
            $('#vmpfence-modal-percentage').text(percentage + '%');
            
            // Update help link
            $('#vmpfence-modal-help-link').attr('href', data.helpLink);
            
            // Show/hide completion message
            if (data.missing.length === 0) {
                $('#vmpfence-modal-complete').show();
                $('#vmpfence-modal-incomplete').hide();
            } else {
                $('#vmpfence-modal-complete').hide();
                $('#vmpfence-modal-incomplete').show();
                
                // Populate missing items list
                var $list = $('#vmpfence-modal-list');
                $list.empty();
                
                $.each(data.missing, function(i, item) {
                    var itemPercentage = Math.round(item.percentage * 100);
                    $list.append(
                        $('<li>').append(
                            $('<strong>').text(itemPercentage + '%'),
                            $('<span>').text(item.title)
                        )
                    );
                });
            }
            
            // Position modal near element
            this.position($modal, element);
            
            // Show modal
            $modal.fadeIn(1);
        },
        
        /**
         * Update circle progress
         */
        updateCircle: function(percentage) {
            var circumference = 2 * Math.PI * 45; // radius = 45
            var offset = circumference - (percentage / 100) * circumference;
            
            var $progress = $('#vmpfence-modal-progress');
            $progress.css('stroke-dashoffset', offset);
            
            // Update color based on percentage (matching dashboard logic)
            var color;
            if (percentage >= 80) {
                color = '#28a745'; // Green for excellent
            } else if (percentage >= 60) {
                color = '#17a2b8'; // Blue for good
            } else if (percentage >= 40) {
                color = '#ffc107'; // Yellow for fair
            } else {
                color = '#dc3545'; // Red for poor
            }
            
            // Apply color directly to stroke
            $progress.css('stroke', color);
        },
        
        /**
         * Position modal near element
         */
        position: function($modal, $element) {
            var offset = $element.offset();
            var elementHeight = $element.outerHeight();
            var elementWidth = $element.outerWidth();
            var modalWidth = $modal.outerWidth();
            var modalHeight = $modal.outerHeight();
            
            // Position modal above the element
            var top = offset.top - modalHeight - 10;
            var left = offset.left + (elementWidth / 2) - (modalWidth / 2);
            
            // Adjust if modal goes off-screen
            var windowWidth = $(window).width();
            var windowHeight = $(window).height();
            var scrollTop = $(window).scrollTop();
            
            // Remove all arrow classes first
            $modal.removeClass('arrow-up arrow-left arrow-right arrow-down');
            
            var arrowDirection = 'arrow-down'; // Default: modal above, arrow points down
            
            // Check horizontal overflow
            if (left < 10) {
                left = 10;
                // If modal is pushed to the left edge, check if we should position it to the right of element
                if (offset.left + elementWidth + modalWidth + 10 < windowWidth) {
                    left = offset.left + elementWidth + 10;
                    top = offset.top + (elementHeight / 2) - (modalHeight / 2);
                    arrowDirection = 'arrow-left'; // Modal on right, arrow points left
                }
            }
            
            if (left + modalWidth > windowWidth - 10) {
                left = windowWidth - modalWidth - 10;
                // If modal is pushed to the right edge, check if we should position it to the left of element
                if (offset.left - modalWidth - 10 > 0) {
                    left = offset.left - modalWidth - 10;
                    top = offset.top + (elementHeight / 2) - (modalHeight / 2);
                    arrowDirection = 'arrow-right'; // Modal on left, arrow points right
                }
            }
            
            // Check vertical overflow - if doesn't fit above, show below
            if (top < scrollTop + 10) {
                top = offset.top + elementHeight + 10;
                arrowDirection = 'arrow-up'; // Modal below, arrow points up
            }
            
            // Add the appropriate arrow class
            $modal.addClass(arrowDirection);
            
            $modal.css({
                top: top + 'px',
                left: left + 'px'
            });
        },
        
        /**
         * Hide modal
         */
        hide: function() {
            var self = this;
            // Clear any existing timeout
            if (self.hideTimeout) {
                clearTimeout(self.hideTimeout);
            }
            // Add small delay to allow mouse to move to modal
            self.hideTimeout = setTimeout(function() {
                $('#vmpfence-status-modal').fadeOut(1);
            }, 100);
        },
        
        /**
         * Cancel hide timeout
         */
        cancelHide: function() {
            if (this.hideTimeout) {
                clearTimeout(this.hideTimeout);
                this.hideTimeout = null;
            }
        }
    };
    
    /**
     * Initialize hover events on status circles
     */
    $(document).ready(function() {
        // Add hover events to elements with data-status-type attribute
        $(document).on('mouseenter', '[data-status-type]', function() {
            var statusType = $(this).data('status-type');
            VMPFenceStatusModal.cancelHide();
            VMPFenceStatusModal.show(statusType, $(this));
        });
        
        $(document).on('mouseleave', '[data-status-type]', function() {
            VMPFenceStatusModal.hide();
        });
        
        // Keep modal visible when hovering over the modal itself
        $(document).on('mouseenter', '#vmpfence-status-modal', function() {
            VMPFenceStatusModal.cancelHide();
        });
        
        $(document).on('mouseleave', '#vmpfence-status-modal', function() {
            VMPFenceStatusModal.hide();
        });
    });
    
})(jQuery);
