jQuery(document).ready(function($) {
    let isProcessing = false;
    function getPostTitle() {
        if (typeof wp !== 'undefined' && wp.data && wp.data.select('core/editor')) {
            var title = wp.data.select('core/editor').getEditedPostAttribute('title');
            if (title && title.length > 0) return title;
        }

        var classicTitle = $('#title').val();
        if (classicTitle && classicTitle.length > 0) return classicTitle;

        var productTitle = $('#title').val();
        if (productTitle && productTitle.length > 0) return productTitle;
        
        return '';
    }
    
    function getEditorContent() {
        if (typeof wp !== 'undefined' && wp.data && wp.data.select('core/editor')) {
            var content = wp.data.select('core/editor').getEditedPostContent();
            if (content && content.length > 0) return content;

            var contentAttr = wp.data.select('core/editor').getEditedPostAttribute('content');
            if (contentAttr && contentAttr.length > 0) return contentAttr;
        }

        if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
            var tinyContent = tinyMCE.get('content').getContent();
            if (tinyContent && tinyContent.length > 0) return tinyContent;
        }

        var textareaContent = $('#content').val();
        if (textareaContent && textareaContent.length > 0) return textareaContent;
        
        return '';
    }
    
    function setEditorContent(content) {
        if (typeof wp !== 'undefined' && wp.data && wp.data.dispatch('core/editor')) {
            var originalContent = wp.data.select('core/editor').getEditedPostContent();

            wp.data.dispatch('core/editor').editPost({ content: content });

            if (wp.blocks && wp.blocks.parse) {
                var blocks = wp.blocks.parse(content);
                if (blocks && blocks.length) {
                    wp.data.dispatch('core/editor').resetBlocks(blocks);
                }
            }
            return;
        }

        if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
            tinyMCE.get('content').setContent(content);
            return;
        }

        $('#content').val(content);
    }
    
    // Event handlers ? event delegation
    $(document).on('click', '#thia-generate-desc, #thia-generate-desc-force', function() {
        if (isProcessing) return;
        
        let title = getPostTitle();
        if (!title) {
            alert('Please enter a title first!');
            return;
        }
        
        processRequest('generate', title, '');
    });
    
    $(document).on('click', '#thia-fix-grammar, #thia-fix-grammar-force', function() {
        if (isProcessing) return;
        
        let content = getEditorContent();
        if (!content) {
            alert('Please add content first!');
            return;
        }
        
        processRequest('grammar', '', content);
    });
    
    $(document).on('click', '#thia-format-text, #thia-format-text-force', function() {
        if (isProcessing) return;
        
        let content = getEditorContent();
        if (!content) {
            alert('Please add content first!');
            return;
        }
        
        processRequest('format', '', content);
    });
    
    $(document).on('click', '#thia-improve-readability, #thia-improve-readability-force', function() {
        if (isProcessing) return;
        
        let content = getEditorContent();
        if (!content) {
            alert('Please add content first!');
            return;
        }
        
        processRequest('readability', '', content);
    });
    
    $(document).on('click', '#thia-translate, #thia-translate-force', function() {
        if (isProcessing) return;
        
        let content = getEditorContent();
        if (!content) {
            alert('Please add content first!');
            return;
        }
        
        processRequest('translate', '', content);
    });
    
    function processRequest(action, title, content) {
        isProcessing = true;
        showModal(true, 'Thia is processing your request...');
        
        $('#thia-ai-status, #thia-ai-status-force').text('Processing...').css('color', '#f0ad4e');
        
        $.ajax({
            url: thia_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'thia_ai_action',
                action_type: action,
                title: title,
                content: content,
                nonce: thia_ajax.nonce
            },
            success: function(response) {
                isProcessing = false;
                
                if (response.success) {
                    setEditorContent(response.data);
                    showModal(false, 'Complete! Content has been updated.');
                    $('#thia-ai-status, #thia-ai-status-force').text('? Complete!').css('color', '#5cb85c');
                    setTimeout(function() {
                        $('#thia-creator-modal').fadeOut(300);
                        $('#thia-ai-status, #thia-ai-status-force').text('');
                    }, 1500);
                } else {
                    showModal(false, 'Error: ' + response.data);
                    $('#thia-ai-status, #thia-ai-status-force').text('Error: ' + response.data).css('color', '#d9534f');
                    setTimeout(function() {
                        $('#thia-creator-modal').fadeOut(300);
                        $('#thia-ai-status, #thia-ai-status-force').text('');
                    }, 3000);
                }
            },
            error: function(xhr, status, error) {
                isProcessing = false;
                showModal(false, 'Connection error: ' + error);
                $('#thia-ai-status, #thia-ai-status-force').text('Connection error!').css('color', '#d9534f');
                setTimeout(function() {
                    $('#thia-creator-modal').fadeOut(300);
                    $('#thia-ai-status, #thia-ai-status-force').text('');
                }, 3000);
            }
        });
    }
    
    function showModal(show, message) {
        if (show) {
            $('.thia-loading').show();
            $('.thia-result').hide();
            $('.thia-loading p').text(message);
            $('#thia-creator-modal').fadeIn(300);
        } else {
            $('.thia-loading').hide();
            $('.thia-result').show();
            $('.thia-result').html('<div class="result-content" style="padding: 20px; text-align: center;">' + message + '</div>');
        }
    }
    
    // Close modal
    $(document).on('click', '.thia-close, .thia-creator-modal-overlay', function() {
        if (!isProcessing) {
            $('#thia-creator-modal').fadeOut(300);
        }
    });
    
    // ESC key
    $(document).on('keydown', function(e) {
        if (e.key === 'Escape' && !isProcessing && $('#thia-creator-modal').is(':visible')) {
            $('#thia-creator-modal').fadeOut(300);
        }
    });
});