(function($) {
    'use strict';

    // Function to add button to attachment details
    function addGenerateButton() {
        
        // Try multiple selectors to find alt text field - updated for actual WordPress structure
        var $altField = null;
        var selectors = [
            '#attachment-details-two-column-alt-text',
            '.setting.alt-text textarea',
            '.setting.alt-text input',
            '.setting[data-setting="alt"] textarea',
            '.setting[data-setting="alt"] input',
            '.attachment-details .setting.alt-text textarea',
            '.attachment-details .setting.alt-text input',
            '.media-frame .setting.alt-text textarea',
            '.media-frame .setting.alt-text input',
            'textarea[id*="alt-text"]',
            'input[id*="alt-text"]'
        ];
        
        // Try each selector
        for (var i = 0; i < selectors.length; i++) {
            $altField = $(selectors[i]);
            if ($altField.length > 0) {
                break;
            }
        }
        
        // If still not found, try finding by label text
        if (!$altField || $altField.length === 0) {
            $('label').each(function() {
                var labelText = $(this).text().toLowerCase();
                if (labelText.indexOf('alternative text') !== -1 || labelText.indexOf('alt text') !== -1) {
                    var labelFor = $(this).attr('for');
                    if (labelFor) {
                        $altField = $('#' + labelFor);
                        if ($altField.length > 0) {
                            return false; // break
                        }
                    }
                    // Try finding in parent setting
                    var $setting = $(this).closest('.setting');
                    if ($setting.length) {
                        $altField = $setting.find('input, textarea');
                        if ($altField.length > 0) {
                            return false; // break
                        }
                    }
                }
            });
        }
        
        if (!$altField || $altField.length === 0) {
            return;
        }
        
        $altField.each(function() {
            var $field = $(this);
            var $setting = $field.closest('.setting');
            
            // If no .setting parent, try parent div
            if ($setting.length === 0) {
                $setting = $field.parent();
            }
            
            // Get attachment ID first to check for existing button
            var attachmentId = null;
            
            // Try to get from form fields (attachments[3596][field])
            $('input[name*="attachments["], textarea[name*="attachments["], select[name*="attachments["]').each(function() {
                var name = $(this).attr('name');
                if (name) {
                    var match = name.match(/attachments\[(\d+)\]/);
                    if (match) {
                        attachmentId = match[1];
                        return false; // break
                    }
                }
            });
            
            // Try to get from data attribute
            if (!attachmentId && $field.attr('name')) {
                var match = $field.attr('name').match(/attachments\[(\d+)\]/);
                if (match) {
                    attachmentId = match[1];
                }
            }
            
            // Try to get from wp.media
            if (!attachmentId && typeof wp !== 'undefined' && wp.media) {
                // Try active frame
                if (wp.media.frame && wp.media.frame.state) {
                    var state = wp.media.frame.state();
                    if (state && state.get('selection') && state.get('selection').first()) {
                        attachmentId = state.get('selection').first().id;
                    }
                }
                // Try attachment details controller
                if (!attachmentId && wp.media.controller && wp.media.controller.AttachmentDetails) {
                    var controller = wp.media.frame && wp.media.frame.state() && wp.media.frame.state().controller;
                    if (controller && controller.model) {
                        attachmentId = controller.model.id;
                    }
                }
            }
            
            // Try to get from URL or page
            if (!attachmentId) {
                var urlMatch = window.location.href.match(/[?&]item=(\d+)/);
                if (urlMatch) {
                    attachmentId = urlMatch[1];
                }
            }
            
            if (!attachmentId) {
                return;
            }
            
            // Simple check: if button already exists for this attachment ID, skip
            var $settingSpan = $setting.closest('span.setting');
            if ($settingSpan.length > 0) {
                // Check if button paragraph already exists right after this setting span
                var $nextElement = $settingSpan.next();
                if ($nextElement.hasClass('gistmag-atg-button-paragraph')) {
                    var $existingButton = $nextElement.find('.gistmag-atg-generate-btn[data-attachment-id="' + attachmentId + '"]');
                    if ($existingButton.length > 0) {
                        return; // Button already exists, skip
                    }
                }
            }
            
            
            // Get image URL
            var imageUrl = '';
            if (typeof wp !== 'undefined' && wp.media && wp.media.attachment) {
                var attachment = wp.media.attachment(attachmentId);
                if (attachment && attachment.get('url')) {
                    imageUrl = attachment.get('url');
                }
            }
            
            // Create button HTML - use span instead of div for valid HTML inside paragraph
            var buttonHtml = '<span class="gistmag-atg-button-wrapper" style="display: inline-flex; align-items: center; gap: 8px;">' +
                '<button type="button" class="button button-small gistmag-atg-generate-btn" ' +
                'data-attachment-id="' + attachmentId + '" ' +
                'data-image-url="' + imageUrl + '">' +
                '<span class="dashicons dashicons-update" style="vertical-align: middle; font-size: 16px; width: 16px; height: 16px; line-height: 1;"></span> ' +
                'Generate Alt Text' +
                '</button> ' +
                '<select class="gistmag-atg-mode" id="gistmag-atg-mode-' + attachmentId + '" style="height: 28px; padding: 0 8px;">' +
                '<option value="short">Short</option>' +
                '<option value="long">Long</option>' +
                '<option value="seo">SEO</option>' +
                '</select> ' +
                '<span class="gistmag-atg-status" id="gistmag-atg-status-' + attachmentId + '" style="font-size: 12px; display: none;"></span>' +
                '</span>';
            
            // Insert button in a new paragraph outside the setting span, like Rank Math
            // Find the parent setting span
            var $settingSpan = $setting.closest('span.setting');
            
            if ($settingSpan.length > 0) {
                // Create a new paragraph element for the button
                var $buttonParagraph = $('<p class="gistmag-atg-button-paragraph"></p>').html(buttonHtml);
                
                // Insert the paragraph after the setting span
                $settingSpan.after($buttonParagraph);
            } else {
                // Fallback: add after the field if we can't find the setting span
                $field.after(buttonHtml);
            }
        });
    }


    $(document).ready(function() {
        // Add button on page load
        setTimeout(addGenerateButton, 500);
        setTimeout(addGenerateButton, 1500);
        setTimeout(addGenerateButton, 3000);
        
        // Add button when media modal opens or updates
        if (typeof wp !== 'undefined' && wp.media) {
            // Hook into wp.media events
            $(document).on('DOMContentLoaded', function() {
                // Wait for wp.media to be ready
                if (wp.media && wp.media.controller) {
                    // Override the AttachmentDetails controller to inject button
                    var originalRender = wp.media.controller.AttachmentDetails.prototype.render;
                    wp.media.controller.AttachmentDetails.prototype.render = function() {
                        var result = originalRender.apply(this, arguments);
                        setTimeout(addGenerateButton, 300);
                        return result;
                    };
                }
            });
            
            // Listen for when media modal is opened
            $(document).on('click', '.add_media, .insert-media, [data-action="add-media"]', function() {
                setTimeout(addGenerateButton, 1000);
            });
            
            // Listen for attachment selection in media library
            $(document).on('click', '.attachment, .attachment-preview, .wp-core-ui .attachment', function() {
                setTimeout(addGenerateButton, 500);
            });
            
            // Listen for when attachment details view is shown
            $(document).on('DOMNodeInserted', '.attachment-details, .media-frame .attachment-details', function() {
                setTimeout(addGenerateButton, 300);
            });
            
            // Use MutationObserver for better DOM watching
            if (typeof MutationObserver !== 'undefined') {
                var observer = new MutationObserver(function(mutations) {
                    var shouldCheck = false;
                    mutations.forEach(function(mutation) {
                        if (mutation.addedNodes.length) {
                            $(mutation.addedNodes).each(function() {
                                if ($(this).hasClass('attachment-details') || 
                                    $(this).find('.attachment-details').length ||
                                    $(this).hasClass('setting') ||
                                    $(this).find('.setting').length) {
                                    shouldCheck = true;
                                }
                            });
                        }
                    });
                    if (shouldCheck) {
                        setTimeout(addGenerateButton, 200);
                    }
                });
                
                observer.observe(document.body, {
                    childList: true,
                    subtree: true
                });
            }
        }
        
        // Also try on window load
        $(window).on('load', function() {
            setTimeout(addGenerateButton, 1000);
        });
        
        // Generate alt text for single attachment
        $(document).on('click', '.gistmag-atg-generate-btn', function(e) {
            e.preventDefault();
            
            var $button = $(this);
            var attachmentId = $button.data('attachment-id');
            var imageUrl = $button.data('image-url');
            var mode = $('#gistmag-atg-mode-' + attachmentId).val() || $button.siblings('.gistmag-atg-mode').val() || 'short';
            var originalHtml = $button.html();
            var $status = $('#gistmag-atg-status-' + attachmentId);
            
            $button.prop('disabled', true).html('<span class="dashicons dashicons-update" style="vertical-align: middle; font-size: 16px; width: 16px; height: 16px; line-height: 1;"></span> Generating...');
            $status.hide();
            
            $.ajax({
                url: gistmag_atg.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'gistmag_atg_generate',
                    nonce: gistmag_atg.nonce,
                    attachment_id: attachmentId,
                    image_url: imageUrl,
                    mode: mode
                },
                success: function(response) {
                    if (response.success && response.data.alt_text) {
                        var altText = response.data.alt_text;
                        
                        // Update the alt text field - try multiple selectors
                        var $altField = $('input[name="attachments[' + attachmentId + '][alt]"], textarea[name="attachments[' + attachmentId + '][alt]"], .attachment-details .setting.alt-text input, .attachment-details .setting.alt-text textarea');
                        
                        if ($altField.length) {
                            $altField.val(altText).trigger('change').trigger('input');
                        }
                        
                        // Update via WordPress media modal
                        if (typeof wp !== 'undefined' && wp.media && wp.media.model) {
                            var attachment = wp.media.attachment(attachmentId);
                            if (attachment) {
                                attachment.set('alt', altText);
                                // Try to save the attachment if wp.ajax is available
                                if (typeof wp !== 'undefined' && wp.ajax) {
                                    var saveData = {
                                        action: 'save-attachment',
                                        id: attachmentId,
                                        changes: {
                                            alt: altText
                                        }
                                    };
                                    
                                    // Try to get nonce from wp.media if available
                                    if (wp.media.model && wp.media.model.settings && wp.media.model.settings.nonce && wp.media.model.settings.nonce.save) {
                                        saveData.nonce = wp.media.model.settings.nonce.save;
                                        wp.ajax.post('save-attachment', saveData);
                                    }
                                }
                            }
                        }
                        
                        // Show success message
                        $status.html('<span style="color: #00a32a; font-weight: 500;">✓ Generated!</span>').show();
                        
                        // Reload after a moment if on media library page
                        setTimeout(function() {
                            if (window.location.href.indexOf('upload.php') > -1) {
                                // Don't reload, just update
                            }
                        }, 1500);
                    } else {
                        $status.html('<span style="color: #d63638; font-weight: 500;">✗ Failed</span>').show();
                        alert('Failed to generate alt text: ' + (response.data.message || 'Unknown error'));
                    }
                },
                error: function() {
                    $status.html('<span style="color: #d63638; font-weight: 500;">✗ Error</span>').show();
                    alert('Error generating alt text. Please try again.');
                },
                complete: function() {
                    $button.prop('disabled', false).html(originalHtml);
                }
            });
        });
        
        // Add bulk action button to media toolbar (like Rank Math)
        function addBulkActionButton() {
            var $toolbar = $('.media-toolbar-secondary');
            if ($toolbar.length === 0) {
                return;
            }
            
            // Check if button already exists
            if ($toolbar.find('.gistmag-bulk-generate-button').length > 0) {
                return;
            }
            
            // Create button similar to Rank Math's
            var $button = $('<button>', {
                class: 'button media-button button-primary button-large gistmag-bulk-generate-button',
                html: '<span class="dashicons dashicons-update" style="vertical-align: middle; margin-right: 5px;"></span> Generate Alt Text (GistMag)',
                type: 'button'
            });
            
            // Insert before the "Delete permanently" button or after Rank Math button
            var $rankMathBtn = $toolbar.find('.rank-math-bulk-generate-button');
            if ($rankMathBtn.length > 0) {
                $rankMathBtn.after($button);
            } else {
                var $deleteBtn = $toolbar.find('.delete-selected-button').first();
                if ($deleteBtn.length > 0) {
                    $deleteBtn.before($button);
                } else {
                    $toolbar.prepend($button);
                }
            }
        }
        
        // Add bulk action button on page load
        setTimeout(addBulkActionButton, 500);
        setTimeout(addBulkActionButton, 1500);
        
        // Watch for toolbar changes
        if (typeof MutationObserver !== 'undefined') {
            var toolbarObserver = new MutationObserver(function(mutations) {
                var shouldAdd = false;
                mutations.forEach(function(mutation) {
                    if (mutation.addedNodes.length) {
                        $(mutation.addedNodes).each(function() {
                            if ($(this).hasClass('media-toolbar-secondary') || 
                                $(this).find('.media-toolbar-secondary').length) {
                                shouldAdd = true;
                            }
                        });
                    }
                });
                if (shouldAdd) {
                    setTimeout(addBulkActionButton, 200);
                }
            });
            
            if ($('.media-toolbar-secondary').length > 0) {
                toolbarObserver.observe(document.body, {
                    childList: true,
                    subtree: true
                });
            }
        }
        
        // Handle bulk action button click
        $(document).on('click', '.gistmag-bulk-generate-button', function(e) {
            e.preventDefault();
            
            // Get selected attachments
            var $selected = $('.attachment.selected, input[name="media[]"]:checked');
            var attachmentIds = [];
            
            // Try to get from selected attachments
            $selected.each(function() {
                var id = $(this).data('id') || $(this).val() || $(this).closest('.attachment').data('id');
                if (id) {
                    attachmentIds.push(id);
                }
            });
            
            // Try to get from checkboxes
            if (attachmentIds.length === 0) {
                $('input[name="media[]"]:checked').each(function() {
                    attachmentIds.push($(this).val());
                });
            }
            
            if (attachmentIds.length === 0) {
                alert('Please select at least one image.');
                return;
            }
            
            // Show mode selector
            var mode = prompt('Select mode (short/long/seo):', 'short') || 'short';
            
            if (!['short', 'long', 'seo'].includes(mode)) {
                alert('Invalid mode. Please use short, long, or seo.');
                return;
            }
            
            bulkGenerateAltText(attachmentIds, mode);
        });
        
        // Also add to bulk actions dropdown (for list view)
        if ($('#bulk-action-selector-top').length) {
            var bulkActionHtml = '<option value="gistmag_atg_generate">Generate Alt Text (GistMag)</option>';
            $('#bulk-action-selector-top, #bulk-action-selector-bottom').append(bulkActionHtml);
            
            $('.bulk-actions').on('submit', function(e) {
                var action = $(this).find('select[name="action"]').val();
                if (action === 'gistmag_atg_generate') {
                    e.preventDefault();
                    var checked = $('input[name="media[]"]:checked');
                    if (checked.length === 0) {
                        alert('Please select at least one image.');
                        return;
                    }
                    
                    var attachmentIds = checked.map(function() {
                        return $(this).val();
                    }).get();
                    
                    var mode = prompt('Select mode (short/long/seo):', 'short') || 'short';
                    
                    if (!['short', 'long', 'seo'].includes(mode)) {
                        alert('Invalid mode. Please use short, long, or seo.');
                        return;
                    }
                    
                    bulkGenerateAltText(attachmentIds, mode);
                }
            });
        }
    });
    
    function bulkGenerateAltText(attachmentIds, mode) {
        var $progress = $('<div class="gistmag-atg-progress"><p>Generating alt text for ' + attachmentIds.length + ' images...</p><div class="progress-bar"><div class="progress-fill"></div></div></div>');
        $('body').append($progress);
        
        $.ajax({
            url: gistmag_atg.ajaxUrl,
            type: 'POST',
            data: {
                action: 'gistmag_atg_bulk_generate',
                nonce: gistmag_atg.nonce,
                attachment_ids: attachmentIds,
                mode: mode
            },
            success: function(response) {
                if (response.success) {
                    var results = response.data.results;
                    var successful = results.filter(function(r) { return r.success; }).length;
                    var failed = results.length - successful;
                    
                    $progress.html(
                        '<div class="notice notice-success">' +
                        '<p>Completed! ' + successful + ' successful, ' + failed + ' failed.</p>' +
                        '</div>'
                    );
                    
                    setTimeout(function() {
                        location.reload();
                    }, 2000);
                } else {
                    $progress.html(
                        '<div class="notice notice-error">' +
                        '<p>Error: ' + (response.data.message || 'Unknown error') + '</p>' +
                        '</div>'
                    );
                }
            },
            error: function() {
                $progress.html(
                    '<div class="notice notice-error">' +
                    '<p>Error generating alt text. Please try again.</p>' +
                    '</div>'
                );
            }
        });
    }
    
})(jQuery);
