/**
 * AI Review Column JavaScript
 *
 * Handles tooltip functionality and interactions for the AI Review column
 *
 * @since 4.2.5
 */
(function($) {
    'use strict';

    // REST API endpoints
    var restUrl = wpufAIReview.rest_url + 'wpuf/v1/ai-review';
    var restNonce = wpufAIReview.rest_nonce;

    /**
     * Initialize AI Review column functionality
     */
    function initAIReviewColumn() {
        // Only run on post list screens (any post type)
        if (!$('body').hasClass('edit-php')) {
            return;
        }

        initTooltips();
        initAccessibility();
        initRetryHandler();
    }

    /**
     * Initialize tooltip functionality
     */
    function initTooltips() {
        // Wrap AI circles with tooltip containers
        $('.wpuf-ai-circle').each(function() {
            var $circle = $(this);
            var tooltipText = $circle.attr('title') || $circle.data('tooltip');

            if (!tooltipText) {
                return;
            }

            // Remove title attribute to prevent default tooltip
            $circle.removeAttr('title');

            // Wrap with tooltip container
            $circle.wrap('<div class="wpuf-ai-tooltip"></div>');

            // Add tooltip text
            $circle.after('<div class="wpuf-ai-tooltip-text">' + escapeHtml(tooltipText) + '</div>');
        });

        // Reposition tooltips on hover to prevent viewport overflow
        $(document).on('mouseenter focus', '.wpuf-ai-tooltip', function() {
            var $tooltip = $(this).find('.wpuf-ai-tooltip-text');
            var tooltipEl = $tooltip[0];

            // Reset to default centered position
            $tooltip.css({ left: '50%', right: 'auto', transform: 'translateX(-50%)' });
            tooltipEl.style.setProperty('--wpuf-arrow-left', '50%');

            var tooltipRect = tooltipEl.getBoundingClientRect();
            var viewportWidth = window.innerWidth;

            if (tooltipRect.right > viewportWidth) {
                // Overflows right edge — shift tooltip left
                var overflowRight = tooltipRect.right - viewportWidth + 16;
                $tooltip.css({ transform: 'translateX(calc(-50% - ' + overflowRight + 'px))' });

                // Move the arrow to stay aligned with the circle
                var arrowLeft = ((tooltipRect.width / 2) + overflowRight) / tooltipRect.width * 100;
                tooltipEl.style.setProperty('--wpuf-arrow-left', arrowLeft + '%');
            } else if (tooltipRect.left < 0) {
                // Overflows left edge — shift tooltip right
                var overflowLeft = Math.abs(tooltipRect.left) + 16;
                $tooltip.css({ transform: 'translateX(calc(-50% + ' + overflowLeft + 'px))' });

                // Move the arrow to stay aligned with the circle
                var arrowLeftPos = ((tooltipRect.width / 2) - overflowLeft) / tooltipRect.width * 100;
                tooltipEl.style.setProperty('--wpuf-arrow-left', arrowLeftPos + '%');
            }
        });

    }

    /**
     * Initialize accessibility features
     */
    function initAccessibility() {
        // Add ARIA labels for screen readers
        $('.wpuf-ai-circle').each(function() {
            var $circle = $(this);
            var tooltipText = $circle.data('tooltip');

            if (tooltipText) {
                $circle.attr('aria-label', tooltipText);
                $circle.attr('role', 'button');
                $circle.attr('tabindex', '0');
            }
        });

        // Handle keyboard navigation
        $('.wpuf-ai-circle').on('keydown', function(e) {
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                $(this).trigger('mouseenter');
            }
        });

        // Handle focus events for keyboard users
        $('.wpuf-ai-circle').on('focus', function() {
            $(this).trigger('mouseenter');
        }).on('blur', function() {
            $(this).trigger('mouseleave');
        });
    }

    /**
     * Initialize retry handler for clickable icons
     */
    function initRetryHandler() {
        // Handle retry on icon click
        $(document).on('click', '.wpuf-ai-circle.clickable', function(e) {
            e.preventDefault();
            e.stopPropagation();

            var $icon = $(this);
            var postId = $icon.data('post-id');
            var status = $icon.data('status');
            var summary = $icon.data('summary');

            // Build confirmation message
            var statusLabels = {
                'full': wpufAIReview.i18n.full || 'Full Match',
                'medium': wpufAIReview.i18n.medium || 'Medium Match',
                'none': wpufAIReview.i18n.none || 'No Match',
                'failed': wpufAIReview.i18n.failed || 'Failed',
                'pending': wpufAIReview.i18n.pending || 'Pending',
                'in_progress': wpufAIReview.i18n.inProgress || 'In Progress'
            };

            var statusLabel = statusLabels[status] || status;
            var confirmMessage = (wpufAIReview.i18n.confirmRetry || 'Retry AI review for this post?')
                + '\n\n'
                + (wpufAIReview.i18n.currentStatus || 'Current status')
                + ': ' + statusLabel;

            if (summary) {
                confirmMessage += '\n' + (wpufAIReview.i18n.summary || 'Summary') + ': ' + summary;
            }

            // Confirmation dialog
            if (!confirm(confirmMessage)) {
                return;
            }

            // Show loading state
            $icon.addClass('wpuf-ai-loading');

            $.ajax({
                url: restUrl + '/retry',
                type: 'POST',
                data: {
                    post_id: postId
                },
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', restNonce);
                },
                success: function(response) {
                    if (response.success) {
                        // Update icon to show pending
                        $icon
                            .removeClass()
                            .addClass('wpuf-ai-circle wpuf-ai-circle-blue clickable')
                            .data('status', 'pending')
                            .html('○')
                            .attr('aria-label', wpufAIReview.i18n.pending || 'Review Pending');

                        // Start polling for status updates
                        pollReviewStatus(postId, $icon);
                    } else {
                        var errorMsg = (wpufAIReview.i18n.retryFailed || 'Retry failed') + ': ' + (response.data && response.data.message ? response.data.message : JSON.stringify(response));
                        alert(errorMsg);
                    }
                },
                error: function(xhr) {
                    // Try to parse the error message from the response
                    var errorMsg = (wpufAIReview.i18n.requestFailed || 'Request failed. Please try again.');
                    if (xhr.responseText) {
                        try {
                            var response = JSON.parse(xhr.responseText);
                            if (response.message) {
                                errorMsg = response.message;
                            } else if (response.data && response.data.message) {
                                errorMsg = response.data.message;
                            }
                        } catch (e) {
                            // If parsing fails, use the default message
                        }
                    }

                    alert(errorMsg);
                },
                complete: function() {
                    $icon.removeClass('wpuf-ai-loading');
                }
            });
        });
    }

    /**
     * Poll for review status updates
     */
    function pollReviewStatus(postId, $icon) {
        var pollCount = 0;
        var maxPolls = 30; // Poll for up to 5 minutes (30 * 10 seconds)
        var pollInterval = 10000; // 10 seconds

        var pollTimer = setInterval(function() {
            pollCount++;

            if (pollCount > maxPolls) {
                clearInterval(pollTimer);
                return;
            }

            $.ajax({
                url: restUrl + '/status',
                type: 'GET',
                data: {
                    post_id: postId
                },
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', restNonce);
                },
                success: function(response) {
                    // REST API returns data at root level, not nested under 'data'
                    var newStatus = response.status || (response.data && response.data.status);
                    var summary = response.summary || (response.data && response.data.summary) || '';

                    if (response.success && newStatus) {
                        // Stop polling if review is complete
                        if (['full', 'medium', 'none', 'failed'].indexOf(newStatus) !== -1) {
                            clearInterval(pollTimer);
                            updateReviewIcon($icon, newStatus, summary);
                        }
                    }
                },
                error: function() {
                    // Silently continue polling on error
                }
            });
        }, pollInterval);
    }

    /**
     * Update review icon based on new status
     */
    function updateReviewIcon($icon, status, summary) {
        var statusConfig = {
            'full': {
                class: 'wpuf-ai-circle-green',
                icon: '●',
                label: wpufAIReview.i18n.full || 'Full Match'
            },
            'medium': {
                class: 'wpuf-ai-circle-yellow',
                icon: '●',
                label: wpufAIReview.i18n.medium || 'Medium Match'
            },
            'none': {
                class: 'wpuf-ai-circle-red',
                icon: '●',
                label: wpufAIReview.i18n.none || 'No Match'
            },
            'failed': {
                class: 'wpuf-ai-circle-gray',
                icon: '●',
                label: wpufAIReview.i18n.failed || 'Failed'
            }
        };

        var config = statusConfig[status];
        if (!config) {
            return;
        }

        var ariaLabel = config.label;
        if (summary) {
            ariaLabel += ': ' + summary;
        }

        $icon
            .removeClass()
            .addClass('wpuf-ai-circle ' + config.class + ' clickable')
            .data('status', status)
            .data('summary', summary)
            .html(config.icon)
            .attr('aria-label', ariaLabel);
    }

    /**
     * Escape HTML to prevent XSS
     */
    function escapeHtml(text) {
        var map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };

        return text.replace(/[&<>"']/g, function(m) {
            return map[m];
        });
    }


    /**
     * Initialize on document ready
     */
    $(document).ready(function() {
        initAIReviewColumn();
    });


})(jQuery);
