/**
 * Add Feed Source - JavaScript functionality
 * Handles form interactions, validation, and AJAX submissions
 */

(function($) {
    'use strict';

    $(document).ready(function() {
        // Content filter options
        const contentFilter = $('#content-filter');
        const keywordFilter = $('#keywordFilter');
        const lengthFilter = $('#lengthFilter');

        contentFilter.on('change', function() {
            keywordFilter.hide();
            lengthFilter.hide();
            
            if (this.value === 'keyword' || this.value === 'both') {
                keywordFilter.show();
            }
            if (this.value === 'length' || this.value === 'both') {
                lengthFilter.show();
            }
        });

        // Attribution format
        const attributionFormat = $('#attribution-format');
        const customAttribution = $('#customAttribution');

        attributionFormat.on('change', function() {
            if (this.value === 'custom') {
                customAttribution.show();
            } else {
                customAttribution.hide();
            }
        });

        // Author handling
        const authorHandling = $('#author-handling');
        const specificAuthor = $('#specificAuthor');

        authorHandling.on('change', function() {
            if (this.value === 'specific') {
                specificAuthor.show();
            } else {
                specificAuthor.hide();
            }
        });

        // Form submission
        $('#feedSourceForm').on('submit', function(e) {
            e.preventDefault();
            
            // Check if we're in edit mode
            const isEditMode = $('input[name="feed_id"]').length > 0;
            
            // Show loading state
            const submitBtn = $(this).find('button[type="submit"]');
            const originalText = submitBtn.text();
            submitBtn.text(isEditMode ? 'Updating Feed...' : 'Adding Feed...').prop('disabled', true);
            
            // Collect form data
            const formData = new FormData(this);
            formData.append('action', isEditMode ? 'blogibot_update_feed_source' : 'blogibot_add_feed_source');
            formData.append('nonce', blogibotFeed.nonce);
            
            // Make AJAX request
            $.ajax({
                url: blogibotFeed.ajax_url,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    submitBtn.text(originalText).prop('disabled', false);
                    
                    if (response.success) {
                        Blog82AI_Modal.showSuccess(
                            isEditMode ? 'Feed Updated' : 'Feed Added',
                            response.data.message || (isEditMode ? 'Feed source updated successfully!' : 'Feed source added successfully!'),
                            false
                        );
                        setTimeout(function() {
                            window.location.href = blogibotFeed.manage_feeds_url;
                        }, 1500);
                    } else {
                        Blog82AI_Modal.showError(
                            'Error',
                            response.data.message || (isEditMode ? 'Failed to update feed source.' : 'Failed to add feed source.')
                        );
                    }
                },
                error: function(xhr, status, error) {
                    submitBtn.text(originalText).prop('disabled', false);
                    Blog82AI_Modal.showError('Connection Error', error || 'An error occurred while saving the feed.');
                }
            });
        });

        // Populate form in edit mode
        if (typeof blogibotFeedData !== 'undefined' && blogibotFeedData.edit_mode) {
            const feedData = blogibotFeedData.feed_data;
            
            // Category
            if (feedData.category) {
                $('#feed-category').val(feedData.category);
            }
            
            // Import settings
            if (feedData.import_frequency) {
                $('#import-frequency').val(feedData.import_frequency);
            }
            
            if (feedData.import_type) {
                $('#import-type').val(feedData.import_type);
            }
            
            if (feedData.max_posts) {
                $('#max-posts').val(feedData.max_posts);
            }
            
            // Checkboxes
            $('input[name="auto_fetch"]').prop('checked', feedData.auto_fetch == 1);
            $('input[name="fetch_full_content"]').prop('checked', feedData.fetch_full_content == 1);
            $('input[name="auto_featured_image"]').prop('checked', feedData.auto_featured_image == 1);
            
            // Fallback image
            if (feedData.fallback_image) {
                $('#fallback-image').val(feedData.fallback_image);
            }
            
            // Content filter
            if (feedData.content_filter) {
                $('#content-filter').val(feedData.content_filter).trigger('change');
            }
            
            // Update submit button text
            $('button[type="submit"]').text('Update Feed Source');
        }
    });

    // Feed validation function
    window.validateFeed = function() {
        const feedUrl = $('#feed-url').val();
        const resultDiv = $('#feed-validation-result');
        
        if (!feedUrl) {
            Blog82AI_Modal.showError('Missing URL', 'Please enter a feed URL first.');
            return;
        }
        
        // Show loading
        resultDiv.show().html('<div class="blog82ai-validation-loading">🔄 Validating feed...</div>');
        
        // Make AJAX request to validate feed
        $.ajax({
            url: blogibotFeed.ajax_url,
            type: 'POST',
            data: {
                action: 'blogibot_validate_feed',
                nonce: blogibotFeed.nonce,
                feed_url: feedUrl
            },
            success: function(response) {
                if (response.success && response.data.valid) {
                    const data = response.data;
                    let html = `
                        <div class="blog82ai-validation-success">
                            ✅ Valid ${data.feed_type.toUpperCase()} feed found!
                            <div class="blog82ai-feed-info">
                                <strong>Title:</strong> ${data.title}<br>
                                <strong>Description:</strong> ${data.description || 'No description'}<br>
                                <strong>Last Updated:</strong> ${data.last_updated}<br>
                                <strong>Posts Found:</strong> ${data.posts_count}
                            </div>
                        </div>
                    `;
                    
                    // Auto-fill feed name if empty
                    const feedNameInput = $('#feed-name');
                    if (!feedNameInput.val()) {
                        feedNameInput.val(data.title);
                    }
                    
                    // Show feed preview if posts are available
                    if (data.preview_posts && data.preview_posts.length > 0) {
                        html += '<div class="blog82ai-feed-preview"><h4>Feed Preview:</h4>';
                        data.preview_posts.forEach(function(post) {
                            html += `
                                <div class="blog82ai-preview-post">
                                    <h5><a href="${post.link}" target="_blank">${post.title}</a></h5>
                                    <p class="post-date">${post.date}</p>
                                    <p>${post.excerpt}</p>
                                </div>
                            `;
                        });
                        html += '</div>';
                    }
                    
                    resultDiv.html(html);
                } else {
                    resultDiv.html(`
                        <div class="blog82ai-validation-error">
                            ❌ ${response.data.message || 'Failed to validate feed.'}
                        </div>
                    `);
                }
            },
            error: function(xhr, status, error) {
                resultDiv.html(`
                    <div class="blog82ai-validation-error">
                        ❌ Error validating feed: ${error}
                    </div>
                `);
            }
        });
    };

    // Test feed function
    window.testFeed = function() {
        const feedUrl = $('#feed-url').val();
        
        if (!feedUrl) {
            Blog82AI_Modal.showError('Missing URL', 'Please enter a feed URL first.');
            return;
        }
        
        // Show preview
        const previewDiv = $('#feedPreview');
        previewDiv.show().find('.blog82ai-preview-content').html('<div class="blog82ai-loading">🔄 Loading feed preview...</div>');
        
        // Call validate_feed AJAX to get real data
        $.ajax({
            url: blogibotFeed.ajax_url,
            type: 'POST',
            data: {
                action: 'blogibot_validate_feed',
                nonce: blogibotFeed.nonce,
                feed_url: feedUrl
            },
            success: function(response) {
                if (response.success) {
                    const feed = response.data;
                    let postsHtml = '';
                    
                    feed.preview_posts.forEach(function(post) {
                        postsHtml += `
                            <div class="blog82ai-preview-post">
                                <h5>${post.title}</h5>
                                <p>Published ${post.date}</p>
                                <p>Excerpt: ${post.excerpt}</p>
                                <a href="${post.link}" target="_blank">View Original →</a>
                            </div>
                        `;
                    });
                    
                    previewDiv.find('.blog82ai-preview-content').html(`
                        <div class="blog82ai-preview-info">
                            <p><strong>Feed Title:</strong> ${feed.title}</p>
                            <p><strong>Total Posts Found:</strong> ${feed.posts_count}</p>
                            <p><strong>Last Updated:</strong> ${feed.last_updated}</p>
                        </div>
                        <div class="blog82ai-preview-posts">
                            <h4>Latest Posts from Feed:</h4>
                            ${postsHtml}
                        </div>
                    `);
                    
                    // Scroll to preview
                    previewDiv[0].scrollIntoView({ behavior: 'smooth' });
                } else {
                    previewDiv.find('.blog82ai-preview-content').html(`
                        <div class="blog82ai-validation-error">
                            ❌ Error: ${response.data.message}
                        </div>
                    `);
                }
            },
            error: function(xhr, status, error) {
                previewDiv.find('.blog82ai-preview-content').html(`
                    <div class="blog82ai-validation-error">
                        ❌ Error testing feed: ${error}
                    </div>
                `);
            }
        });
    };

})(jQuery);
