jQuery(document).ready(function($) {
    $('#content_source_toggle').prop('checked', true).trigger('change');

    const noCalendarMessage = $('#no_calendar_message');

    const contentCalendar = $('#diyseo_content_calendar');
    const category = $('#diyseo_category');
    const articleTitle = $('#diyseo_article_title');
    const customTitle = $('#diyseo_custom_title');
    const postDate = $('#diyseo_post_date');
    const wordCount = $('#diyseo_word_count');
    const generateButton = $('#diyseo_generate_content');
    const loadingIndicator = $('#diyseo_calendar_loading');
    const contentToggle = $('#content_source_toggle');
    const additionalContext = $('#diyseo_additional_context')
    const focusKeyword = $('#diyseo_focus_keyword')

    // Function to populate calendars dropdown
    function populateCalendars(calendars) {
        contentCalendar.empty();
        contentCalendar.append($('<option>', {
            value: '',
            text: 'Select Calendar'
        }));
        
        calendars.forEach(function(calendar) {
            contentCalendar.append($('<option>', {
                value: calendar.domain,
                text: calendar.domain
            }));
        });
    }
    function updateArticleSelect(articles) {
    var select = $('#diyseo_article_title');
    select.empty();
    select.append('<option value="">Select Article</option>');
    
    articles.forEach(function(article) {
        var option = $('<option>', {
            value: article.title,
            text: article.title
        });
        
        if (article.status === 'completed') {
            option.addClass('completed-article')
                 .prepend('✓ ');
        }
        
        select.append(option);
    });
}

    // Function to populate categories dropdown
    function populateCategories(data) {
        category.empty();
        
        // Add "All" option first
        category.append($('<option>', {
            value: 'All',
            text: 'All',
            style: 'color: #E0E0E0;'
        }));

        if (data && data.categories) {
            data.categories.forEach(function(cat) {
                if (!cat.value.includes('|')) {
                    // Main category - add as a regular option but styled
                    const mainOption = $('<option>', {
                        value: cat.value,
                        text: cat.label,
                        style: 'color: #ea188a; font-weight: bold; background-color: #12163A;'
                    });
                    category.append(mainOption);

                } else {
                    // Subcategory - add with indent
                    const subcategoryName = cat.value.split('|')[1];
                    const mainCategoryName = cat.value.split('|')[0];
                    const option = $('<option>', {
                        value: cat.value,
                        text: '  ↳ ' + subcategoryName,
                        'data-main-category': mainCategoryName,
                        style: 'color: #E0E0E0; background-color: #12163A; padding-left: 20px;'
                    });
                    category.append(option);
                }
            });
        }
    }

    // Function to populate articles dropdown
// Function to populate articles dropdown
function populateArticles(data) {
    console.log('Raw data received:', data);
    
    articleTitle.empty();
    articleTitle.append($('<option>', {
        value: '',
        text: 'Select Article'
    }));

    // Check the data structure and add debugging
    if (data) {
        console.log('Data exists:', data);
        if (data.articles) {
            console.log('Articles array:', data.articles);
            
            data.articles.forEach(function(article) {
                console.log('Processing article:', article);
                
                // Check if this article exists in the existing array
                const isCompleted = data.existing && data.existing.includes(article.title);
                console.log('Article completion status:', article.title, isCompleted);
                
                var option = $('<option>', {
                    value: article.title,
                    text: isCompleted ? '✓ ' + article.title : article.title
                });
                
                if (isCompleted) {
                    option.addClass('completed-article');
                }
                
                if (article.date) {
                    option.data('post-date', article.date);
                }
                
                articleTitle.append(option);
            });
        } else {
            console.log('No articles array found in data');
        }
    } else {
        console.log('No data received');
    }
}
    // Load content calendars
   function loadContentCalendars() {
    $.ajax({
        url: diyseoCalendarParams.ajaxurl,
        type: 'POST',
        data: {
            action: 'diyseo_get_calendars',
            nonce: diyseoCalendarParams.nonce
        },
        success: function(response) {
            if (response.success && response.data && response.data.length > 0) {
                populateCalendars(response.data);
                noCalendarMessage.hide();
            } else {
                console.error('No calendars found:', response);
                noCalendarMessage.show();
            }
        },
        error: function(xhr, status, error) {
            console.error('AJAX error:', error);
            noCalendarMessage.show();
        }
    });
}

    // Toggle between custom and calendar modes
contentToggle.on('change', function() {
    const isCustom = $(this).is(':checked');
    if (isCustom) {
        $('#calendar_fields').hide();
        $('#custom_title_field').show();
        $('#toggle_label').text('Use Custom Title');
    } else {
        $('#calendar_fields').show();
        $('#custom_title_field').hide();
        $('#toggle_label').text('Use Content Calendar');
        
        // Check if calendars exist when switching to calendar mode
        if (contentCalendar.find('option').length <= 1) { // Only has default option
            loadContentCalendars();
        }
    }
});
    // Update categories when calendar changes
    contentCalendar.on('change', function() {
        const selectedCalendar = $(this).val();
        if (selectedCalendar) {
            $.ajax({
                url: diyseoCalendarParams.ajaxurl,
                type: 'POST',
                data: {
                    action: 'diyseo_get_categories',
                    nonce: diyseoCalendarParams.nonce,
                    calendar: selectedCalendar
                },
                success: function(response) {
                    if (response.success && response.data) {
                        populateCategories(response.data);
                        // Clear articles when calendar changes
                        articleTitle.empty().append($('<option>', {
                            value: '',
                            text: 'Select Article'
                        }));
                    }
                }
            });
        }
    });

    // Update articles when category changes
category.on('change', function() {
    const selectedCalendar = contentCalendar.val();
    const selectedCategory = $(this).val();
    
    if (selectedCalendar && selectedCategory) {
        console.log('Selected category:', selectedCategory);
        
        $.ajax({
            url: diyseoCalendarParams.ajaxurl,
            type: 'POST',
            data: {
                action: 'diyseo_get_articles',
                nonce: diyseoCalendarParams.nonce,
                calendar: selectedCalendar,
                category: selectedCategory
            },
            success: function(response) {
                console.log('Articles response:', response);
                if (response.success && response.data) {
                    populateArticles(response.data);
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX error:', error);
            }
        });
    }
});

    // Update post date when article is selected
    articleTitle.on('change', function() {
        const selectedOption = $(this).find('option:selected');
        const articleDate = selectedOption.data('post-date');
        if (articleDate) {
            postDate.val(articleDate);
        }
    });

    // Generate article
    generateButton.on('click', function() {
        showArticleLoading();
            console.log('Additional Context:', additionalContext);

        const isCustom = contentToggle.is(':checked');
        let title;

        
        if (isCustom) {
            title = customTitle.val().trim();

            if (!title) {
                alert('Please enter a custom title');
                return;
            }
        } else {
            title = articleTitle.val();
            if (!title) {
               // alert('Please select an article from the content calendar');
                //return;
            }
            title = articleTitle.find('option:selected').text();
        }

        loadingIndicator.show();
        loadingIndicator.css("display", "flex");
        
        $.ajax({
            url: diyseoCalendarParams.ajaxurl,
            type: 'POST',
            data: {
                action: 'diyseo_generate_calendar_article',
                nonce: diyseoCalendarParams.nonce,
                post_id: diyseoCalendarParams.postId,
                title: title,
                is_custom: isCustom,
                post_date: postDate.val(),
                word_count: wordCount.val(),
                additional_context: additionalContext.val(),
                focus_keyword: focusKeyword.val()
            },
            success: function(response) {
                 hideArticleLoading()
                if (response.success) {
                    // Update the classic editor if it exists
                    if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
                        tinyMCE.get('content').setContent(response.data.content);
                    }
                    // Update the text editor
                    $('#content').val(response.data.content);
                    // Update the title
                    $('#title').val(response.data.title);
                    // If using Gutenberg
                    if (wp.data && wp.data.dispatch('core/editor')) {
                        wp.data.dispatch('core/editor').editPost({ title: response.data.title });

                        if (wp.blocks && wp.blocks.rawHandler && wp.data.dispatch('core/block-editor')) {
                            var blocks = wp.blocks.rawHandler({ HTML: response.data.content });
                            wp.data.dispatch('core/block-editor').resetBlocks(blocks);
                        } else {
                            wp.data.dispatch('core/editor').editPost({ content: response.data.content });
                        }
                    }
                } else {
                    alert('Failed to generate content: ' + (response.data ? response.data.message : 'Unknown error'));
                }
            },
            error: function() {
                loadingIndicator.hide();
                alert('Failed to generate content. Please try again.');
            }
        });
    });

    // Initialize
    loadContentCalendars();



// Add CSS for the completed articles
$('<style>')
    .prop('type', 'text/css')
    .html(`
        .completed-article {
            color: #28a745 !important;
            font-weight: bold;
        }
        #diyseo_article_title option.completed-article::before {
            content: '✓';
            margin-right: 5px;
        }
    `)
    .appendTo('head');
function showArticleLoading() {
    const container = document.getElementById('articleLoadingContainer');
    const messages = [
        { main: "Analyzing topic...", sub: "Preparing to create your content" },
        { main: "Generating content structure...", sub: "Organizing your article sections" },
        { main: "Writing your article...", sub: "Creating engaging content" },
        { main: "Adding final touches...", sub: "Almost there!" }
    ];
    
    container.style.display = 'flex';
    let messageIndex = 0;
    
    const messageInterval = setInterval(() => {
        if (messageIndex < messages.length) {
            document.getElementById('loadingMessage').textContent = messages[messageIndex].main;
            document.getElementById('loadingSubMessage').textContent = messages[messageIndex].sub;
            messageIndex++;
        } else {
            messageIndex = 0;
        }
    }, 3000);
    
    container.dataset.intervalId = messageInterval;
}

function hideArticleLoading() {
    const container = document.getElementById('articleLoadingContainer');
    if (container.dataset.intervalId) {
        clearInterval(parseInt(container.dataset.intervalId));
    }
    container.style.display = 'none';
}

});