/**
 * Easy AI Blog Generator - SEO Enhancement Tools
 *
 * JavaScript functionality for:
 * - Keyword density analysis
 * - Applying SEO suggestions
 * - Generating keyword suggestions
 */

(function($) {
    'use strict';

    // Initialize the SEO tools when the document is ready
    $(document).ready(function() {
        console.log('Document ready, initializing SEO tools...');
        
        // Initialize the main metabox analyzer
        initMainMetaboxAnalyzer();
        
        // Keyword Suggestions
        initKeywordSuggestions();
    });

    /**
     * Initialize the main metabox keyword analyzer
     */
    function initMainMetaboxAnalyzer() {
        const $analyzeButton = $('#easyaibloggen-analyze-keyword');
        const $resultsContainer = $('#easyaibloggen-main-analysis-results');
        const $resultsContent = $('.easyaibloggen-main-results-content');
        const $suggestionContent = $('.easyaibloggen-main-suggestions');
        const $applyButton = $('#easyaibloggen-main-apply-suggestions');
        
        console.log('Initializing main metabox analyzer...');
        console.log('Analyze button found:', $analyzeButton.length > 0);
        console.log('Button HTML:', $analyzeButton.length > 0 ? $analyzeButton.prop('outerHTML') : 'Not found');
        console.log('Results container found:', $resultsContainer.length > 0);
        console.log('Results content found:', $resultsContent.length > 0);
        console.log('Suggestion content found:', $suggestionContent.length > 0);
        console.log('Apply button found:', $applyButton.length > 0);
        
        // Only proceed if the analyze button exists
        if (!$analyzeButton.length) {
            console.error('Analyze button not found, exiting initialization');
            return;
        }
        
        // Handle the analyze button click
        $analyzeButton.on('click', function(e) {
            e.preventDefault();
            console.log('Analyze button clicked');
            
            // Show that analysis is in progress
            $analyzeButton.prop('disabled', true);
            
            // Get the post ID
            const postId = $(this).data('postid') || $('#post_ID').val();
            console.log('Post ID:', postId);
            
            // Check if easyAiSeoData is available
            if (typeof easyAiSeoData === 'undefined') {
                console.error('easyAiSeoData is not defined! Script was not properly localized.');
                alert('Error: Script data is missing. Please reload the page and try again.');
                $analyzeButton.prop('disabled', false);
                return;
            }
            
            console.log('AJAX URL:', easyAiSeoData.ajaxUrl);
            console.log('Nonce:', easyAiSeoData.nonce);
            
            // Make the AJAX request to analyze density using the stored preferred keyword
            console.log('Making AJAX request...');
            $.ajax({
                url: easyAiSeoData.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'easyaibloggen_analyze_keyword_density',
                    nonce: easyAiSeoData.nonce,
                    postId: postId,
                    auto_get_keyword: true
                },
                success: function(response) {
                    console.log('AJAX request successful:', response);
                    
                    // First check if the response is properly formatted
                    if (typeof response !== 'object') {
                        console.error('Invalid response format:', response);
                        handleError('Server returned an invalid response format. Please try again.');
                        return;
                    }
                    
                    if (response.success) {
                        console.log('Response data:', response.data);
                        
                        // Display the instructions and analysis HTML
                        if (response.data && response.data.instructions) {
                            $resultsContent.html(response.data.instructions);
                        } else {
                            console.warn('No instructions in response data');
                            $resultsContent.html('<div class="notice notice-warning"><p>Analysis completed, but no detailed instructions were returned.</p></div>');
                        }
                        
                        if (response.data && response.data.analysisHtml) {
                            $suggestionContent.html(response.data.analysisHtml);
                        } else {
                            console.warn('No analysis HTML in response data');
                            $suggestionContent.html('<div class="notice notice-warning"><p>No detailed analysis content was returned.</p></div>');
                        }
                        
                        // Show the containers
                        $resultsContainer.show();
                        
                        // Enable apply suggestions button
                        if (response.data && response.data.canApplySuggestions) {
                            $applyButton.show().on('click', function() {
                                applySuggestions(postId);
                            });
                        } else {
                            $applyButton.hide();
                        }
                    } else {
                        console.error('Error in response:', response.data);
                        handleError(response.data);
                    }
                    $analyzeButton.prop('disabled', false);
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.error('AJAX request failed:', textStatus, errorThrown);
                    handleError(easyAiSeoData.errorMessage);
                },
                complete: function() {
                    $analyzeButton.prop('disabled', false);
                }
            });
        });
        
        /**
         * Apply suggestions to the post content
         */
        function applySuggestions(postId) {
            const $applyButton = $('#easyaibloggen-main-apply-suggestions');
            $applyButton.prop('disabled', true).text(easyAiSeoData.applyingSuggestions || 'Applying...');
            
            $.ajax({
                url: easyAiSeoData.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'easyaibloggen_apply_seo_suggestions',
                    nonce: easyAiSeoData.nonce,
                    postId: postId
                },
                success: function(response) {
                    console.log('Apply suggestions response:', response);
                    if (response.success) {
                        alert(response.data.message || 'Suggestions applied successfully.');
                        if (response.data.instructions) {
                            $resultsContent.html(response.data.instructions);
                        }
                    } else {
                        handleError(response.data);
                    }
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.error('Apply suggestions failed:', textStatus, errorThrown);
                    handleError(easyAiSeoData.errorMessage);
                },
                complete: function() {
                    $applyButton.prop('disabled', false).text('Apply Suggestions');
                }
            });
        }
        
        /**
         * Handle errors
         */
        function handleError(errorMessage) {
            console.error('Error analyzing keyword density:', errorMessage);
            const error = typeof errorMessage === 'string' ? errorMessage : 'An unknown error occurred. Please try again.';
            $resultsContent.html('<div class="notice notice-error"><p>' + error + '</p></div>');
            $suggestionContent.empty(); // Clear any previous content
            $resultsContainer.show();
            $applyButton.hide(); // Hide the apply button
        }
    }

    /**
     * Initialize the keyword suggestions feature
     */
    function initKeywordSuggestions() {
        const $generateButton = $('#easyaibloggen-generate-keywords');
        const $loader = $('#easyaibloggen-keywords-loader');
        const $container = $('#easyaibloggen-keywords-container');
        const $textarea = $('#easyaibloggen_suggested_keywords');
        
        // Only proceed if the generate button exists
        if (!$generateButton.length) {
            return;
        }
        
        // Handle the generate button click
        $generateButton.on('click', function() {
            // Show the loader
            $loader.show();
            $generateButton.prop('disabled', true);
            
            // Make the AJAX request
            $.ajax({
                url: easyAiSeoData.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'easyaibloggen_generate_keywords',
                    nonce: easyAiSeoData.nonce
                },
                success: function(response) {
                    if (response.success) {
                        // Update the textarea with the keywords
                        $textarea.val(response.data.keywords);
                        $container.show();
                    } else {
                        handleError(response.data);
                    }
                },
                error: function() {
                    handleError(easyAiSeoData.errorMessage);
                },
                complete: function() {
                    $loader.hide();
                    $generateButton.prop('disabled', false);
                }
            });
        });
        
        /**
         * Handle an error
         *
         * @param {string} errorMessage The error message
         */
        function handleError(errorMessage) {
            if (typeof errorMessage === 'object' && errorMessage.message) {
                console.log('Debug Info:', errorMessage.debug);
                alert(errorMessage.message);
            } else {
                alert(errorMessage || easyAiSeoData.errorMessage);
            }
        }
    }

})(jQuery); 