// Localize blogibotFeed for AJAX requests
// Note: blogibotFeed object is defined via wp_localize_script in Blogibot.php

document.addEventListener('DOMContentLoaded', function () {
    // Content filter options
    const contentFilter = document.getElementById('content-filter');
    const keywordFilter = document.getElementById('keywordFilter');
    const lengthFilter = document.getElementById('lengthFilter');

    if (contentFilter) {
        contentFilter.addEventListener('change', function () {
            if (keywordFilter) keywordFilter.style.display = 'none';
            if (lengthFilter) lengthFilter.style.display = 'none';

            if (this.value === 'keyword' || this.value === 'both') {
                if (keywordFilter) keywordFilter.style.display = 'block';
            }
            if (this.value === 'length' || this.value === 'both') {
                if (lengthFilter) lengthFilter.style.display = 'block';
            }
        });
    }

    // Attribution format
    const attributionFormat = document.getElementById('attribution-format');
    const customAttribution = document.getElementById('customAttribution');

    if (attributionFormat) {
        attributionFormat.addEventListener('change', function () {
            if (customAttribution) {
                if (this.value === 'custom') {
                    customAttribution.style.display = 'block';
                } else {
                    customAttribution.style.display = 'none';
                }
            }
        });
    }

    // Author handling
    const authorHandling = document.getElementById('author-handling');
    const specificAuthor = document.getElementById('specificAuthor');

    if (authorHandling) {
        authorHandling.addEventListener('change', function () {
            if (specificAuthor) {
                if (this.value === 'specific') {
                    specificAuthor.style.display = 'block';
                } else {
                    specificAuthor.style.display = 'none';
                }
            }
        });
    }

    // Form submission
    const feedSourceForm = document.getElementById('feedSourceForm');
    if (feedSourceForm) {
        feedSourceForm.addEventListener('submit', function (e) {
            e.preventDefault();
            console.log('Form submitted');

            // Check if we're in edit mode
            const isEditMode = document.querySelector('input[name="feed_id"]') !== null;

            // Show loading state
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.textContent;
            submitBtn.textContent = isEditMode ? 'Updating Feed...' : 'Adding Feed...';
            submitBtn.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);

            console.log('Sending AJAX request', Object.fromEntries(formData));

            // Make AJAX request
            jQuery.ajax({
                url: blogibotFeed.ajax_url,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function (response) {
                    console.log('AJAX success', response);
                    submitBtn.textContent = originalText;
                    submitBtn.disabled = false;

                    if (response.success) {
                        Blog82AI_Modal.showSuccess(
                            'Success',
                            response.data.message || (isEditMode ? 'Feed source updated successfully!' : 'Feed source added successfully!'),
                            false  // Don't auto-close, we want to redirect on manual close
                        );
                        // Redirect after a short delay
                        setTimeout(function () {
                            window.location.href = blogibotFeed.manage_feeds_url;
                        }, 2000);
                    } else {
                        console.log('Showing error modal', response.data);
                        // Handle case where response.data might be a string (though usually it's an object)
                        let errorMsg = 'Unknown error';
                        if (response.data && response.data.message) {
                            errorMsg = response.data.message;
                        } else if (typeof response.data === 'string') {
                            errorMsg = response.data;
                        }

                        Blog82AI_Modal.showError(
                            'Error',
                            errorMsg || (isEditMode ? 'Failed to update feed source.' : 'Failed to add feed source.')
                        );
                    }
                },
                error: function (xhr, status, error) {
                    console.error('AJAX error', status, error, xhr.responseText);
                    submitBtn.textContent = originalText;
                    submitBtn.disabled = false;
                    Blog82AI_Modal.showError(
                        'System Error',
                        'An unexpected error occurred: ' + error
                    );
                }
            });
        });
    }

    // Populate form in edit mode
    if (typeof blogibotFeed.feed_data !== 'undefined' && blogibotFeed.feed_data) {
        const feedData = blogibotFeed.feed_data;

        // Category
        const categorySelect = document.getElementById('feed-category');
        if (categorySelect && feedData.category) {
            categorySelect.value = feedData.category;
        }

        // Import settings
        const frequencySelect = document.getElementById('import-frequency');
        if (frequencySelect && feedData.import_frequency) {
            frequencySelect.value = feedData.import_frequency;
        }

        const importTypeSelect = document.getElementById('import-type');
        if (importTypeSelect && feedData.import_type) {
            importTypeSelect.value = feedData.import_type;
        }

        const maxPostsInput = document.getElementById('max-posts');
        if (maxPostsInput && feedData.max_posts) {
            maxPostsInput.value = feedData.max_posts;
        }

        // Checkboxes
        const autoFetchCheckbox = document.querySelector('input[name="auto_fetch"]');
        if (autoFetchCheckbox) {
            autoFetchCheckbox.checked = feedData.auto_fetch == 1;
        }

        const fetchFullContentCheckbox = document.querySelector('input[name="fetch_full_content"]');
        if (fetchFullContentCheckbox) {
            fetchFullContentCheckbox.checked = feedData.fetch_full_content == 1;
        }

        const autoFeaturedImageCheckbox = document.querySelector('input[name="auto_featured_image"]');
        if (autoFeaturedImageCheckbox) {
            autoFeaturedImageCheckbox.checked = feedData.auto_featured_image == 1;
        }

        // Fallback image
        const fallbackImageInput = document.getElementById('fallback-image');
        if (fallbackImageInput && feedData.fallback_image) {
            fallbackImageInput.value = feedData.fallback_image;
        }

        // Content filter
        const contentFilterSelect = document.getElementById('content-filter');
        if (contentFilterSelect && feedData.content_filter) {
            contentFilterSelect.value = feedData.content_filter;
            contentFilterSelect.dispatchEvent(new Event('change'));
        }

        // Update submit button text
        const submitBtn = document.querySelector('button[type="submit"]');
        if (submitBtn) {
            submitBtn.textContent = 'Update Feed Source';
        }
    }
});

function validateFeed() {
    const feedUrl = document.getElementById('feed-url').value;
    const resultDiv = document.getElementById('feed-validation-result');

    if (!feedUrl) {
        Blog82AI_Modal.showError(
            'Validation Error',
            'Please enter a feed URL first.'
        );
        return;
    }

    // Show loading
    resultDiv.style.display = 'block';
    resultDiv.innerHTML = '<div class="blog82ai-validation-loading">🔄 Validating feed...</div>';

    // Make AJAX request to validate feed
    jQuery.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;
                resultDiv.innerHTML = `
                    <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 = document.getElementById('feed-name');
                if (!feedNameInput.value) {
                    feedNameInput.value = data.title;
                }

                // Show feed preview if posts are available
                if (data.preview_posts && data.preview_posts.length > 0) {
                    let previewHtml = '<div class="blog82ai-feed-preview"><h4>Feed Preview:</h4>';
                    data.preview_posts.forEach(post => {
                        previewHtml += `
                            <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>
                        `;
                    });
                    previewHtml += '</div>';
                    resultDiv.innerHTML += previewHtml;
                }
            } else {
                resultDiv.innerHTML = `
                    <div class="blog82ai-validation-error">
                        ❌ ${response.data.message || 'Failed to validate feed.'}
                    </div>
                `;
            }
        },
        error: function (xhr, status, error) {
            resultDiv.innerHTML = `
                <div class="blog82ai-validation-error">
                    ❌ Error validating feed: ${error}
                </div>
            `;
        }
    });
}

function testFeed() {
    const feedUrl = document.getElementById('feed-url').value;

    if (!feedUrl) {
        Blog82AI_Modal.showError(
            'Test Error',
            'Please enter a feed URL first.'
        );
        return;
    }

    // Show preview
    const previewDiv = document.getElementById('feedPreview');
    previewDiv.style.display = 'block';
    previewDiv.querySelector('.blog82ai-preview-content').innerHTML = '<div class="blog82ai-loading">🔄 Loading feed preview...</div>';

    // Call validate_feed AJAX to get real data
    jQuery.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(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.querySelector('.blog82ai-preview-content').innerHTML = `
                    <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.scrollIntoView({ behavior: 'smooth' });
            } else {
                previewDiv.querySelector('.blog82ai-preview-content').innerHTML = `
                    <div class="blog82ai-validation-error">
                        ❌ Error: ${response.data.message}
                    </div>
                `;
            }
        },
        error: function (xhr, status, error) {
            previewDiv.querySelector('.blog82ai-preview-content').innerHTML = `
                <div class="blog82ai-validation-error">
                    ❌ Error testing feed: ${error}
                </div>
            `;
        }
    });
}
