var SyrusDeepL = {
    
    isTranslating: false,
    
    translateContent: function() {
        if(this.isTranslating) {
            return;
        }
        
        var sourceLang = jQuery('#deepl-source-lang').val();
        var targetLang = jQuery('#deepl-target-lang').val();
        var translateSelected = jQuery('#deepl-translate-selected').is(':checked');
        var preserveFormatting = jQuery('#deepl-preserve-formatting').is(':checked');
        
        var content = '';
        var isGutenberg = false;
        
        if(typeof wp !== 'undefined' && wp.data && wp.data.select('core/editor')) {
            isGutenberg = true;
            
            if(translateSelected) {
                var selectedBlock = wp.data.select('core/block-editor').getSelectedBlock();
                if(selectedBlock && selectedBlock.attributes && selectedBlock.attributes.content) {
                    content = selectedBlock.attributes.content;
                } else {
                    var selection = window.getSelection().toString();
                    if(selection) {
                        content = selection;
                    } else {
                        alert('Please select text to translate');
                        return;
                    }
                }
            } else {
                content = wp.data.select('core/editor').getEditedPostContent();
            }
        } else {
            if(typeof tinyMCE !== 'undefined' && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden()) {
                if(translateSelected) {
                    content = tinyMCE.activeEditor.selection.getContent();
                    if(!content) {
                        alert('Please select text to translate');
                        return;
                    }
                } else {
                    content = tinyMCE.activeEditor.getContent();
                }
            } else {
                var contentField = jQuery('#content');
                if(contentField.length) {
                    if(translateSelected) {
                        var textarea = contentField[0];
                        if(textarea.selectionStart !== textarea.selectionEnd) {
                            content = textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);
                        } else {
                            alert('Please select text to translate');
                            return;
                        }
                    } else {
                        content = contentField.val();
                    }
                }
            }
        }
        
        if(!content || content.trim() === '') {
            alert('No content to translate');
            return;
        }
        
        this.isTranslating = true;
        jQuery('#deepl-translation-status').show();
        jQuery('#deepl-translation-error').hide().text('');
        jQuery('#btn-deepl-translate').prop('disabled', true);
        
        jQuery.ajax({
            url: syrus_deepl_args.ajax_url,
            type: 'POST',
            data: {
                action: 'deepl-translate-content',
                content: content,
                source_lang: sourceLang,
                target_lang: targetLang,
                preserve_formatting: preserveFormatting ? 1 : 0,
                translate_selected: translateSelected ? 1 : 0,
                post_id: jQuery('#post_ID').val()
            },
            success: function(response) {
                jQuery('#deepl-translation-status').hide();
                jQuery('#btn-deepl-translate').prop('disabled', false);
                SyrusDeepL.isTranslating = false;
                
                if(response.success) {
                    var translatedContent = response.data.text;
                    
                    if(isGutenberg) {
                        if(translateSelected) {
                            var selectedBlock = wp.data.select('core/block-editor').getSelectedBlock();
                            if(selectedBlock) {
                                wp.data.dispatch('core/block-editor').updateBlock(selectedBlock.clientId, {
                                    attributes: {
                                        content: translatedContent
                                    }
                                });
                            } else {
                                var newBlock = wp.blocks.createBlock('core/paragraph', {
                                    content: translatedContent
                                });
                                wp.data.dispatch('core/block-editor').insertBlocks(newBlock);
                            }
                        } else {
                            var blocks = wp.blocks.parse(translatedContent);
                            wp.data.dispatch('core/block-editor').resetBlocks(blocks);
                        }
                    } else {
                        if(typeof tinyMCE !== 'undefined' && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden()) {
                            if(translateSelected) {
                                tinyMCE.activeEditor.selection.setContent(translatedContent);
                            } else {
                                tinyMCE.activeEditor.setContent(translatedContent);
                            }
                        } else {
                            var contentField = jQuery('#content');
                            if(translateSelected) {
                                var textarea = contentField[0];
                                var start = textarea.selectionStart;
                                var end = textarea.selectionEnd;
                                var text = textarea.value;
                                textarea.value = text.substring(0, start) + translatedContent + text.substring(end);
                            } else {
                                contentField.val(translatedContent);
                            }
                        }
                    }
                    
                    if(response.data.detected_source_language) {
                        console.log('Detected language: ' + response.data.detected_source_language);
                    }
                    
                } else {
                    jQuery('#deepl-translation-error').show().text('Error: ' + (response.data.message || 'Translation failed'));
                }
            },
            error: function() {
                jQuery('#deepl-translation-status').hide();
                jQuery('#btn-deepl-translate').prop('disabled', false);
                jQuery('#deepl-translation-error').show().text('Connection error');
                SyrusDeepL.isTranslating = false;
            }
        });
    }
};

jQuery(document).ready(function() {
    if(typeof syrus_deepl_args === 'undefined') {
        window.syrus_deepl_args = {
            ajax_url: ajaxurl || '/wp-admin/admin-ajax.php'
        };
    }
});