/**
 * Metabox JavaScript for HD SofT AI Summary
 *
 * @package HDSofT\AISummary
 */

(function($) {
    'use strict';

    $(document).ready(function() {
        var $metabox = $('.hdsoft-ai-summary-metabox');
        var $titleField = $('#hdsoft_ai_summary_title');
        var $textarea = $('#hdsoft_ai_summary_text');
        var $generateBtn = $('#hdsoft-generate-summary');
        var $result = $('#hdsoft-summary-result');
        var $manualFlag = $('#hdsoft_ai_summary_manual');
        var $postId = $('#hdsoft_post_id');

        // Track original values
        var originalTitle = $titleField.val();
        var originalSummary = $textarea.val();

        // Generate summary button handler
        $generateBtn.on('click', function(e) {
            e.preventDefault();
            generateSummary();
        });

        // Track manual edits
        $textarea.on('input', function() {
            var currentValue = $(this).val();
            if (currentValue !== originalSummary) {
                markAsManual();
            }
            updateStatus();
        });

        $titleField.on('input', function() {
            var currentValue = $(this).val();
            if (currentValue !== originalTitle) {
                markAsManual();
            }
            updateStatus();
        });

        // Generate summary function
        function generateSummary() {
            var postId = $postId.val();
            
            if (!postId) {
                showResult('error', 'Invalid post ID.');
                return;
            }
            
            // Show loading state
            setLoadingState(true);
            hideResult();
            
            $.ajax({
                url: hdsoft_ai_summary_metabox.ajax_url,
                type: 'POST',
                data: {
                    action: 'hdsoft_ai_summary_generate',
                    post_id: postId,
                    force_regenerate: true,
                    nonce: hdsoft_ai_summary_metabox.nonce
                },
                timeout: 60000,
                success: function(response) {
                    if (response.success) {
                        // Update both fields immediately
                        if (response.data.title) {
                            $titleField.val(response.data.title);
                            originalTitle = response.data.title;
                        }
                        
                        if (response.data.summary) {
                            $textarea.val(response.data.summary);
                            originalSummary = response.data.summary;
                        }
                        
                        // Mark as auto-generated
                        $manualFlag.val('0');
                        
                        showResult('success', hdsoft_ai_summary_metabox.strings.success);
                        updateStatus();
                        
                    } else {
                        var errorMessage = response.data && response.data.message 
                            ? response.data.message 
                            : 'Unknown error occurred.';
                        showResult('error', hdsoft_ai_summary_metabox.strings.error + ' ' + errorMessage);
                    }
                },
                error: function(xhr, status, error) {
                    var errorMessage = 'Request failed.';
                    
                    if (status === 'timeout') {
                        errorMessage = 'Request timed out. The summary generation is taking longer than expected.';
                    } else if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
                        errorMessage = xhr.responseJSON.data.message;
                    }
                    
                    showResult('error', hdsoft_ai_summary_metabox.strings.error + ' ' + errorMessage);
                },
                complete: function() {
                    setLoadingState(false);
                }
            });
        }

        // Mark summary as manually edited
        function markAsManual() {
            $manualFlag.val('1');
        }

        // Show result message
        function showResult(type, message) {
            $result.removeClass('success error')
                   .addClass(type)
                   .html(message)
                   .show();
            
            // Auto-hide success messages after 3 seconds
            if (type === 'success') {
                setTimeout(function() {
                    hideResult();
                }, 3000);
            }
        }

        // Hide result message
        function hideResult() {
            $result.hide().removeClass('success error');
        }

        // Set loading state
        function setLoadingState(loading) {
            if (loading) {
                $generateBtn.prop('disabled', true)
                           .find('span').removeClass('dashicons-update').addClass('dashicons-update-alt');
                $generateBtn.find('.dashicons').addClass('hdsoft-spinning');
                $generateBtn.contents().filter(function() {
                    return this.nodeType === 3;
                }).last().replaceWith(' ' + hdsoft_ai_summary_metabox.strings.generating);
                
                $metabox.addClass('hdsoft-loading');
            } else {
                $generateBtn.prop('disabled', false)
                           .find('span').removeClass('dashicons-update-alt').addClass('dashicons-update');
                $generateBtn.find('.dashicons').removeClass('hdsoft-spinning');
                $generateBtn.contents().filter(function() {
                    return this.nodeType === 3;
                }).last().replaceWith(' ' + hdsoft_ai_summary_metabox.strings.generate);
                
                $metabox.removeClass('hdsoft-loading');
            }
        }

        // Update status display
        function updateStatus() {
            var $statusContainer = $('.hdsoft-summary-status');
            var currentSummary = $textarea.val().trim();
            var isManual = $manualFlag.val() === '1';
            
            if (!currentSummary) {
                $statusContainer.empty();
                return;
            }
            
            var statusHtml = '';
            
            if (isManual) {
                statusHtml = '<p class="hdsoft-status-manual">' +
                    '<span class="dashicons dashicons-edit"></span>' +
                    'Manually edited' +
                    '</p>';
            } else {
                statusHtml = '<p class="hdsoft-status-auto">' +
                    '<span class="dashicons dashicons-robot"></span>' +
                    'Auto-generated' +
                    '</p>';
            }
            
            $statusContainer.html(statusHtml);
        }

        // Handle post save
        $('#post').on('submit', function() {
            // Check if fields were edited
            if ($titleField.val() !== originalTitle || $textarea.val() !== originalSummary) {
                $manualFlag.val('1');
            }
        });

        // Initialize status on page load
        updateStatus();

        // Add Gutenberg save completion listener for auto-refresh
        if (window.wp && wp.data) {
            let wasCurrentlySaving = false;
            
            wp.data.subscribe(function() {
                const editor = wp.data.select('core/editor');
                if (!editor) return;
                
                const isSavingPost = editor.isSavingPost();
                const isAutosaving = editor.isAutosavingPost();
                const didPostSaveRequestSucceed = editor.didPostSaveRequestSucceed();
                
                // Detect transition from saving to not saving (successful save completion)
                if (wasCurrentlySaving && !isSavingPost && !isAutosaving && didPostSaveRequestSucceed) {
                    // Only refresh if manual flag is 0 (auto-generation case)
                    if ($manualFlag.val() === '0') {
                        setTimeout(refreshFromServer, 1000); // Small delay to ensure server processing is complete
                    }
                }
                
                wasCurrentlySaving = isSavingPost && !isAutosaving;
            });
        }

        // Refresh summary fields from server
        function refreshFromServer() {
            var postId = $postId.val();
            
            if (!postId) return;
            
            $.ajax({
                url: hdsoft_ai_summary_metabox.ajax_url,
                type: 'POST',
                data: {
                    action: 'hdsoft_ai_summary_fetch',
                    post_id: postId,
                    nonce: hdsoft_ai_summary_metabox.nonce
                },
                success: function(response) {
                    if (response.success && response.data) {
                        // Update fields with fresh server data
                        $titleField.val(response.data.title);
                        $textarea.val(response.data.summary);
                        $manualFlag.val(response.data.is_manual ? '1' : '0');
                        
                        // Update tracking variables
                        originalTitle = response.data.title;
                        originalSummary = response.data.summary;
                        
                        // Update status display
                        updateStatus();
                    }
                },
                error: function() {
                    // Silently fail - user can still reload page manually if needed
                }
            });
        }

        // Initialize status on page load
        updateStatus();

        // Add spinning animation CSS
        if (!$('#hdsoft-metabox-styles').length) {
            $('<style id="hdsoft-metabox-styles">' +
                '.hdsoft-spinning { animation: hdsoft-spin 1s linear infinite; } ' +
                '@keyframes hdsoft-spin { to { transform: rotate(360deg); } }' +
                '</style>').appendTo('head');
        }
    });

})(jQuery);
