jQuery(document).ready(function($) {
    const contentCalendar = $('#diyseo_content_calendar');
    const category = $('#diyseo_category');
    const articleTitle = $('#diyseo_article_title');
    const generateButton = $('#diyseo_generate_from_calendar');
    const loadingIndicator = $('#diyseo_calendar_loading');
    // Generate article
    $('#diyseo_generate_content').on('click', function() {
        const isCustom = $('#content_source_toggle').is(':checked');
        let title;
        
        // Determine which title to use based on mode
        if (isCustom) {
            title = customTitle.val().trim();
            if (!title) {
                alert('Please enter a custom title');
                return;
            }
        } else {
            const selectedArticle = articleTitle.find('option:selected');
            if (selectedArticle.val() === '' || selectedArticle.text() === 'Select Article') {
                alert('Please select an article from the content calendar');
                return;
            }
            title = selectedArticle.text();
        }

        const wordCount = $('#diyseo_word_count').val();

        console.log('Mode:', isCustom ? 'Custom' : 'Calendar');
        console.log('Title:', title);
        console.log('Word count:', wordCount);

        loadingIndicator.show();
        $.ajax({
            url: diyseoCalendarParams.ajaxurl,
            type: 'POST',
            data: {
                action: 'diyseo_generate_calendar_article',
                nonce: diyseoCalendarParams.nonce,
                post_id: diyseoCalendarParams.postId,
                is_custom: isCustom,
                title: title,
                word_count: wordCount
            },
            success: function(response) {
                loadingIndicator.hide();
                if (response.success) {
                    if (wp.data && wp.data.dispatch('core/editor')) {
                        wp.data.dispatch('core/editor').editPost({
                            title: response.data.title,
                            content: response.data.content
                        });
                    }
                } else {
                    alert(response.data.message || 'Failed to generate content');
                }
            },
            error: function() {
                loadingIndicator.hide();
                alert('Failed to generate content');
            }
        });
    });

    // Toggle between custom and calendar modes
    $('#content_source_toggle').change(function() {
        const isCustom = $(this).is(':checked');
        if (isCustom) {
            $('#calendar_fields').hide();
            $('#custom_title_field').show();
            $('#toggle_label').text('Using Custom Title');
            
            // Clear required attributes from calendar fields
            contentCalendar.prop('required', false);
            category.prop('required', false);
            articleTitle.prop('required', false);
            customTitle.prop('required', true);
        } else {
            $('#calendar_fields').show();
            $('#custom_title_field').hide();
            $('#toggle_label').text('Using Content Calendar');
            
            // Set required attributes for calendar fields
            contentCalendar.prop('required', true);
            category.prop('required', true);
            articleTitle.prop('required', true);
            customTitle.prop('required', false);
        }
    });
    // 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) {
                    populateCalendars(response.data);
                }
            }
        });
    }

    // Update categories when calendar changes
    contentCalendar.on('change', function() {
        $.ajax({
            url: diyseoCalendarParams.ajaxurl,
            type: 'POST',
            data: {
                action: 'diyseo_get_categories',
                nonce: diyseoCalendarParams.nonce,
                calendar: $(this).val()
            },
            success: function(response) {
                if (response.success) {
                    populateCategories(response.data);
                }
            }
        });
    });

    // Update articles when category changes
    category.on('change', function() {
        $.ajax({
            url: diyseoCalendarParams.ajaxurl,
            type: 'POST',
            data: {
                action: 'diyseo_get_articles',
                nonce: diyseoCalendarParams.nonce,
                calendar: contentCalendar.val(),
                category: $(this).val()
            },
            success: function(response) {
                if (response.success) {
                    populateArticles(response.data);
                }
            }
        });
    });

    // Generate article
    generateButton.on('click', function() {
        loadingIndicator.show();
        $.ajax({
            url: diyseoCalendarParams.ajaxurl,
            type: 'POST',
            data: {
                action: 'diyseo_generate_calendar_article',
                nonce: diyseoCalendarParams.nonce,
                post_id: diyseoCalendarParams.postId,
                title: articleTitle.val()
            },
            success: function(response) {
                loadingIndicator.hide();
                if (response.success) {
                    // Update the WordPress editor with the generated content
                    if (wp.data && wp.data.dispatch('core/editor')) {
                        wp.data.dispatch('core/editor').editPost({
                            title: response.data.title,
                            content: response.data.content
                        });
                    }
                }
            }
        });
    });

    // Initial load
    loadContentCalendars();
});