/**
 * Aysa Media Library Integration
 *
 * Handles the media library integration for Aysa plugin
 */
(function($) {
    'use strict';

    const mediaDebug = window.AYSA_DEBUG === true;
    const mediaDebugLog = (...args) => {
        if (mediaDebug) {
            console.log(...args);
        }
    };

    // Global flag to prevent infinite loops
    let isProcessing = false;
    let processingTimeout = null;

    // Initialize when document is ready
    $(document).ready(function() {
        initAltTextGeneration();
        
        // Simple approach - just monitor for buttons that appear
        monitorForButtons();
        
        // Ensure no dialogs are active on page load
        preventDialogs();
        
        // Add CSS for positioning AYSA section at top of media modal
        addMediaModalCSS();
        
        // Listen for image selection in media modal
        $(document).on('click', '.media-modal .attachment', function() {
            setTimeout(function() {
                mediaDebugLog('Image selected in media modal, moving AYSA section to top');
                moveAysaSectionToTop();
            }, 500);
        });
        
        // Aggressive monitoring for AYSA section appearance
        startAysaPositionMonitoring();
        
        mediaDebugLog('Aysa Media functionality initialized with simple approach');
    });
    
    /**
     * Simple monitoring for Aysa buttons
     */
    function monitorForButtons() {
        // Check for new buttons every few seconds in a non-aggressive way
        setInterval(function() {
            if (isProcessing) return; // Prevent overlapping checks
            
            const newButtons = $('.aysa-generate-alt-text:not(.aysa-initialized)');
            if (newButtons.length > 0) {
                mediaDebugLog('Found ' + newButtons.length + ' new Aysa buttons');
                newButtons.addClass('aysa-initialized');
                initAltTextGeneration();
            }
        }, 3000);
        
        // Listen for media modal opens with a simple approach
        $(document).on('click', '.add_media, .insert-media, .set-post-thumbnail', function() {
            setTimeout(function() {
                if (!isProcessing) {
                    checkForNewButtons();
                    // Re-apply CSS when modal opens to ensure positioning
                    addMediaModalCSS();
                    // Move AYSA section to top
                    moveAysaSectionToTop();
                }
            }, 2000);
            
            // Try again after a longer delay to ensure modal is fully loaded
            setTimeout(function() {
                moveAysaSectionToTop();
            }, 3000);
        });
    }
    
    /**
     * Simple check for new buttons without infinite loops
     */
    function checkForNewButtons() {
        if (isProcessing) return;
        
        isProcessing = true;
        
        // Clear any existing timeout
        if (processingTimeout) {
            clearTimeout(processingTimeout);
        }
        
        // Set timeout to reset processing flag
        processingTimeout = setTimeout(function() {
            isProcessing = false;
        }, 5000);
        
        mediaDebugLog('Checking for new Aysa buttons...');
        
        const newButtons = $('.aysa-generate-alt-text:not(.aysa-initialized)');
        if (newButtons.length > 0) {
            mediaDebugLog('Found ' + newButtons.length + ' uninitialized Aysa buttons');
            newButtons.addClass('aysa-initialized');
            
            // Highlight new upload buttons
            newButtons.filter('.aysa-new-upload').each(function() {
                $(this).css({
                    'background-color': '#4caf50',
                    'color': 'white',
                    'font-weight': 'bold'
                });
            });
        }
        
        // Reset processing flag
        setTimeout(function() {
            isProcessing = false;
        }, 1000);
    }
    
    /**
     * Prevent any dialogs from appearing and destroy existing ones
     */
    function preventDialogs() {
        // Check if jQuery UI dialog is available
        if (typeof $.ui !== 'undefined' && $.ui.dialog) {
            // Remove any existing dialogs
            $('.ui-dialog').remove();
            $('#aysa-parameters-dialog').remove();
            
            // Close any open dialogs
            $('.ui-dialog-content').dialog('close').remove();
            
            // Override the dialog function to prevent new dialogs
            const originalDialog = $.fn.dialog;
            $.fn.dialog = function(options) {
                if (this.hasClass('aysa-dialog') || this.attr('id') === 'aysa-parameters-dialog') {
                    mediaDebugLog('Aysa dialog prevented');
                    return this;
                }
                return originalDialog.apply(this, arguments);
            };
        }
        
        // Add a style to hide any dialogs that might appear
        if (!$('#aysa-prevent-dialogs').length) {
            $('head').append('<style id="aysa-prevent-dialogs">.ui-dialog, #aysa-parameters-dialog { display: none !important; }</style>');
        }
    }

    /**
     * Initialize alt text generation functionality
     */
    function initAltTextGeneration() {
        // Use event delegation to ensure buttons work even when added dynamically
        $(document).off('click.aysa', '.aysa-generate-alt-text').on('click.aysa', '.aysa-generate-alt-text', function(e) {
            e.preventDefault();
            
            mediaDebugLog('Aysa AI Alt Text button clicked');
            
            // Check if this is a newly uploaded image
            const isNewUpload = $(this).hasClass('aysa-new-upload');
            if (isNewUpload) {
                mediaDebugLog('Button clicked on newly uploaded image');
            }
            
            // Ensure no dialogs appear
            preventDialogs();
            
            const attachmentId = $(this).data('attachment-id');
            const statusContainer = $('#aysa-alt-text-status-' + attachmentId);
            
            if (!attachmentId) {
                console.error('No attachment ID found on button');
                return;
            }
            
            // Show loading state
            statusContainer.html('<span style="color:#f57c00;">Analyzing image and generating AI content...</span>');
            
            // Get parameters from metabox
            const language = getLanguageFromMetabox();
            const primaryKeyword = getPrimaryKeywordFromMetabox();
            const tone = getToneFromMetabox();
            const targetAudience = getTargetAudienceFromMetabox();
            
            // Get context information from current page
            const contextInfo = getCurrentPageContext();
            
            mediaDebugLog('Context info:', contextInfo);
            
            // Generate alt text directly without showing dialog
            generateAltText(attachmentId, language, primaryKeyword, tone, targetAudience, contextInfo);
            
            // Add a small delay and check again to make sure no dialogs appeared
            setTimeout(preventDialogs, 100);
        });
        
        // Check for newly uploaded images specifically
        setTimeout(function() {
            const newUploadButtons = $('.aysa-generate-alt-text.aysa-new-upload:not(.aysa-styled)');
            if (newUploadButtons.length) {
                mediaDebugLog('Found ' + newUploadButtons.length + ' buttons for newly uploaded images');
                
                // Highlight these buttons to make them more noticeable
                newUploadButtons.each(function() {
                    const $button = $(this);
                    $button.css({
                        'background-color': '#4caf50',
                        'color': 'white',
                        'font-weight': 'bold'
                    }).addClass('aysa-styled');
                });
                
                // Add CSS for pulse animation if it doesn't exist
                if (!$('#aysa-pulse-style').length) {
                    $('head').append(`
                        <style id="aysa-pulse-style">
                        .aysa-generate-alt-text.aysa-new-upload {
                            animation: aysa-pulse 2s infinite;
                        }
                        @keyframes aysa-pulse {
                            0% { transform: scale(1); }
                            50% { transform: scale(1.05); }
                            100% { transform: scale(1); }
                        }
                        </style>
                    `);
                }
            }
            
            const existingButtons = $('.aysa-generate-alt-text');
            if (existingButtons.length) {
                mediaDebugLog('Found ' + existingButtons.length + ' existing Aysa buttons on page load');
            }
        }, 500);
    }
    
    /**
     * Get context information from the current page (category or product edit)
     */
    function getCurrentPageContext() {
        const context = {
            entity_id: 0,
            entity_type: '',
            entity_name: '',
            entity_description: ''
        };
        
        // Check if we have aysa_media_params with context info
        if (typeof aysa_media_params !== 'undefined') {
            if (aysa_media_params.is_category_page && aysa_media_params.current_term_id) {
                context.entity_id = aysa_media_params.current_term_id;
                context.entity_type = 'category';
                
                // Try to get category name from page
                const categoryNameField = $('#name, input[name="name"]');
                if (categoryNameField.length) {
                    context.entity_name = categoryNameField.val();
                }
                
                // Try to get category description
                const categoryDescField = $('#description, textarea[name="description"]');
                if (categoryDescField.length) {
                    context.entity_description = categoryDescField.val();
                }
                
                // If TinyMCE is active for description
                if (typeof tinyMCE !== 'undefined' && tinyMCE.get('description')) {
                    context.entity_description = tinyMCE.get('description').getContent();
                }
            } else if (aysa_media_params.is_product_page && aysa_media_params.current_post_id) {
                context.entity_id = aysa_media_params.current_post_id;
                context.entity_type = 'product';
                
                // Try to get product title
                const productTitleField = $('#title, input[name="post_title"]');
                if (productTitleField.length) {
                    context.entity_name = productTitleField.val();
                }
                
                // Try to get product content/excerpt
                const productContentField = $('#content, textarea[name="content"]');
                if (productContentField.length) {
                    context.entity_description = productContentField.val();
                }
                
                // If TinyMCE is active for content
                if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
                    context.entity_description = tinyMCE.get('content').getContent();
                }
            }
        }
        
        return context;
    }
     
     /**
      * Get WordPress nonce from available global objects
      */
     function getWpNonce() {
         // First try our specific localized object which should be most reliable
         if (typeof aysa_media_params !== 'undefined' && aysa_media_params.nonce) {
             mediaDebugLog('Found nonce in aysa_media_params (most reliable)');
             return aysa_media_params.nonce;
         }
         
         // Try different possible global objects that might contain the nonce
         if (typeof aysa_ajax !== 'undefined' && aysa_ajax.nonce) {
             mediaDebugLog('Found nonce in aysa_ajax');
             return aysa_ajax.nonce;
         }
         
         if (typeof aysaParams !== 'undefined' && aysaParams.nonce) {
             mediaDebugLog('Found nonce in aysaParams');
             return aysaParams.nonce;
         }
         
         if (typeof aysa_params !== 'undefined' && aysa_params.nonce) {
             mediaDebugLog('Found nonce in aysa_params');
             return aysa_params.nonce;
         }
         
         if (typeof wpApiSettings !== 'undefined' && wpApiSettings.nonce) {
             mediaDebugLog('Found nonce in wpApiSettings');
             return wpApiSettings.nonce;
         }
         
         // Try core WordPress REST nonce
         if (typeof wp !== 'undefined' && wp.apiFetch && wp.apiFetch.nonceMiddleware) {
             try {
                 const nonce = wp.apiFetch.nonceMiddleware.nonce;
                 if (nonce) {
                    mediaDebugLog('Found nonce in wp.apiFetch.nonceMiddleware');
                     return nonce;
                 }
             } catch (e) {}
         }
         
         // Try to find nonce in the DOM (WordPress often adds it as a hidden field)
         const nonceField = $('#_wpnonce').val() || $('input[name="_wpnonce"]').val();
         if (nonceField) {
             mediaDebugLog('Found nonce in DOM input field');
             return nonceField;
         }
         
         console.error('Could not find WordPress nonce!');
         return '';
     }
     
     /**
      * Get WordPress AJAX URL from available global objects
      */
     function getAjaxUrl() {
         // First try our specific localized object which should be most reliable
         if (typeof aysa_media_params !== 'undefined' && aysa_media_params.ajax_url) {
             return aysa_media_params.ajax_url;
         }
         
         // Try different possible global objects that might contain the AJAX URL
         if (typeof aysa_ajax !== 'undefined' && aysa_ajax.ajax_url) {
             return aysa_ajax.ajax_url;
         }
         
         if (typeof aysaParams !== 'undefined' && aysaParams.ajax_url) {
             return aysaParams.ajax_url;
         }
         
         if (typeof aysa_params !== 'undefined' && aysa_params.ajax_url) {
             return aysa_params.ajax_url;
         }
         
         if (typeof ajaxurl !== 'undefined') {
             return ajaxurl;
         }
         
         // WordPress default
         return '/wp-admin/admin-ajax.php';
     }
    
    /**
     * Generate alt text via AJAX
     */
    function generateAltText(attachmentId, language, primaryKeyword, tone, targetAudience, contextInfo) {
        const statusContainer = $('#aysa-alt-text-status-' + attachmentId);
        
        // Get nonce and AJAX URL
        const nonce = getWpNonce();
        const ajaxUrl = getAjaxUrl();
        
        // Debug log to help identify issues
        mediaDebugLog('Generating alt text with:', {
            attachmentId: attachmentId,
            nonce: nonce ? 'Found' : 'Not found',
            ajaxUrl: ajaxUrl
        });
        
        // Ensure we have a valid nonce
        if (!nonce) {
            console.error('No valid nonce found. Cannot proceed with AJAX request.');
            statusContainer.html(
                '<div style="color:#f44336; margin-top:10px;">' +
                '<strong>Error:</strong> Security verification failed. Please refresh the page and try again.' +
                '</div>'
            );
            
            // Try to create a nonce via AJAX as a fallback (WordPress has an endpoint for this)
            $.ajax({
                url: ajaxUrl,
                type: 'POST',
                data: {
                    action: 'aysa_create_nonce',
                    create_for: 'aysa_nonce'
                },
                success: function(response) {
                    if (response.success && response.data && response.data.nonce) {
                        mediaDebugLog('Successfully created new nonce. Retrying request.');
                        // Store the nonce in a global variable
                        if (typeof aysa_media_params === 'undefined') {
                            window.aysa_media_params = { nonce: response.data.nonce };
                        } else {
                            aysa_media_params.nonce = response.data.nonce;
                        }
                        // Retry the request
                        setTimeout(function() {
                            generateAltText(attachmentId, language, primaryKeyword, tone, targetAudience, contextInfo);
                        }, 500);
                    } else {
                        console.error('Failed to create nonce:', response);
                    }
                },
                error: function() {
                    console.error('Ajax request to create nonce failed');
                }
            });
            return;
        }
        
        // Get secondary keywords if the input field exists
        let secondaryKeywords = '';
        const secondaryKeywordsInput = $('#aysa-entity-second-keyword');
        if (secondaryKeywordsInput.length > 0 && secondaryKeywordsInput.val()) {
            secondaryKeywords = secondaryKeywordsInput.val();
        }

        // Create the AJAX data object
        const ajaxData = {
            action: 'aysa_generate_alt_text',
            attachment_id: attachmentId,
            language: language,
            primary_keyword: primaryKeyword,
            secondary_keywords: secondaryKeywords,
            tone: tone,
            target_audience: targetAudience
        };
        
        // Add context information if available
        if (contextInfo && contextInfo.entity_id) {
            ajaxData.context_entity_id = contextInfo.entity_id;
            ajaxData.context_entity_type = contextInfo.entity_type;
            ajaxData.context_entity_name = contextInfo.entity_name;
            ajaxData.context_entity_description = contextInfo.entity_description;
        }
        
        // Add the nonce with multiple parameter names to ensure one works
        ajaxData.nonce = nonce;
        ajaxData._wpnonce = nonce;
        ajaxData.security = nonce;
        
        // Only add the standard header
        const headers = {
            'X-Requested-With': 'XMLHttpRequest'
        };
        
        // Show what we're actually sending
        mediaDebugLog('Sending AJAX request with data:', ajaxData);
        
        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: ajaxData,
            headers: headers,
            beforeSend: function() {
                statusContainer.html('<span style="color:#f57c00;">Analyzing image and generating AI content...</span>');
                
                // Make sure no dialogs appear during AJAX request
                preventDialogs();
            },
            success: function(response) {
                // Log the raw response for debugging
                mediaDebugLog('Raw AJAX response:', response);
                
                if (response.success) {
                    // Show success message
                    statusContainer.html(
                        '<div style="color:#4caf50; margin-top:10px;">' + 
                        '<strong>Success!</strong> ' + response.data.message + 
                        '<div style="margin-top:5px;"><strong>Alt Text:</strong> ' + response.data.alt_text + '</div>' +
                        '</div>'
                    );
                    
                    // Update all form fields immediately in real-time
                    updateFormFields(response.data);
                    
                    // Show simple success notification
                    showSuccessNotification();
                } else {
                    // Show detailed error message
                    let errorMessage = 'An unknown error occurred.';
                    if (response.data && response.data.message) {
                        errorMessage = response.data.message;
                    }
                    
                    statusContainer.html(
                        '<div style="color:#f44336; margin-top:10px;">' +
                        '<strong>Error:</strong> ' + errorMessage + 
                        '</div>'
                    );
                    
                    console.error('AJAX Error:', response);
                }
            },
            error: function(xhr, status, error) {
                // Show error message with more details
                let errorDetails = '';
                let errorMessage = 'Failed to connect to the server';
                let recoveryMessage = '';
                
                try {
                    // Try to parse the response as JSON
                    if (xhr.responseText) {
                        try {
                            const jsonResponse = JSON.parse(xhr.responseText);
                            if (jsonResponse.data && jsonResponse.data.message) {
                                errorMessage = jsonResponse.data.message;
                            }
                        } catch (e) {
                            // If we can't parse as JSON, use the raw text
                            if (xhr.responseText.length < 100) {
                                errorDetails = xhr.responseText;
                            } else {
                                errorDetails = xhr.responseText.substring(0, 100) + '...';
                            }
                        }
                    }
                    
                    // Add more context based on status code
                    if (xhr.status === 403) {
                        recoveryMessage = 'You may not have permission to perform this action or your session has expired. Try logging out and back in.';
                    } else if (xhr.status === 404) {
                        recoveryMessage = 'The server endpoint could not be found. Please contact the plugin developer.';
                    } else if (xhr.status === 500) {
                        recoveryMessage = 'The server encountered an error. Please check the server logs for more information.';
                    } else if (status === 'timeout') {
                        recoveryMessage = 'The request timed out. Please try again later when the server is less busy.';
                    } else if (status === 'abort') {
                        recoveryMessage = 'The request was aborted. Please try again.';
                    } else if (status === 'parsererror') {
                        recoveryMessage = 'The server response could not be parsed. Please contact the plugin developer.';
                    }
                } catch (e) {
                    console.error('Error processing AJAX error:', e);
                }
                
                // Construct the error message
                let errorHtml = 
                    '<div style="color:#f44336; margin-top:10px;">' +
                    '<strong>Error:</strong> ' + errorMessage + '<br>';
                
                if (status) {
                    errorHtml += 'Status: ' + status + '<br>';
                }
                
                if (error) {
                    errorHtml += 'Error: ' + error + '<br>';
                }
                
                if (errorDetails) {
                    errorHtml += 'Details: ' + errorDetails + '<br>';
                }
                
                if (recoveryMessage) {
                    errorHtml += '<hr style="margin:8px 0; border-color:#f443364d;">' +
                                '<span style="font-style:italic;">' + recoveryMessage + '</span>';
                }
                
                // Add a retry button
                errorHtml += '<div style="margin-top:10px;">' +
                            '<button type="button" class="button retry-alt-text-generation" ' +
                            'data-id="' + attachmentId + '" ' +
                            'data-lang="' + language + '" ' +
                            'data-keyword="' + primaryKeyword + '" ' +
                            'data-tone="' + tone + '" ' +
                            'data-audience="' + targetAudience + '" ' +
                            'data-context-info="' + JSON.stringify(contextInfo || {}) + '">' +
                            'Retry</button>' +
                            '</div>' +
                            '</div>';
                
                // Update the status container
                statusContainer.html(errorHtml);
                
                // Add event listener for the retry button
                statusContainer.find('.retry-alt-text-generation').on('click', function() {
                    const btnData = $(this).data();
                    let retryContextInfo = {};
                    
                    try {
                        retryContextInfo = JSON.parse(btnData.contextInfo || '{}');
                    } catch (e) {
                        console.warn('Could not parse context info for retry:', e);
                        retryContextInfo = {};
                    }
                    
                    generateAltText(
                        btnData.id,
                        btnData.lang,
                        btnData.keyword,
                        btnData.tone,
                        btnData.audience,
                        retryContextInfo
                    );
                });
                
                console.error('AJAX Error Details:', {
                    xhr: xhr, 
                    status: status, 
                    error: error,
                    responseText: xhr.responseText
                });
            }
        });
    }
    
    /**
     * Update all form fields with the new values
     */
    function updateFormFields(data) {
        mediaDebugLog('=== DEBUGGING FIELD UPDATE ===');
        mediaDebugLog('Data received:', data);
        
        // Wait a moment for modal to be ready
        setTimeout(function() {
            
            // Since data-setting doesn't exist, try other approaches
            mediaDebugLog('=== TRYING ALTERNATIVE FIELD DETECTION ===');
            
            // Method 1: Find by name attribute
            mediaDebugLog('Method 1: Looking for fields by name...');
            
            // Try specific WordPress media modal IDs first (from console analysis)
            mediaDebugLog('Trying specific WordPress media modal IDs...');
            
            // Alt text by specific ID
            let altField = $('#attachment-details-alt-text');
            if (altField.length && data.alt_text) {
                mediaDebugLog('Found alt field by specific ID:', altField);
                altField.val(data.alt_text);
                altField.trigger('input').trigger('change');
                mediaDebugLog('Alt field updated to:', altField.val());
            }
            
            // Title by specific ID
            let titleField = $('#attachment-details-title');
            if (titleField.length && data.title) {
                mediaDebugLog('Found title field by specific ID:', titleField);
                titleField.val(data.title);
                titleField.trigger('input').trigger('change');
                mediaDebugLog('Title field updated to:', titleField.val());
            }
            
            // Caption by specific ID
            let captionField = $('#attachment-details-caption');
            if (captionField.length && data.caption) {
                mediaDebugLog('Found caption field by specific ID:', captionField);
                captionField.val(data.caption);
                captionField.trigger('input').trigger('change');
                mediaDebugLog('Caption field updated to:', captionField.val());
            }
            
            // Description by specific ID
            let descriptionField = $('#attachment-details-description');
            if (descriptionField.length && data.description) {
                mediaDebugLog('Found description field by specific ID:', descriptionField);
                descriptionField.val(data.description);
                descriptionField.trigger('input').trigger('change');
                mediaDebugLog('Description field updated to:', descriptionField.val());
            }
            
            // If specific IDs didn't work, try fallback methods
            mediaDebugLog('Trying fallback methods for missing fields...');
            
            // Alt text by name (fallback)
            if (!altField.length) {
                altField = $('input[name*="alt"], textarea[name*="alt"]').first();
                if (!altField.length) {
                    altField = $('input[name="_wp_attachment_image_alt"]');
                }
                if (!altField.length) {
                    altField = $('input[name="image_alt"]');
                }
                
                if (altField.length && data.alt_text) {
                    mediaDebugLog('Found alt field by fallback method:', altField);
                    altField.val(data.alt_text);
                    altField.trigger('input').trigger('change');
                    mediaDebugLog('Alt field updated to:', altField.val());
                }
            }
            
            // Title by name
            if (!titleField.length) {
                titleField = $('input[name*="title"]').first();
            }
            if (!titleField.length) {
                // Try by ID
                titleField = $('#post_title, #attachment_title');
            }
            if (!titleField.length) {
                // Try by placeholder
                titleField = $('input[placeholder*="title"], input[placeholder*="Title"]').first();
            }
            if (!titleField.length) {
                // Try by class
                titleField = $('.title input, input.title').first();
            }
            
            if (titleField.length && data.title) {
                mediaDebugLog('Found title field by name:', titleField);
                titleField.val(data.title);
                titleField.trigger('input').trigger('change');
                mediaDebugLog('Title field updated to:', titleField.val());
            } else {
                mediaDebugLog('No title field found. Tried: name, ID, placeholder, class');
            }
            
            // Caption by name
            if (!captionField.length) {
                captionField = $('textarea[name="post_excerpt"]');
            }
            if (!captionField.length) {
                captionField = $('textarea[name="excerpt"]');
            }
            if (!captionField.length) {
                captionField = $('textarea[name*="caption"]').first();
            }
            if (!captionField.length) {
                // Try by ID
                captionField = $('#post_excerpt, #attachment_caption, #excerpt');
            }
            if (!captionField.length) {
                // Try by placeholder
                captionField = $('textarea[placeholder*="caption"], textarea[placeholder*="Caption"]').first();
            }
            if (!captionField.length) {
                // Try by class
                captionField = $('.caption textarea, textarea.caption').first();
            }
            
            if (captionField.length && data.caption) {
                mediaDebugLog('Found caption field by name:', captionField);
                captionField.val(data.caption);
                captionField.trigger('input').trigger('change');
                mediaDebugLog('Caption field updated to:', captionField.val());
            } else {
                mediaDebugLog('No caption field found. Tried: name, ID, placeholder, class');
            }
            
            // Description by name
            if (!descriptionField.length) {
                descriptionField = $('textarea[name="post_content"]');
            }
            if (!descriptionField.length) {
                descriptionField = $('textarea[name*="content"]').first();
            }
            if (!descriptionField.length) {
                descriptionField = $('textarea[name*="description"]').first();
            }
            if (!descriptionField.length) {
                // Try by ID - add the specific WordPress media modal IDs
                descriptionField = $('#post_content, #attachment_content, #content, #description, #attachment-details-description');
            }
            if (!descriptionField.length) {
                // Try by placeholder
                descriptionField = $('textarea[placeholder*="description"], textarea[placeholder*="Description"]').first();
            }
            if (!descriptionField.length) {
                // Try by class
                descriptionField = $('.description textarea, textarea.description, .content textarea, textarea.content').first();
            }
            if (!descriptionField.length) {
                // Try specific WordPress media modal pattern
                descriptionField = $('textarea[id*="description"]').first();
            }
            
            if (descriptionField && descriptionField.length && data.description) {
                mediaDebugLog('Found description field:', descriptionField);
                mediaDebugLog('Description field attributes:', {
                    name: descriptionField.attr('name'),
                    id: descriptionField.attr('id'),
                    class: descriptionField.attr('class'),
                    placeholder: descriptionField.attr('placeholder')
                });
                descriptionField.val(data.description);
                descriptionField.trigger('input').trigger('change');
                mediaDebugLog('Description field updated to:', descriptionField.val());
            } else {
                mediaDebugLog('No description field found. Tried: name, ID, placeholder, class, largest textarea, second textarea, last textarea, any textarea not caption');
                mediaDebugLog('Available textareas count:', $('textarea').length);
                mediaDebugLog('Caption field:', captionField ? captionField[0] : 'none');
                
                // Log all textareas for debugging
                $('textarea').each(function(index) {
                    mediaDebugLog(`Textarea ${index}:`, {
                        element: this,
                        name: $(this).attr('name'),
                        id: $(this).attr('id'),
                        class: $(this).attr('class'),
                        placeholder: $(this).attr('placeholder'),
                        value: $(this).val().substring(0, 50) + '...'
                    });
                });
            }
            
            // Method 2: Find by placeholder text
            mediaDebugLog('Method 2: Looking for fields by placeholder...');
            
            if (!altField.length) {
                altField = $('input[placeholder*="alt"], textarea[placeholder*="alt"]').first();
                if (altField.length && data.alt_text) {
                    mediaDebugLog('Found alt field by placeholder:', altField);
                    altField.val(data.alt_text);
                    altField.trigger('input').trigger('change');
                }
            }
            
            // Method 2.5: Backup - find fields by position/siblings
            mediaDebugLog('Method 2.5: Looking for fields by position/siblings...');
            
            // If we found alt field, try to find other fields near it
            if (altField.length) {
                const altContainer = altField.closest('form, .media-modal, .attachment-details');
                
                // Look for title field in the same container
                if (!titleField.length || titleField.length === 0) {
                    titleField = altContainer.find('input[type="text"]').not(altField).first();
                    if (titleField.length && data.title) {
                        mediaDebugLog('Found title field by position near alt field:', titleField);
                        titleField.val(data.title);
                        titleField.trigger('input').trigger('change');
                        mediaDebugLog('Title field updated to:', titleField.val());
                    }
                }
                
                // Look for textareas in the same container
                if ((!captionField.length || captionField.length === 0) && (!descriptionField.length || descriptionField.length === 0)) {
                    const textareas = altContainer.find('textarea');
                    if (textareas.length >= 1 && data.caption) {
                        captionField = textareas.first();
                        mediaDebugLog('Found caption field by position (first textarea):', captionField);
                        captionField.val(data.caption);
                        captionField.trigger('input').trigger('change');
                        mediaDebugLog('Caption field updated to:', captionField.val());
                    }
                    
                    if (textareas.length >= 2 && data.description) {
                        descriptionField = textareas.last();
                        mediaDebugLog('Found description field by position (last textarea):', descriptionField);
                        descriptionField.val(data.description);
                        descriptionField.trigger('input').trigger('change');
                        mediaDebugLog('Description field updated to:', descriptionField.val());
                    }
                }
                
                // Special focus on description field if still not found
                if ((!descriptionField || descriptionField.length === 0) && data.description) {
                    mediaDebugLog('Special attempt to find description field...');
                    const allTextareas = altContainer.find('textarea');
                    
                    // Try to find a textarea that's not the caption field
                    allTextareas.each(function() {
                        const $this = $(this);
                        if (!captionField || !captionField.length || !$this.is(captionField)) {
                            descriptionField = $this;
                            mediaDebugLog('Found description field by exclusion (not caption):', descriptionField);
                            descriptionField.val(data.description);
                            descriptionField.trigger('input').trigger('change');
                            mediaDebugLog('Description field updated to:', descriptionField.val());
                            return false; // Break the loop
                        }
                    });
                }
            }
            
            // Method 2.7: Try WordPress standard field order
            mediaDebugLog('Method 2.7: Trying WordPress standard field order...');
            
            if (!titleField.length || !captionField.length || !descriptionField.length) {
                const allInputs = $('input[type="text"]');
                const allTextareas = $('textarea');
                
                // Usually in WordPress: first input is title, first textarea is caption, second is description
                if (!titleField.length && allInputs.length >= 1 && data.title) {
                    titleField = allInputs.first();
                    if (!titleField.is(altField)) { // Make sure it's not the alt field
                        mediaDebugLog('Found title field by standard order (first text input):', titleField);
                        titleField.val(data.title);
                        titleField.trigger('input').trigger('change');
                        mediaDebugLog('Title field updated to:', titleField.val());
                    }
                }
                
                if (!captionField.length && allTextareas.length >= 1 && data.caption) {
                    captionField = allTextareas.first();
                    mediaDebugLog('Found caption field by standard order (first textarea):', captionField);
                    captionField.val(data.caption);
                    captionField.trigger('input').trigger('change');
                    mediaDebugLog('Caption field updated to:', captionField.val());
                }
                
                if (!descriptionField.length && allTextareas.length >= 2 && data.description) {
                    descriptionField = allTextareas.eq(1); // Second textarea
                    mediaDebugLog('Found description field by standard order (second textarea):', descriptionField);
                    descriptionField.val(data.description);
                    descriptionField.trigger('input').trigger('change');
                    mediaDebugLog('Description field updated to:', descriptionField.val());
                }
            }
            
            // Method 3: Find by label text
            mediaDebugLog('Method 3: Looking for fields by label...');
            
            if (!altField.length) {
                $('label').each(function() {
                    const labelText = $(this).text().toLowerCase();
                    if (labelText.includes('alt') || labelText.includes('alternative')) {
                        const labelFor = $(this).attr('for');
                        if (labelFor) {
                            altField = $('#' + labelFor);
                            if (altField.length && data.alt_text) {
                                mediaDebugLog('Found alt field by label:', altField);
                                altField.val(data.alt_text);
                                altField.trigger('input').trigger('change');
                            }
                        }
                    }
                });
            }
            
            // Method 4: Log all available fields for manual identification
            mediaDebugLog('=== ALL AVAILABLE FIELDS FOR MANUAL IDENTIFICATION ===');
            
            mediaDebugLog('ALL INPUTS:');
            $('input').each(function(index) {
                const input = $(this);
                mediaDebugLog(`Input ${index}:`, {
                    type: input.attr('type'),
                    name: input.attr('name'),
                    id: input.attr('id'),
                    class: input.attr('class'),
                    placeholder: input.attr('placeholder'),
                    value: input.val(),
                    element: this
                });
            });
            
            mediaDebugLog('ALL TEXTAREAS:');
            $('textarea').each(function(index) {
                const textarea = $(this);
                mediaDebugLog(`Textarea ${index}:`, {
                    name: textarea.attr('name'),
                    id: textarea.attr('id'),
                    class: textarea.attr('class'),
                    placeholder: textarea.attr('placeholder'),
                    value: textarea.val(),
                    element: this
                });
            });
            
            mediaDebugLog('=== END DEBUGGING ===');
            
        }, 500);
        
        // Also try updating fields in Gutenberg media sidebar if available
        updateGutenbergFields(data);
    }
    
    /**
     * Try to update Gutenberg media sidebar fields if they exist
     */
    function updateGutenbergFields(data) {
        // Check if we're in Gutenberg context
        if (typeof wp !== 'undefined' && wp.data && wp.data.select && wp.data.dispatch) {
            try {
                // For Gutenberg editor
                setTimeout(function() {
                    // Try to find and update fields in Gutenberg sidebar
                    const altTextFields = $('.editor-post-featured-image-alt input, .block-editor-media-placeholder input[aria-label="Alternative text"]');
                    if (altTextFields.length) {
                        altTextFields.val(data.alt_text).trigger('input');
                    }
                    
                    const captionFields = $('.wp-caption-text');
                    if (captionFields.length && data.caption) {
                        captionFields.text(data.caption);
                    }
                }, 500);
            } catch (e) {
                console.error('Error updating Gutenberg fields:', e);
            }
        }
    }
    
    /**
     * Trigger form updates to ensure WordPress recognizes the changes
     */
    function triggerFormUpdates() {
        // Simple approach - just trigger change events on the fields
        setTimeout(function() {
            $('input[data-setting], textarea[data-setting]').trigger('change');
        }, 200);
    }
    
    /**
     * Show success notification
     */
    function showSuccessNotification() {
        // Remove any existing notification
        $('.aysa-success-notification').remove();
        
        // Create simple notification
        const notification = $('<div class="aysa-success-notification"></div>');
        notification.html(
            '<div style="position: fixed; top: 32px; right: 20px; z-index: 999999; ' +
            'background: #00a32a; color: white; padding: 10px 15px; border-radius: 3px; ' +
            'font-size: 13px; box-shadow: 0 2px 5px rgba(0,0,0,0.2);">' +
            '✓ Alt text updated successfully!' +
            '</div>'
        );
        
        $('body').append(notification);
        
        // Auto-hide after 3 seconds
        setTimeout(function() {
            notification.fadeOut(300, function() {
                notification.remove();
            });
        }, 3000);
    }
    
    /**
     * Get Language Optimize from metabox
     */
    function getLanguageFromMetabox() {
        const languageField = $('#language_optimize');
        if (languageField.length && languageField.val()) {
            return languageField.val();
        }
        return ''; // Default fallback
    }
    
    /**
     * Get primary keyword from metabox
     */
    function getPrimaryKeywordFromMetabox() {
        const keywordField = $('#aysa-entity-keyword');
        if (keywordField.length && keywordField.val()) {
            return keywordField.val();
        }
        return ''; // Empty if not found
    }
    
    /**
     * Get tone from metabox or settings        it does not exist in metabox
     */
    function getToneFromMetabox() {
        // Try to get from tone settings if available
        const toneField = $('#tone_of_voice, #selected_tone, [name="tone"], [name="selected_tone"]');
        if (toneField.length && toneField.val()) {
            return toneField.val();
        }
        return ''; // Default fallback
    }
    
    /**
     * Get target audience from metabox or settings           it does not exist in metabox
     */
    function getTargetAudienceFromMetabox() {
        // Try to get from audience settings if available
        const audienceField = $('#target_audience, [name="target_audience"]');
        if (audienceField.length && audienceField.val()) {
            return audienceField.val();
        }
        return 'general'; // Default fallback
    }

    /**
     * Add CSS to position AYSA AI section at top of media modal
     */
    function addMediaModalCSS() {
        if ($('#aysa-media-modal-styles').length > 0) {
            return; // Already added
        }
        
        const css = `
            <style id="aysa-media-modal-styles">
                /* Make Generate with Aysa AI button green */
                .aysa-generate-alt-text {
                    background-color: #2ea043 !important;
                    color: white !important;
                    border: 1px solid #2ea043 !important;
                    border-radius: 4px !important;
                    padding: 8px 16px !important;
                    font-weight: 500 !important;
                    transition: all 0.2s ease !important;
                    cursor: pointer !important;
                }
                
                .aysa-generate-alt-text:hover {
                    background-color: #238636 !important;
                    border-color: #238636 !important;
                    color: white !important;
                }
                
                .aysa-generate-alt-text:focus {
                    box-shadow: 0 0 0 2px rgba(46, 160, 67, 0.2) !important;
                    outline: none !important;
                }
                
                /* Style AYSA AI section when moved to top */
                .setting[data-setting="aysa_alt_text_button"].aysa-moved-to-top {
                    background: #f8f9fa !important;
                    border: 1px solid #e1e5e9 !important;
                    border-radius: 6px !important;
                    padding: 15px !important;
                    margin-bottom: 20px !important;
                }
                
                .setting[data-setting="aysa_alt_text_button"].aysa-moved-to-top .name {
                    font-weight: 600 !important;
                    color: #2c3e50 !important;
                    margin-bottom: 10px !important;
                    font-size: 14px !important;
                }
                
                /* Style the description text */
                .media-modal .attachment-details .setting[data-setting="aysa_alt_text_button"] .description {
                    color: #666 !important;
                    font-size: 13px !important;
                    margin: 8px 0 !important;
                    line-height: 1.4 !important;
                }
                
                /* Status container styling */
                .aysa-alt-text-status {
                    margin-top: 10px !important;
                    padding: 8px !important;
                    border-radius: 4px !important;
                    font-size: 13px !important;
                    line-height: 1.4 !important;
                }
                
                /* New upload highlight */
                .aysa-generate-alt-text.aysa-new-upload {
                    background-color: #4caf50 !important;
                    border-color: #4caf50 !important;
                    animation: pulse 2s infinite !important;
                }
                
                .aysa-generate-alt-text.aysa-new-upload:hover {
                    background-color: #45a049 !important;
                    border-color: #45a049 !important;
                }
                
                @keyframes pulse {
                    0% { box-shadow: 0 0 0 0 rgba(76, 175, 80, 0.4); }
                    70% { box-shadow: 0 0 0 10px rgba(76, 175, 80, 0); }
                    100% { box-shadow: 0 0 0 0 rgba(76, 175, 80, 0); }
                }
                
                /* Ensure proper spacing between sections */
                .media-modal .attachment-details .setting[data-setting="aysa_alt_text_button"] + .setting {
                    margin-top: 15px !important;
                }
                
                /* Mobile responsiveness */
                @media (max-width: 782px) {
                    .media-modal .attachment-details .setting[data-setting="aysa_alt_text_button"] {
                        padding: 12px !important;
                        margin-bottom: 15px !important;
                    }
                    
                    .aysa-generate-alt-text {
                        width: 100% !important;
                        text-align: center !important;
                    }
                }
            </style>
        `;
        
        $('head').append(css);
        mediaDebugLog('AYSA Media Modal CSS added');
        
        // Monitor for media modal opening and apply positioning
        setTimeout(function() {
            const observer = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                    if (mutation.addedNodes) {
                        mutation.addedNodes.forEach(function(node) {
                            if (node.nodeType === 1 && (
                                $(node).hasClass('media-modal') || 
                                $(node).find('.media-modal').length ||
                                $(node).hasClass('attachment-details') ||
                                $(node).find('.attachment-details').length
                            )) {
                                mediaDebugLog('Media modal detected, ensuring AYSA positioning');
                                setTimeout(function() {
                                    // Move AYSA section physically to top of attachment details
                                    moveAysaSectionToTop();
                                }, 500);
                            }
                        });
                    }
                });
            });
            
            observer.observe(document.body, {
                childList: true,
                subtree: true
            });
        }, 1000);
    }

    /**
     * Move AYSA AI section physically to top of attachment details
     */
    function moveAysaSectionToTop() {
        mediaDebugLog('Attempting to create AYSA section at top...');
        
        // Check if we already created a top section
        if ($('.aysa-top-section').length > 0) {
            mediaDebugLog('AYSA top section already exists');
            return true;
        }
        
        // Find the AYSA button first
        const aysaButton = $('.aysa-generate-alt-text');
        if (aysaButton.length === 0) {
            mediaDebugLog('AYSA button not found');
            return false;
        }
        
        // Find the sidebar container
        const sidebar = $('.media-modal .media-sidebar, .media-sidebar').first();
        if (sidebar.length === 0) {
            mediaDebugLog('Media sidebar not found');
            return false;
        }
        
        mediaDebugLog('Found sidebar, creating AYSA section at top');
        
        // Get the button's parent section to copy content
        const originalSection = aysaButton.closest('.setting, .compat-item, tr, .form-field');
        
        // Create new section at the top
        const newAysaSection = $(`
            <div class="aysa-top-section" style="
                background: #f8f9fa;
                border: 1px solid #e1e5e9;
                border-radius: 6px;
                padding: 15px;
                margin-bottom: 20px;
                border-bottom: 2px solid #ddd;
            ">
                <div class="name" style="
                    font-weight: 600;
                    color: #2c3e50;
                    margin-bottom: 10px;
                    font-size: 14px;
                ">🎯 AYSA AI Content Generation</div>
                <div class="aysa-content"></div>
            </div>
        `);
        
        // Copy the button and description to the new section
        const buttonClone = aysaButton.clone();
        const description = aysaButton.siblings('p.description, .description').clone();
        const statusDiv = aysaButton.siblings('.aysa-alt-text-status, [id*="aysa-alt-text-status"]').clone();
        
        newAysaSection.find('.aysa-content').append(buttonClone);
        if (description.length) {
            newAysaSection.find('.aysa-content').append(description);
        }
        if (statusDiv.length) {
            newAysaSection.find('.aysa-content').append(statusDiv);
        }
        
        // Insert at the very top of sidebar
        sidebar.prepend(newAysaSection);
        
        // Hide the original section
        if (originalSection.length) {
            originalSection.hide();
        }
        
        mediaDebugLog('AYSA section successfully created at top');
        return true;
    }

    /**
     * Start aggressive monitoring for AYSA section positioning
     */
    function startAysaPositionMonitoring() {
        mediaDebugLog('Starting AYSA position monitoring...');
        
        // Check every 2 seconds for AYSA section that needs repositioning
        const monitoringInterval = setInterval(function() {
            // Only check if media modal is open
            if ($('.media-modal').length > 0) {
                const aysaButton = $('.aysa-generate-alt-text');
                const topSection = $('.aysa-top-section');
                
                if (aysaButton.length > 0 && topSection.length === 0) {
                    mediaDebugLog('Found AYSA button but no top section, creating...');
                    moveAysaSectionToTop();
                } else if (aysaButton.length > 0 && topSection.length > 0) {
                    // Check if top section is actually at the top
                    const sidebar = $('.media-modal .media-sidebar, .media-sidebar').first();
                    if (sidebar.length > 0) {
                        const firstChild = sidebar.children().first();
                        if (!firstChild.hasClass('aysa-top-section')) {
                            mediaDebugLog('AYSA top section not first, moving...');
                            topSection.detach().prependTo(sidebar);
                        }
                    }
                }
            }
        }, 2000);
        
        // Also check immediately when modal content changes
        $(document).on('DOMSubtreeModified', '.media-modal, .attachment-details', function() {
            setTimeout(function() {
                if ($('.aysa-generate-alt-text').length > 0) {
                    mediaDebugLog('Modal content changed, checking AYSA position...');
                    moveAysaSectionToTop();
                }
            }, 300);
        });
        
        // Modern alternative to DOMSubtreeModified
        if (window.MutationObserver) {
            const modalObserver = new MutationObserver(function(mutations) {
                let shouldCheck = false;
                mutations.forEach(function(mutation) {
                    if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
                        for (let node of mutation.addedNodes) {
                            if (node.nodeType === 1) { // Element node
                                if ($(node).find('.aysa-generate-alt-text').length > 0 || 
                                    $(node).hasClass('aysa-generate-alt-text') ||
                                    $(node).find('.attachment-details').length > 0 ||
                                    $(node).hasClass('attachment-details')) {
                                    shouldCheck = true;
                                    break;
                                }
                            }
                        }
                    }
                });
                
                if (shouldCheck) {
                    setTimeout(function() {
                        mediaDebugLog('DOM mutation detected, moving AYSA section...');
                        moveAysaSectionToTop();
                    }, 500);
                }
            });
            
            // Observe the entire document for changes
            modalObserver.observe(document.body, {
                childList: true,
                subtree: true
            });
        }
        
        // Stop monitoring after 5 minutes to prevent memory leaks
        setTimeout(function() {
            clearInterval(monitoringInterval);
            mediaDebugLog('Stopped AYSA position monitoring after 5 minutes');
        }, 300000);
    }

    // Make function globally available for debugging
    window.moveAysaSectionToTop = moveAysaSectionToTop;
    window.startAysaPositionMonitoring = startAysaPositionMonitoring;

})(jQuery); 
