(function($) {
    'use strict';

    // Cache DOM elements
    const $generateButton = $('#aifi-generate');
    const $promptInput = $('#aifi-prompt');
    const $customTextInput = $('#aifi-custom-text');
    const $styleSelect = $('#aifi-style');
    const $preview = $('#aifi-preview');
    const $message = $('#aifi-message');
    const $spinner = $('.aifi-actions .spinner');
    const $loadingSpinner = $('#aifi-loading-spinner');

    // --- Generate Prompt from Content ---

    var lastSavedPrompt = $promptInput.val();

    // Save prompt to post meta via REST
    function savePromptMeta(promptValue) {
        var postId = parseInt($('#post_ID').val(), 10);
        if (!postId) return;
        $.ajax({
            url: aifiData.savePromptUrl,
            method: 'POST',
            beforeSend: function(xhr) {
                xhr.setRequestHeader('X-WP-Nonce', aifiData.nonce);
                xhr.setRequestHeader('Content-Type', 'application/json');
            },
            data: JSON.stringify({ post_id: postId, prompt: promptValue }),
            processData: false
        });
    }

    // Auto-save prompt on blur if value changed
    $promptInput.on('blur', function() {
        var current = $promptInput.val();
        if (current !== lastSavedPrompt) {
            lastSavedPrompt = current;
            savePromptMeta(current);
        }
    });

    // Generate Prompt from Content button
    $('#aifi-generate-prompt').on('click', function(e) {
        e.preventDefault();

        // Stability AI doesn't support text generation
        if (aifiData.provider === 'stability') {
            $('#aifi-prompt-message')
                .removeClass('success error')
                .addClass('error')
                .text(aifiData.i18n.stabilityNoText)
                .show();
            return;
        }

        var postId = parseInt($('#post_ID').val(), 10);
        if (!postId) return;

        var $btn = $(this);
        var $promptSpinner = $('#aifi-prompt-spinner');
        var $promptMsg = $('#aifi-prompt-message');

        $btn.prop('disabled', true);
        $promptSpinner.addClass('is-active');
        $promptMsg.hide().removeClass('success error');

        $.ajax({
            url: aifiData.generatePromptUrl,
            method: 'POST',
            beforeSend: function(xhr) {
                xhr.setRequestHeader('X-WP-Nonce', aifiData.nonce);
                xhr.setRequestHeader('Content-Type', 'application/json');
            },
            data: JSON.stringify({ post_id: postId }),
            processData: false,
            success: function(response) {
                if (response.success && response.prompt) {
                    $promptInput.val(response.prompt);
                    lastSavedPrompt = response.prompt;
                    $promptMsg
                        .addClass('success')
                        .text(aifiData.i18n.promptGenerated)
                        .show();
                } else {
                    $promptMsg
                        .addClass('error')
                        .text(aifiData.i18n.promptError)
                        .show();
                }
            },
            error: function(xhr) {
                var msg = aifiData.i18n.promptError;
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    msg = xhr.responseJSON.message;
                }
                $promptMsg.addClass('error').text(msg).show();
            },
            complete: function() {
                $btn.prop('disabled', false);
                $promptSpinner.removeClass('is-active');
            }
        });
    });

    // Handle generate button click
    $generateButton.on('click', function(e) {
        e.preventDefault();

        // Persist prompt before generation if it changed
        var currentPrompt = $promptInput.val();
        if (currentPrompt !== lastSavedPrompt) {
            lastSavedPrompt = currentPrompt;
            savePromptMeta(currentPrompt);
        }

        // Reset UI
        $preview.hide();
        $message.hide().removeClass('success error');
        $generateButton.prop('disabled', true);
        $spinner.addClass('is-active');
        $loadingSpinner.show();

        // Get post ID from the page
        const postId = $('#post_ID').val();
        
        // Get post title - compatible with both Classic Editor and Block Editor
        let postTitle = '';
        
        // Try Classic Editor first (title field)
        const titleField = $('#title');
        if (titleField.length && titleField.val()) {
            postTitle = titleField.val();
        } else {
            // Fallback to Block Editor method
            // Try alternative selectors first (more reliable)
            const altTitle = $('.editor-post-title__input').val() || $('.wp-block-post-title input').val() || '';
            if (altTitle && altTitle.trim()) {
                postTitle = altTitle;
            } else {
                // Last resort: extract from H1, removing any "· PostType" suffix (e.g., "· Post", "· Movie", "· Product")
                const titleFromH1 = $('h1').eq(1).text().split('·')[0].trim();
                if (titleFromH1) {
                    postTitle = titleFromH1;
                }
            }
        }

        // Check if a featured image already exists and confirm overwrite
        let hasExistingImage = false;
        const existingThumbnail = $('#_thumbnail_id').val();
        if (existingThumbnail && parseInt(existingThumbnail) > 0) {
            hasExistingImage = true;
        } else if (typeof wp !== 'undefined' && wp.data && wp.data.select('core/editor')) {
            hasExistingImage = wp.data.select('core/editor').getEditedPostAttribute('featured_media') > 0;
        }
        if (hasExistingImage) {
            if (!confirm(aifiData.i18n.confirmOverwrite)) {
                $generateButton.prop('disabled', false);
                $spinner.removeClass('is-active');
                $loadingSpinner.hide();
                return;
            }
        }

        // Prepare request data
        const data = {
            post_id: postId,
            title: postTitle,
            prompt: $promptInput.val(),
            custom_text: $customTextInput.val(),
            style: $styleSelect.val()
        };

        // Make API request
        $.ajax({
            url: aifiData.restUrl,
            method: 'POST',
            beforeSend: function(xhr) {
                xhr.setRequestHeader('X-WP-Nonce', aifiData.nonce);
                xhr.setRequestHeader('Content-Type', 'application/json');
            },
            data: JSON.stringify(data),
            processData: false,
            success: function(response) {
                if (response.success) {
                    // Show success message
                    $message
                        .addClass('success')
                        .text(aifiData.i18n.success)
                        .show();

                    // Show preview
                    $preview
                        .find('img')
                        .attr('src', response.url)
                        .end()
                        .show();

                    // Show Stability tools if they exist (now that we have a featured image)
                    $('#aifi-stability-tools').show();

                    // Update featured image in the editor
                    if (aifiData.isClassicEditor) {
                        // Classic Editor: Set featured image using traditional method
                        $('#_thumbnail_id').val(response.attachment_id);
                        
                        // Update the featured image display in Classic Editor
                        const featuredImageContainer = $('#postimagediv');
                        if (featuredImageContainer.length) {
                            // Remove existing image if any
                            featuredImageContainer.find('.inside img').remove();
                            
                            // Add new image
                            const imgElement = $('<img>').attr({
                                'src': response.url,
                                'style': 'max-width: 100%; height: auto;'
                            });
                            
                            featuredImageContainer.find('.inside').prepend(imgElement);
                            
                            // Show the "Remove featured image" link if hidden
                            featuredImageContainer.find('.remove-post-thumbnail').show();
                        }
                    } else {
                        // Block Editor: Use wp.media method
                        if (wp.media && wp.media.featuredImage) {
                            wp.media.featuredImage.set(response.attachment_id);
                        }
                    }
                } else {
                    showError(response.message || aifiData.i18n.error);
                }
            },
            error: function(xhr) {
                let message = aifiData.i18n.error;
                
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    message = xhr.responseJSON.message;
                }

                showError(message);
            },
            complete: function() {
                $generateButton.prop('disabled', false);
                $spinner.removeClass('is-active');
                $loadingSpinner.hide();
            }
        });
    });

    /**
     * Show error message.
     *
     * @param {string} message Error message to display.
     */
    function showError(message) {
        $message
            .addClass('error')
            .text(message)
            .show();
    }

    // --- Stability AI Tools: Upscale & Remove Background ---

    var $stabilityTools = $('#aifi-stability-tools');
    var $stabilityLoading = $('#aifi-stability-loading');
    var $stabilityMessage = $('#aifi-stability-message');

    // Upscale button
    $('#aifi-upscale').on('click', function(e) {
        e.preventDefault();

        var $btn = $(this);
        var postId = $('#post_ID').val();
        var mode = $('#aifi-upscale-mode').val();

        $btn.prop('disabled', true);
        $stabilityMessage.hide().removeClass('success error');
        $stabilityLoading.show();

        $.ajax({
            url: aifiData.upscaleUrl,
            method: 'POST',
            beforeSend: function(xhr) {
                xhr.setRequestHeader('X-WP-Nonce', aifiData.nonce);
                xhr.setRequestHeader('Content-Type', 'application/json');
            },
            data: JSON.stringify({ post_id: parseInt(postId, 10), mode: mode }),
            processData: false,
            success: function(response) {
                if (response.success) {
                    $stabilityMessage.addClass('success').text(aifiData.i18n.upscaleSuccess).show();
                    updateFeaturedImage(response.attachment_id, response.url);
                } else {
                    $stabilityMessage.addClass('error').text(response.message || aifiData.i18n.upscaleError).show();
                }
            },
            error: function(xhr) {
                var msg = aifiData.i18n.upscaleError;
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    msg = xhr.responseJSON.message;
                }
                $stabilityMessage.addClass('error').text(msg).show();
            },
            complete: function() {
                $btn.prop('disabled', false);
                $stabilityLoading.hide();
            }
        });
    });

    // Remove Background button
    $('#aifi-remove-bg').on('click', function(e) {
        e.preventDefault();

        var $btn = $(this);
        var postId = $('#post_ID').val();

        $btn.prop('disabled', true);
        $stabilityMessage.hide().removeClass('success error');
        $stabilityLoading.show();

        $.ajax({
            url: aifiData.removeBgUrl,
            method: 'POST',
            beforeSend: function(xhr) {
                xhr.setRequestHeader('X-WP-Nonce', aifiData.nonce);
                xhr.setRequestHeader('Content-Type', 'application/json');
            },
            data: JSON.stringify({ post_id: parseInt(postId, 10) }),
            processData: false,
            success: function(response) {
                if (response.success) {
                    $stabilityMessage.addClass('success').text(aifiData.i18n.removeBgSuccess).show();
                    updateFeaturedImage(response.attachment_id, response.url);
                } else {
                    $stabilityMessage.addClass('error').text(response.message || aifiData.i18n.removeBgError).show();
                }
            },
            error: function(xhr) {
                var msg = aifiData.i18n.removeBgError;
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    msg = xhr.responseJSON.message;
                }
                $stabilityMessage.addClass('error').text(msg).show();
            },
            complete: function() {
                $btn.prop('disabled', false);
                $stabilityLoading.hide();
            }
        });
    });

    /**
     * Update the featured image in the editor after upscale/remove-bg.
     */
    function updateFeaturedImage(attachmentId, url) {
        // Update preview if visible
        $preview.find('img').attr('src', url);

        if (aifiData.isClassicEditor) {
            $('#_thumbnail_id').val(attachmentId);
            var $container = $('#postimagediv .inside');
            $container.find('img').remove();
            $container.prepend($('<img>').attr({ 'src': url, 'style': 'max-width: 100%; height: auto;' }));
            $('#postimagediv .remove-post-thumbnail').show();
        } else {
            if (wp.media && wp.media.featuredImage) {
                wp.media.featuredImage.set(attachmentId);
            }
        }
    }

    // Review request notice — dismissal handler.
    $(document).on('click', '.aifi-review-notice [data-aifi-review-action]', function(e) {
        var $btn    = $(this);
        var $notice = $btn.closest('.aifi-review-notice');
        var action  = $btn.attr('data-aifi-review-action');
        var rest    = $notice.attr('data-rest');
        var nonce   = $notice.attr('data-nonce');

        if (!rest || !nonce) return;

        // For the "Leave a review" link, let the new tab open naturally.
        if (action !== 'done') {
            e.preventDefault();
        }

        $.ajax({
            url: rest,
            method: 'POST',
            beforeSend: function(xhr) {
                xhr.setRequestHeader('X-WP-Nonce', nonce);
                xhr.setRequestHeader('Content-Type', 'application/json');
            },
            data: JSON.stringify({ state: action }),
            processData: false
        });

        $notice.addClass('aifi-review-hiding');
        setTimeout(function() { $notice.remove(); }, 250);
    });

})(jQuery); 