/**
 * AI Auto Tool - Comment Generator
 * 
 * Handles manual comment generation from post editor
 * 
 * @package AI_Auto_Tool
 * @version 2.0
 */

(function($) {
    'use strict';

    // Wait for DOM ready
    $(document).ready(function() {
        initCommentGenerator();
    });

    /**
     * Initialize comment generator functionality
     */
    function initCommentGenerator() {
        const $button = $('#aiautotool-generate-comments-btn');
        
        if (!$button.length) {
            return;
        }

        // Handle button click
        $button.on('click', function(e) {
            e.preventDefault();
            handleGenerateComments($(this));
        });
    }

    /**
     * Handle comment generation request
     * 
     * @param {jQuery} $button - The button element
     */
    function handleGenerateComments($button) {
        // Confirm action
        if (!confirm(aiautotoolCommentGen.i18n.confirm)) {
            return;
        }

        const postId = $button.data('post-id');
        
        if (!postId) {
            showError(aiautotoolCommentGen.i18n.error);
            return;
        }

        // Disable button and show loading state
        setLoadingState($button, true);

        // Make AJAX request
        $.ajax({
            url: aiautotoolCommentGen.ajaxurl,
            type: 'POST',
            data: {
                action: 'aiautotool_manual_generate_comments',
                post_id: postId,
                security: aiautotoolCommentGen.nonce
            },
            timeout: 60000, // 60 seconds timeout
            success: function(response) {
                handleSuccess(response, $button);
            },
            error: function(xhr, status, error) {
                handleError(xhr, status, error, $button);
            }
        });
    }

    /**
     * Handle successful response
     * 
     * @param {Object} response - AJAX response
     * @param {jQuery} $button - The button element
     */
    function handleSuccess(response, $button) {
        setLoadingState($button, false);

        if (response.success) {
            showSuccess(response.data.message || aiautotoolCommentGen.i18n.success);
            
            // Update UI
            updateCommentCount();
            
            // Optionally reload page after short delay
            setTimeout(function() {
                location.reload();
            }, 2000);
        } else {
            const errorMessage = response.data && response.data.message ? 
                                response.data.message : 
                                aiautotoolCommentGen.i18n.error;
            
            // Check if it's a limit error
            if (errorMessage.includes('limit') || errorMessage.includes('upgrade')) {
                showError(aiautotoolCommentGen.i18n.limitExceeded);
            } else {
                showError(errorMessage);
            }
        }
    }

    /**
     * Handle error response
     * 
     * @param {Object} xhr - XMLHttpRequest object
     * @param {string} status - Error status
     * @param {string} error - Error message
     * @param {jQuery} $button - The button element
     */
    function handleError(xhr, status, error, $button) {
        setLoadingState($button, false);
        
        let errorMessage = aiautotoolCommentGen.i18n.error;
        
        if (status === 'timeout') {
            errorMessage = 'Request timeout. The AI is taking too long to respond. Please try again.';
        } else if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
            errorMessage = xhr.responseJSON.data.message;
        }
        
        showError(errorMessage);
        console.error('Comment generation error:', status, error);
    }

    /**
     * Set loading state for button
     * 
     * @param {jQuery} $button - The button element
     * @param {boolean} loading - Whether to show loading state
     */
    function setLoadingState($button, loading) {
        const $container = $button.closest('.aiautotool-comment-actions');
        const $info = $container.find('.aiautotool-generation-info');

        if (loading) {
            $button.prop('disabled', true).addClass('disabled');
            $info.show();
            
            // Update button text
            const $icon = $button.find('.dashicons');
            $icon.removeClass('dashicons-admin-comments').addClass('dashicons-update');
        } else {
            $button.prop('disabled', false).removeClass('disabled');
            $info.hide();
            
            // Restore button text
            const $icon = $button.find('.dashicons');
            $icon.removeClass('dashicons-update').addClass('dashicons-admin-comments');
        }
    }

    /**
     * Update comment count display
     */
    function updateCommentCount() {
        const $countSpan = $('.aiautotool-comment-stats .comment-count');
        if ($countSpan.length) {
            // Add visual feedback
            $countSpan.css('color', '#00a32a');
            setTimeout(function() {
                $countSpan.css('color', '');
            }, 2000);
        }
    }

    /**
     * Show success message
     * 
     * @param {string} message - Success message
     */
    function showSuccess(message) {
        showNotice(message, 'success');
    }

    /**
     * Show error message
     * 
     * @param {string} message - Error message
     */
    function showError(message) {
        showNotice(message, 'error');
    }

    /**
     * Show admin notice
     * 
     * @param {string} message - Notice message
     * @param {string} type - Notice type (success, error, warning, info)
     */
    function showNotice(message, type) {
        // Remove existing notices
        $('.aiautotool-comment-notice').remove();

        // Create notice element
        const noticeClass = 'notice notice-' + type + ' is-dismissible aiautotool-comment-notice';
        const $notice = $('<div>', {
            'class': noticeClass,
            'html': '<p>' + escapeHtml(message) + '</p>'
        });

        // Add dismiss button
        $notice.append(
            '<button type="button" class="notice-dismiss">' +
            '<span class="screen-reader-text">Dismiss this notice.</span>' +
            '</button>'
        );

        // Insert notice
        if ($('.wrap > h1').length) {
            $('.wrap > h1').after($notice);
        } else {
            $('.wrap').prepend($notice);
        }

        // Handle dismiss
        $notice.find('.notice-dismiss').on('click', function() {
            $notice.fadeOut(300, function() {
                $(this).remove();
            });
        });

        // Auto dismiss after 5 seconds for success messages
        if (type === 'success') {
            setTimeout(function() {
                $notice.fadeOut(300, function() {
                    $(this).remove();
                });
            }, 5000);
        }

        // Scroll to notice
        $('html, body').animate({
            scrollTop: $notice.offset().top - 100
        }, 300);
    }

    /**
     * Escape HTML to prevent XSS
     * 
     * @param {string} text - Text to escape
     * @return {string} Escaped text
     */
    function escapeHtml(text) {
        const map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return text.replace(/[&<>"']/g, function(m) { return map[m]; });
    }

    /**
     * Debug helper
     */
    function debug(message, data) {
        if (window.console && typeof window.console.log === 'function') {
            console.log('[AI Comment Generator] ' + message, data || '');
        }
    }

})(jQuery);

