jQuery(document).ready(function($){
    // -------------------------
    // Settings Page: Post Generation
    // -------------------------
    console.log("Front-end update script loaded.");
    var continuous = false;
    var continuousCount = 0;
    
    function generatePost(mode, topic, keyword) {
        console.log("generatePost called with mode:", mode, "topic:", topic, "keyword:", keyword);
        $('#easyaibloggen-status').html('<p>' + easyaibloggen_localized.generatingPost + '</p>');
        $.ajax({
            type: 'POST',
            url: easyaibloggen_localized.ajaxurl,
            data: {
                action: 'easyaibloggen_generate_post',
                nonce: easyaibloggen_localized.nonce,
                topic: topic,
                keyword: keyword,
                mode: mode,
                count: $('#easyaibloggen-count').val()
            },
            success: function(response) {
                console.log("generatePost response:", response);
                if(response.success){
                    $('#easyaibloggen-status').append('<p>' + easyaibloggen_localized.postCreated + ' ' + response.data + '</p>');
                    $('#easyaibloggen-generated-posts').load(location.href + ' #easyaibloggen-generated-posts > *');
                    if(continuous && (--continuousCount > 0)){
                        $.ajax({
                            type: 'POST',
                            url: easyaibloggen_localized.ajaxurl,
                            data: {
                                action: 'easyaibloggen_suggest_adjacent_topic',
                                nonce: easyaibloggen_localized.nonce_adjacent,
                                post_id: response.data
                            },
                            success: function(resp){
                                console.log("Adjacent topic response:", resp);
                                if(resp.success){
                                    generatePost('continuous', resp.data, keyword);
                                } else {
                                    $('#easyaibloggen-status').append('<p>' + easyaibloggen_localized.errorGettingAdjacent + ' ' + resp.data + '</p>');
                                }
                            },
                            error: function(jqXHR, textStatus){
                                $('#easyaibloggen-status').append('<p>' + easyaibloggen_localized.ajaxError + ' ' + textStatus + '</p>');
                                console.log("AJAX error on adjacent topic:", textStatus);
                            }
                        });
                    }
                } else {
                    $('#easyaibloggen-status').append('<p>' + easyaibloggen_localized.error + ' ' + response.data + '</p>');
                }
            },
            error: function(jqXHR, textStatus){
                $('#easyaibloggen-status').append('<p>' + easyaibloggen_localized.ajaxError + ' ' + textStatus + '</p>');
                console.log("AJAX error on generatePost:", textStatus);
            }
        });
    }
    
    $('#easyaibloggen-single-post').on('click', function(e){
        e.preventDefault();
        continuous = false;
        $('#easyaibloggen-stop-continuous').hide();
        var topic = $('#easyaibloggen-topic').val();
        var keyword = $('#easyaibloggen-keyword').val();
        generatePost('single', topic, keyword);
    });
    
    $('#easyaibloggen-start-continuous').on('click', function(e){
        e.preventDefault();
        continuous = true;
        $('#easyaibloggen-stop-continuous').show();
        var topic = $('#easyaibloggen-topic').val();
        var keyword = $('#easyaibloggen-keyword').val();
        continuousCount = parseInt($('#easyaibloggen-count').val()) || 5;
        generatePost('continuous', topic, keyword);
    });
    
    $('#easyaibloggen-stop-continuous').on('click', function(e){
        e.preventDefault();
        continuous = false;
        $('#easyaibloggen-stop-continuous').hide();
        $('#easyaibloggen-status').append('<p>' + easyaibloggen_localized.continuousStopped + '</p>');
    });
    
    // Use document-on-click for better event delegation with the Generate Similar button
    $(document).on('click', '.easyaibloggen-generate-similar', function(e){
        e.preventDefault();
        var topic = $(this).data('topic');
        var keyword = $(this).data('keyword');
        generatePost('single', topic, keyword);
    });
    
    // -------------------------
    // Settings Page: Scheduling Topics Generation
    // -------------------------
    $('#easyaibloggen-generate-schedule-data').on('click', function(e){
        e.preventDefault();
        var scheduleTopic = $('input[name="easyaibloggen_schedule_topic"]').val();
        if(scheduleTopic === ''){
            alert(easyaibloggen_localized.enterSchedulingTopic);
            return;
        }
        $('#easyaibloggen-schedule-data-status').html('<p>' + easyaibloggen_localized.generatingTopics + '</p>');
        $.ajax({
            type: 'POST',
            url: easyaibloggen_localized.ajaxurl,
            data: {
                action: 'easyaibloggen_generate_schedule_data',
                nonce: easyaibloggen_localized.scheduleNonce,
                schedule_topic: scheduleTopic
            },
            success: function(response) {
                if(response.success){
                    $('#easyaibloggen-schedule-data-status').html('<p>' + easyaibloggen_localized.scheduleDataSaved + '</p>');
                } else {
                    $('#easyaibloggen-schedule-data-status').html('<p>' + easyaibloggen_localized.error + ' ' + response.data + '</p>');
                }
            },
            error: function(jqXHR, textStatus){
                $('#easyaibloggen-schedule-data-status').html('<p>' + easyaibloggen_localized.ajaxError + ' ' + textStatus + '</p>');
            }
        });
    });
    
    // -------------------------
    // Update Metabox: Handling Update Button Clicks
    // -------------------------
    $(document).on('click', '.easyaibloggen-update-btn', function(e){
        e.preventDefault();
        var currentUpdateType = $(this).data('update-type');
        var currentPostId = $(this).data('postid');
        console.log("Preview update:", currentUpdateType, "Post ID:", currentPostId);
        var extraData = {};
        if(currentUpdateType === 'image'){
            extraData.image_style = $('#easyaibloggen-meta-image-style').val();
        }
        $('#easyaibloggen-update-preview').html('<p>Loading preview...</p>');
        $.ajax({
            type: 'POST',
            url: easyaibloggen_localized.ajaxurl,
            data: $.extend({
                action: 'easyaibloggen_update_' + currentUpdateType,
                nonce: easyaibloggen_localized.nonce_update,
                post_id: currentPostId,
                preview: 1
            }, extraData),
            success: function(response){
                console.log("Preview response:", response);
                if(response.success){
                    $('#easyaibloggen-update-preview').html('<p>Preview:</p><div>' + response.data.preview + '</div>');
                    $('#easyaibloggen-apply-changes')
                        .data('update-type', currentUpdateType)
                        .data('postid', currentPostId)
                        .show();
                } else {
                    $('#easyaibloggen-update-preview').html('<p>Error: ' + response.data + '</p>');
                    $('#easyaibloggen-apply-changes').hide();
                }
            },
            error: function(jqXHR, textStatus){
                $('#easyaibloggen-update-preview').html('<p>AJAX error: ' + textStatus + '</p>');
                console.log("AJAX error in preview:", textStatus);
                $('#easyaibloggen-apply-changes').hide();
            }
        });
    });
    
    // Use document-on-click for better event delegation
    $(document).on('click', '#easyaibloggen-apply-changes', function(e){
        e.preventDefault();
        var currentUpdateType = $(this).data('update-type');
        var currentPostId = $(this).data('postid');
        if(!currentUpdateType || !currentPostId){
            alert("No update to apply.");
            return;
        }
        console.log("Applying update:", currentUpdateType, "Post ID:", currentPostId);
        $('#easyaibloggen-update-preview').append('<p>Applying changes...</p>');
        var extraData = {};
        if(currentUpdateType === 'image'){
            extraData.image_style = $('#easyaibloggen-meta-image-style').val();
        }
        $.ajax({
            type: 'POST',
            url: easyaibloggen_localized.ajaxurl,
            data: $.extend({
                action: 'easyaibloggen_update_' + currentUpdateType,
                nonce: easyaibloggen_localized.nonce_update,
                post_id: currentPostId
            }, extraData),
            success: function(response){
                console.log("Apply response:", response);
                if(response.success){
                    $('#easyaibloggen-update-preview').append('<p>Update applied successfully.</p>');
                } else {
                    $('#easyaibloggen-update-preview').append('<p>Error applying update: ' + response.data + '</p>');
                }
            },
            error: function(jqXHR, textStatus){
                $('#easyaibloggen-update-preview').append('<p>AJAX error applying update: ' + textStatus + '</p>');
                console.log("AJAX error in apply:", textStatus);
            }
        });
    });
    
    // -------------------------
    // Format Conversion: Event Handlers
    // -------------------------
    $(document).on('click', '.easyaibloggen-convert-format-btn', function(e){
        e.preventDefault();
        var currentPostId = $(this).data('postid');
        var selectedFormat = $('#easyaibloggen-format-style').val();
        
        console.log("Convert format:", selectedFormat, "Post ID:", currentPostId);
        $('#easyaibloggen-update-preview').html('<p>Generating format preview...</p>');
        
        $.ajax({
            type: 'POST',
            url: easyaibloggen_localized.ajaxurl,
            data: {
                action: 'easyaibloggen_convert_format',
                nonce: easyaibloggen_localized.nonce_update,
                post_id: currentPostId,
                format: selectedFormat,
                preview: 1
            },
            success: function(response){
                console.log("Format preview response:", response);
                if(response.success){
                    $('#easyaibloggen-update-preview').html('<p>Preview of ' + selectedFormat + ' format:</p><div>' + response.data.preview + '</div>');
                    
                    // Create an apply button specifically for the format conversion
                    var applyButton = $('<button id="easyaibloggen-apply-format" class="button button-primary" style="margin-top:10px;">Apply Format Changes</button>');
                    $('#easyaibloggen-update-preview').append(applyButton);
                } else {
                    $('#easyaibloggen-update-preview').html('<p>Error: ' + response.data + '</p>');
                }
            },
            error: function(jqXHR, textStatus){
                $('#easyaibloggen-update-preview').html('<p>AJAX error: ' + textStatus + '</p>');
                console.log("AJAX error in format preview:", textStatus);
            }
        });
    });
    
    // Use document-on-click for the dynamically created Apply Format button
    $(document).on('click', '#easyaibloggen-apply-format', function(e){
        e.preventDefault();
        var postId = $('.easyaibloggen-convert-format-btn').data('postid');
        var format = $('#easyaibloggen-format-style').val();
        applyFormatChanges(postId, format);
    });
    
    function applyFormatChanges(postId, format) {
        $('#easyaibloggen-update-preview').append('<p>Applying format changes...</p>');
        
        $.ajax({
            type: 'POST',
            url: easyaibloggen_localized.ajaxurl,
            data: {
                action: 'easyaibloggen_convert_format',
                nonce: easyaibloggen_localized.nonce_update,
                post_id: postId,
                format: format
            },
            success: function(response){
                console.log("Format apply response:", response);
                if(response.success){
                    $('#easyaibloggen-update-preview').append('<p>Format changes applied successfully. <a href="' + window.location.href + '">Refresh</a> to see the updated post.</p>');
                } else {
                    $('#easyaibloggen-update-preview').append('<p>Error applying format changes: ' + response.data + '</p>');
                }
            },
            error: function(jqXHR, textStatus){
                $('#easyaibloggen-update-preview').append('<p>AJAX error applying format changes: ' + textStatus + '</p>');
                console.log("AJAX error in format apply:", textStatus);
            }
        });
    }
});
