/**
 * Editorial Calendar Page JavaScript
 *
 * @package Wisewand
 * @since 1.0.0
 */

        jQuery(document).ready(function($) {
            let calendar;

            // ===================================
            // HELPER FUNCTIONS (Define First)
            // ===================================

            function validateCTAs() {
                if (!$('input[name="use_cta"]').is(':checked')) {
                    return true;
                }

                let valid = true;
                let errorMsg = '';

                $('.cta-row').each(function(index) {
                    const anchor = $(this).find('.cta-anchor').val().trim();
                    const url = $(this).find('.cta-url').val().trim();

                    if ((anchor && !url) || (!anchor && url)) {
                        errorMsg = '❌ CTA #' + (index + 1) + ': Both anchor text and URL are required';
                        valid = false;
                        return false;
                    }

                    if (url && !isValidURL(url)) {
                        errorMsg = '❌ CTA #' + (index + 1) + ': Invalid URL format';
                        valid = false;
                        return false;
                    }
                });

                if (!valid) {
                    alert(errorMsg);
                }

                return valid;
            }

            function isValidURL(string) {
                try {
                    new URL(string);
                    return true;
                } catch (_) {
                    return false;
                }
            }

            function updateCTANumbers() {
                $('.cta-row').each(function(index) {
                    $(this).find('.cta-number').text('CTA #' + (index + 1));
                    // Hide remove button on first CTA, show on others
                    if (index === 0) {
                        $(this).find('.btn-remove-cta').css('visibility', 'hidden');
                    } else {
                        $(this).find('.btn-remove-cta').css('visibility', 'visible');
                    }
                });
            }

            // Note: loadProjectsAndPersonas() function defined later (line ~1467)
            // Removed duplicate definition here to fix JavaScript error

            function calculateCredits() {
                let total = 0;

                if ($('input[name="use_image"]').is(':checked')) total += 0.5;

                // Dynamic inline images cost based on count
                if ($('input[name="use_inlineimages"]').is(':checked')) {
                    const inlineCount = parseInt($('input[name="inlineimages_count"]').val()) || 1;
                    total += (inlineCount * 0.5);
                }

                if ($('input[name="use_social"]').is(':checked')) total += 0.5;
                if ($('input[name="use_audio"]').is(':checked')) total += 1.0;

                $('#total-credits').text(total.toFixed(1));
            }

            function switchFieldsForContentType(endpoint, type) {
                // Hide all conditional sections
                $('.articles-only-fields, .articles-only-fields-2, .articles-only-fields-3').hide();
                $('.pages-only-fields, .pages-only-fields-2').hide();
                $('.pages-only-features').hide();
                $('.articles-discover-fields').hide();
                $('.affiliation-only-section').hide();
                $('.affiliation-product-review-fields, .affiliation-compare-products-fields, .affiliation-top-products-fields').hide();

                if (endpoint === 'articles') {
                    // Show articles-specific fields
                    $('.articles-only-fields, .articles-only-fields-2, .articles-only-fields-3').show();
                    $('.articles-discover-fields').show(); // Secondary keywords

                    // Show affiliation section if affiliation type
                    if (type && type.startsWith('affiliation-')) {
                        $('.affiliation-only-section').show();

                        if (type === 'affiliation-product-review') {
                            $('.affiliation-product-review-fields').show();
                        } else if (type === 'affiliation-compare-products') {
                            $('.affiliation-compare-products-fields').show();
                        } else if (type === 'affiliation-top-product') {
                            $('.affiliation-top-products-fields').show();
                        }
                    }

                } else if (endpoint === 'categorypages' || endpoint === 'productpages') {
                    // Show category/product page fields
                    $('.pages-only-fields, .pages-only-fields-2').show();
                    $('.pages-only-features').show();

                } else if (endpoint === 'discoverarticles') {
                    // Show discover article fields (hybrid)
                    $('.pages-only-fields, .pages-only-fields-2').show();
                    $('.pages-only-features').show();
                    $('.articles-discover-fields').show(); // Secondary keywords
                }
            }

            // ===================================
            // CALENDAR INITIALIZATION
            // ===================================

            // Initialize FullCalendar
            const calendarEl = document.getElementById('editorial-calendar');
            if (calendarEl) {
                calendar = new FullCalendar.Calendar(calendarEl, {
                    initialView: 'dayGridMonth',
                    headerToolbar: {
                        left: 'prev,next today',
                        center: 'title',
                        right: 'dayGridMonth,timeGridWeek,listMonth'
                    },
                    views: {
                        listMonth: {
                            listDayFormat: { weekday: 'long', month: 'long', day: 'numeric' },
                            noEventsContent: 'No scheduled publications'
                        }
                    },
                    editable: true,
                    events: function(info, successCallback, failureCallback) {
                        loadCalendarEvents(info.startStr, info.endStr, successCallback, failureCallback);
                    },
                    eventClick: function(info) {
                        openEntryPanel(info.event.id);
                    },
                    eventDrop: function(info) {
                        updateEntryDate(info.event.id, info.event.startStr);
                    },
                    height: 'auto',
                });

                calendar.render();
            }

            // Load calendar events
            function loadCalendarEvents(start, end, successCallback, failureCallback) {
                // Get current source filter value
                const sourceFilter = $('#source-filter').val() || 'all';

                $.ajax({
                    url: wisewandCalendar.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'wisewand_get_calendar_events',
                        start_date: start,
                        end_date: end,
                        source_filter: sourceFilter,
                        nonce: wisewandCalendar.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            successCallback(response.data.events);
                        } else {
                            failureCallback();
                        }
                    },
                    error: failureCallback
                });
            }

            // Open entry panel
            function openEntryPanel(entryId) {
                $('#entry-side-panel').show();
                $('#panel-body').html('<div class="loading-spinner">Loading entry details...</div>');

                $.ajax({
                    url: wisewandCalendar.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'wisewand_get_entry_details',
                        entry_id: entryId,
                        nonce: wisewandCalendar.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            $('#panel-body').html(response.data.html);

                            // Load projects and personas after HTML is injected
                            if (typeof loadProjectsAndPersonas === 'function') {
                                loadProjectsAndPersonas();
                            }
                        } else {
                            $('#panel-body').html('<div class="error">Failed to load entry</div>');
                        }
                    }
                });
            }

            // Update entry date on drag
            function updateEntryDate(entryId, newDate) {
                $.ajax({
                    url: wisewandCalendar.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'wisewand_update_entry_date',
                        entry_id: entryId,
                        new_date: newDate,
                        nonce: wisewandCalendar.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            console.log('Entry date updated');
                        } else {
                            alert('Failed to update date');
                            calendar.refetchEvents();
                        }
                    }
                });
            }

            // Save entry changes
            $(document).on('click', '.btn-save-entry', function() {
                const $btn = $(this);
                const entryId = $('#entry-id').val();

                // Validate before saving
                if (!validateCTAs()) {
                    return false;
                }

                const formData = {
                    entry_id: entryId,
                    publication_date: $('input[name="publication_date"]').val(),
                    publication_time_range: $('select[name="publication_time_range"]').val(),
                    content_merge_strategy: $('select[name="content_merge_strategy"]').val(),
                    existing_post_id: $('input[name="existing_post_id"]:checked').val() || '',
                    notes: $('textarea[name="notes"]').val(),
                    api_endpoint: $('#api-endpoint').val(), // NEW: Track which API endpoint
                    wisewand_payload: {
                        // Basic Configuration
                        type: $('#article-type').val(), // From hidden field (only for articles endpoint)
                        length: $('select[name="article_length"]').val(),
                        lang: $('select[name="article_language"]').val(),
                        country: $('select[name="article_country"]').val(),
                        title: $('input[name="article_title"]').val(),
                        target_keyword: $('input[name="target_keyword"]').val(),

                        // Articles-only fields
                        keep_title: $('input[name="keep_title"]').is(':checked'),
                        keywords_secondary: $('textarea[name="keywords_secondary"]').val(),
                        search_intention_answer: $('textarea[name="search_intention_answer"]').val(),
                        avoid_information: $('textarea[name="avoid_information"]').val(),

                        // Category/Product/Discover Pages only fields
                        website: $('input[name="website"]').val() || '',
                        writing_style: $('textarea[name="writing_style"]').val() || '',

                        // Writing Style & Persona
                        writing_style_mode: $('select[name="writing_style_mode"]').val(),
                        persona_id: $('select[name="persona_id"]').val() || '',
                        project_id: $('select[name="project_id"]').val() || '',

                        // Content Features
                        use_toc: $('input[name="use_toc"]').is(':checked'),
                        use_summary: $('input[name="use_summary"]').is(':checked'),
                        use_bulletlist: $('input[name="use_bulletlist"]').is(':checked'),
                        use_blockquotes: $('input[name="use_blockquotes"]').is(':checked'),
                        use_infotable: $('input[name="use_infotable"]').is(':checked'),
                        use_boldkeywords: $('input[name="use_boldkeywords"]').is(':checked'),
                        use_externalsources: $('input[name="use_externalsources"]').is(':checked'),

                        // FAQ
                        use_faq: $('input[name="use_faq"]').is(':checked'),
                        faq_questions: $('textarea[name="faq_questions"]').val(),

                        // CTAs
                        use_cta: $('input[name="use_cta"]').is(':checked'),
                        cta_anchors: $('.cta-anchor').map(function() { return $(this).val(); }).get(),
                        cta_urls: $('.cta-url').map(function() { return $(this).val(); }).get(),

                        // Social Media
                        use_social: $('input[name="use_social"]').is(':checked'),
                        social_networks: $('input[name="social_networks[]"]:checked').map(function() { return $(this).val(); }).get(),

                        // Featured Image
                        use_image: $('input[name="use_image"]').is(':checked'),
                        image_ratio: $('select[name="image_ratio"]').val(),
                        image_use_palette: $('input[name="image_use_palette"]').is(':checked'),
                        image_primary_color: $('input[name="image_primary_color"]').val(),
                        image_secondary_color: $('input[name="image_secondary_color"]').val(),
                        image_prompt: $('textarea[name="image_prompt"]').val(),

                        // Inline Images
                        use_inlineimages: $('input[name="use_inlineimages"]').is(':checked'),
                        inlineimages_count: parseInt($('input[name="inlineimages_count"]').val()) || 1,
                        inline_images_ratio: $('select[name="inline_images_ratio"]').val(),
                        inline_images_use_palette: $('input[name="inline_images_use_palette"]').is(':checked'),
                        inline_images_primary_color: $('input[name="inline_images_primary_color"]').val(),
                        inline_images_secondary_color: $('input[name="inline_images_secondary_color"]').val(),

                        // Audio
                        use_audio: $('input[name="use_audio"]').is(':checked'),
                        audio_voice_id: $('select[name="audio_voice_id"]').val(),

                        // Internal Links
                        use_internallinks: $('input[name="use_internallinks"]').is(':checked'),
                        use_indexed_pages_internal_links: $('input[name="use_indexed_pages_internal_links"]').is(':checked'),
                        use_wp_internal_links: $('input[name="use_wp_internal_links"]').is(':checked'),
                        use_app_internal_links: $('input[name="use_app_internal_links"]').is(':checked'),
                        use_list_internal_links: $('input[name="use_list_internal_links"]').is(':checked'),
                        internal_links_list: $('textarea[name="internal_links_list"]').val(),
                        internal_links_wp_status: $('input[name="internal_links_wp_status[]"]:checked').map(function() { return $(this).val(); }).get(),

                        // Affiliation Fields - Product Review
                        affiliation_product_name: $('input[name="affiliation_product_name"]').val(),
                        affiliation_product_review_urls: $('input[name="affiliation_product_review_urls[]"]').map(function() { return $(this).val(); }).get(),
                        affiliation_link_urls: $('.affiliation-link-url').map(function() { return $(this).val(); }).get(),
                        affiliation_link_anchors: $('.affiliation-link-anchor').map(function() { return $(this).val(); }).get(),
                        affiliation_promo_code: $('input[name="affiliation_promo_code"]').val(),
                        affiliation_promo_percentage: $('input[name="affiliation_promo_percentage"]').val(),

                        // Affiliation Fields - Compare Products (Product 1)
                        affiliation_product_1_name: $('input[name="affiliation_product_1_name"]').val(),
                        affiliation_product_1_review_urls: $('input[name="affiliation_product_1_review_urls[]"]').map(function() { return $(this).val(); }).get(),
                        affiliation_product_1_link_urls: $('input[name="affiliation_links_product_1_url[]"]').map(function() { return $(this).val(); }).get(),
                        affiliation_product_1_link_anchors: $('input[name="affiliation_links_product_1_anchor[]"]').map(function() { return $(this).val(); }).get(),
                        affiliation_promo_code_1: $('input[name="affiliation_promo_code_1"]').val(),
                        affiliation_promo_percentage_1: $('input[name="affiliation_promo_percentage_1"]').val(),

                        // Affiliation Fields - Compare Products (Product 2)
                        affiliation_product_2_name: $('input[name="affiliation_product_2_name"]').val(),
                        affiliation_product_2_review_urls: $('input[name="affiliation_product_2_review_urls[]"]').map(function() { return $(this).val(); }).get(),
                        affiliation_product_2_link_urls: $('input[name="affiliation_links_product_2_url[]"]').map(function() { return $(this).val(); }).get(),
                        affiliation_product_2_link_anchors: $('input[name="affiliation_links_product_2_anchor[]"]').map(function() { return $(this).val(); }).get(),
                        affiliation_promo_code_2: $('input[name="affiliation_promo_code_2"]').val(),
                        affiliation_promo_percentage_2: $('input[name="affiliation_promo_percentage_2"]').val(),

                        // AI Instructions
                        search_intention_answer: $('textarea[name="search_intention_answer"]').val(),
                        additional_information: $('textarea[name="additional_information"]').val(),
                        avoid_information: $('textarea[name="avoid_information"]').val(),
                    },
                    nonce: wisewandCalendar.nonce
                };

                // Collect Top Products data (complex nested structure)
                const topProducts = [];
                $('#top-products-container .top-product-card').each(function() {
                    const $card = $(this);
                    const product = {
                        name: $card.find('.top-product-name').val(),
                        urls: [],
                        affiliation_links: [],
                        promo_code: $card.find('.top-product-promo-code').val(),
                        promo_percentage: $card.find('.top-product-promo-percentage').val()
                    };

                    // Collect URLs for this product
                    $card.find('.top-product-url').each(function() {
                        const url = $(this).val();
                        if (url) product.urls.push(url);
                    });

                    // Collect affiliation links for this product
                    $card.find('.top-product-affiliation-links-container .affiliation-link-row-small').each(function() {
                        const url = $(this).find('.top-product-link-url').val();
                        const anchor = $(this).find('.top-product-link-anchor').val();
                        if (url && anchor) {
                            product.affiliation_links.push({url: url, anchor: anchor});
                        }
                    });

                    if (product.name || product.urls.length > 0 || product.affiliation_links.length > 0) {
                        topProducts.push(product);
                    }
                });

                formData.wisewand_payload.top_products_data = topProducts;

                $btn.prop('disabled', true).text('💾 Saving...');

                $.ajax({
                    url: wisewandCalendar.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'wisewand_save_entry',
                        ...formData
                    },
                    success: function(response) {
                        if (response.success) {
                            alert('✅ Changes saved successfully!');
                            $('#entry-side-panel').hide();
                            calendar.refetchEvents();
                        } else {
                            alert('❌ Save failed:\n' + (response.data?.message || 'Unknown error'));
                        }
                    },
                    error: function() {
                        alert('❌ Connection error');
                    },
                    complete: function() {
                        $btn.prop('disabled', false).text('💾 Save Changes');
                    }
                });
            });

            // Delete entry
            $(document).on('click', '.btn-delete-entry', function() {
                const entryId = $('#entry-id').val();

                if (!confirm('🗑️ Delete this scheduled publication?\n\nThis action cannot be undone.')) {
                    return;
                }

                $.ajax({
                    url: wisewandCalendar.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'wisewand_delete_entry',
                        entry_id: entryId,
                        nonce: wisewandCalendar.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            alert('✅ Entry deleted');
                            $('#entry-side-panel').hide();
                            calendar.refetchEvents();
                        } else {
                            alert('❌ Delete failed');
                        }
                    }
                });
            });

            // Generate Now
            $(document).on('click', '.btn-generate-now', function() {
                const $btn = $(this);
                const entryId = $('#entry-id').val();

                if (!confirm('⚡ Generate Article Now?\n\nThis will:\n• Save your current settings\n• Start AI content generation immediately\n• Article will be ready in 5-10 minutes\n\nContinue?')) {
                    return;
                }

                // Validate CTAs before generating
                if (!validateCTAs()) {
                    return false;
                }

                $btn.prop('disabled', true).text('⚡ Saving & Generating...');

                // Collect current form data (IMPORTANT: Use what user just configured!)
                const currentFormData = {
                    entry_id: entryId,
                    publication_date: $('input[name="publication_date"]').val(),
                    publication_time_range: $('select[name="publication_time_range"]').val(),
                    content_merge_strategy: $('select[name="content_merge_strategy"]').val(),
                    existing_post_id: $('input[name="existing_post_id"]:checked').val() || '',
                    notes: $('textarea[name="notes"]').val(),
                    api_endpoint: $('#api-endpoint').val(),
                    wisewand_payload: {
                        type: $('#article-type').val(),
                        length: $('select[name="article_length"]').val(),
                        lang: $('select[name="article_language"]').val(),
                        country: $('select[name="article_country"]').val(),
                        title: $('input[name="article_title"]').val(),
                        target_keyword: $('input[name="target_keyword"]').val(),
                        keep_title: $('input[name="keep_title"]').is(':checked'),
                        keywords_secondary: $('textarea[name="keywords_secondary"]').val(),
                        search_intention_answer: $('textarea[name="search_intention_answer"]').val(),
                        avoid_information: $('textarea[name="avoid_information"]').val(),
                        website: $('input[name="website"]').val() || '',
                        writing_style: $('textarea[name="writing_style"]').val() || '',
                        writing_style_mode: $('select[name="writing_style_mode"]').val(),
                        persona_id: $('select[name="persona_id"]').val() || '',
                        project_id: $('select[name="project_id"]').val() || '',
                        use_toc: $('input[name="use_toc"]').is(':checked'),
                        use_summary: $('input[name="use_summary"]').is(':checked'),
                        use_bulletlist: $('input[name="use_bulletlist"]').is(':checked'),
                        use_blockquotes: $('input[name="use_blockquotes"]').is(':checked'),
                        use_infotable: $('input[name="use_infotable"]').is(':checked'),
                        use_boldkeywords: $('input[name="use_boldkeywords"]').is(':checked'),
                        use_externalsources: $('input[name="use_externalsources"]').is(':checked'),
                        use_faq: $('input[name="use_faq"]').is(':checked'),
                        faq_questions: $('textarea[name="faq_questions"]').val(),
                        use_cta: $('input[name="use_cta"]').is(':checked'),
                        cta_anchors: $('.cta-anchor').map(function() { return $(this).val(); }).get(),
                        cta_urls: $('.cta-url').map(function() { return $(this).val(); }).get(),
                        use_social: $('input[name="use_social"]').is(':checked'),
                        social_networks: $('input[name="social_networks[]"]:checked').map(function() { return $(this).val(); }).get(),
                        use_image: $('input[name="use_image"]').is(':checked'),
                        image_ratio: $('select[name="image_ratio"]').val(),
                        image_use_palette: $('input[name="image_use_palette"]').is(':checked'),
                        image_primary_color: $('input[name="image_primary_color"]').val(),
                        image_secondary_color: $('input[name="image_secondary_color"]').val(),
                        image_prompt: $('textarea[name="image_prompt"]').val(),
                        use_inlineimages: $('input[name="use_inlineimages"]').is(':checked'),
                        inlineimages_count: parseInt($('input[name="inlineimages_count"]').val()) || 1,
                        inline_images_ratio: $('select[name="inline_images_ratio"]').val(),
                        inline_images_use_palette: $('input[name="inline_images_use_palette"]').is(':checked'),
                        inline_images_primary_color: $('input[name="inline_images_primary_color"]').val(),
                        inline_images_secondary_color: $('input[name="inline_images_secondary_color"]').val(),
                        use_audio: $('input[name="use_audio"]').is(':checked'),
                        audio_voice_id: $('select[name="audio_voice_id"]').val(),
                        use_internallinks: $('input[name="use_internallinks"]').is(':checked'),
                        use_indexed_pages_internal_links: $('input[name="use_indexed_pages_internal_links"]').is(':checked'),
                        use_wp_internal_links: $('input[name="use_wp_internal_links"]').is(':checked'),
                        use_app_internal_links: $('input[name="use_app_internal_links"]').is(':checked'),
                        use_list_internal_links: $('input[name="use_list_internal_links"]').is(':checked'),
                        internal_links_list: $('textarea[name="internal_links_list"]').val(),
                        internal_links_wp_status: $('input[name="internal_links_wp_status[]"]:checked').map(function() { return $(this).val(); }).get(),
                        additional_information: $('textarea[name="additional_information"]').val(),
                        affiliation_product_name: $('input[name="affiliation_product_name"]').val(),
                        affiliation_product_review_urls: $('input[name="affiliation_product_review_urls[]"]').map(function() { return $(this).val(); }).get(),
                        affiliation_link_urls: $('.affiliation-link-url').map(function() { return $(this).val(); }).get(),
                        affiliation_link_anchors: $('.affiliation-link-anchor').map(function() { return $(this).val(); }).get(),
                        affiliation_promo_code: $('input[name="affiliation_promo_code"]').val(),
                        affiliation_promo_percentage: $('input[name="affiliation_promo_percentage"]').val(),
                        affiliation_product_1_name: $('input[name="affiliation_product_1_name"]').val(),
                        affiliation_product_1_review_urls: $('input[name="affiliation_product_1_review_urls[]"]').map(function() { return $(this).val(); }).get(),
                        affiliation_product_1_link_urls: $('input[name="affiliation_links_product_1_url[]"]').map(function() { return $(this).val(); }).get(),
                        affiliation_product_1_link_anchors: $('input[name="affiliation_links_product_1_anchor[]"]').map(function() { return $(this).val(); }).get(),
                        affiliation_promo_code_1: $('input[name="affiliation_promo_code_1"]').val(),
                        affiliation_promo_percentage_1: $('input[name="affiliation_promo_percentage_1"]').val(),
                        affiliation_product_2_name: $('input[name="affiliation_product_2_name"]').val(),
                        affiliation_product_2_review_urls: $('input[name="affiliation_product_2_review_urls[]"]').map(function() { return $(this).val(); }).get(),
                        affiliation_product_2_link_urls: $('input[name="affiliation_links_product_2_url[]"]').map(function() { return $(this).val(); }).get(),
                        affiliation_product_2_link_anchors: $('input[name="affiliation_links_product_2_anchor[]"]').map(function() { return $(this).val(); }).get(),
                        affiliation_promo_code_2: $('input[name="affiliation_promo_code_2"]').val(),
                        affiliation_promo_percentage_2: $('input[name="affiliation_promo_percentage_2"]').val(),
                    },
                };

                // Collect Top Products data
                const topProducts = [];
                $('#top-products-container .top-product-card').each(function() {
                    const $card = $(this);
                    const product = {
                        name: $card.find('.top-product-name').val(),
                        urls: [],
                        affiliation_links: [],
                        promo_code: $card.find('.top-product-promo-code').val(),
                        promo_percentage: $card.find('.top-product-promo-percentage').val()
                    };

                    $card.find('.top-product-url').each(function() {
                        const url = $(this).val();
                        if (url) product.urls.push(url);
                    });

                    $card.find('.top-product-affiliation-links-container .affiliation-link-row-small').each(function() {
                        const url = $(this).find('.top-product-link-url').val();
                        const anchor = $(this).find('.top-product-link-anchor').val();
                        if (url && anchor) {
                            product.affiliation_links.push({url: url, anchor: anchor});
                        }
                    });

                    if (product.name || product.urls.length > 0 || product.affiliation_links.length > 0) {
                        topProducts.push(product);
                    }
                });

                currentFormData.wisewand_payload.top_products_data = topProducts;

                // DEBUG: Log what we're about to send
                console.log('=== GENERATE NOW: Sending Data ===');
                console.log('Entry ID:', entryId);
                console.log('API Endpoint:', currentFormData.api_endpoint);
                console.log('Persona ID:', currentFormData.wisewand_payload.persona_id);
                console.log('Project ID:', currentFormData.wisewand_payload.project_id);
                console.log('Full Payload:', currentFormData);
                console.log('================================');

                // Send CURRENT form data (what user just configured) for Generate Now
                $.ajax({
                    url: wisewandCalendar.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'wisewand_generate_now',
                        ...currentFormData, // Send all current form values!
                        nonce: wisewandCalendar.nonce
                    },
                    success: function(response) {
                        console.log('=== GENERATE NOW: Response Received ===');
                        console.log('Success:', response.success);
                        console.log('Response:', response);
                        console.log('=====================================');

                        if (response.success) {
                            const message = '✅ ' + response.data.message +
                                          '\n\nArticle ID: ' + response.data.article_id +
                                          '\n\nView in Wisewand Dashboard:\n' + response.data.wisewand_url +
                                          '\n\nThe article is now generating. Check back in 5-10 minutes or wait for webhook notification.';

                            alert(message);

                            // Also log the clickable link
                            console.log('🔗 View article in Wisewand:', response.data.wisewand_url);

                            calendar.refetchEvents();
                            // Keep panel open to show updated status
                            setTimeout(function() {
                                // Reload entry details to show new status
                                openEntryPanel(entryId);
                            }, 1000);
                        } else {
                            console.error('=== GENERATE NOW: Failed ===');
                            console.error('Error Message:', response.data?.message);
                            console.error('Full Response:', response);
                            console.error('============================');

                            const errorDetails = response.data?.message || 'Unknown error';
                            alert('❌ Generation failed:\n\n' + errorDetails + '\n\nCheck browser console (F12) for more details');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('=== GENERATE NOW AJAX ERROR ===');
                        console.error('Status:', status);
                        console.error('Error:', error);
                        console.error('Response:', xhr.responseText);
                        console.error('Status Code:', xhr.status);
                        console.error('===============================');

                        let errorMsg = 'Connection error: ' + error;
                        try {
                            const response = JSON.parse(xhr.responseText);
                            if (response.data && response.data.message) {
                                errorMsg = response.data.message;
                            }
                        } catch(e) {
                            // Keep default error
                        }

                        alert('❌ ' + errorMsg + '\n\nCheck browser console (F12) for details');
                    },
                    complete: function() {
                        $btn.prop('disabled', false).text('⚡ Generate Now');
                    }
                });
            });

            // Import Now button handler
            $(document).on('click', '#import-now-btn', function() {
                const $btn = $(this);
                const entryId = $('#entry-id').val();

                if (!confirm('📥 Import this article to WordPress now?\n\nThis will create a WordPress post immediately.\n\nContinue?')) {
                    return;
                }

                $btn.prop('disabled', true).text('📥 Importing...');

                $.ajax({
                    url: wisewandCalendar.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'wisewand_import_now',
                        entry_id: entryId,
                        nonce: wisewandCalendar.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            alert('✅ ' + response.data.message + '\n\nPost ID: ' + response.data.post_id);

                            // Refresh calendar and panel
                            calendar.refetchEvents();
                            setTimeout(function() {
                                openEntryPanel(entryId);
                            }, 1000);
                        } else {
                            alert('❌ Import failed:\n\n' + (response.data?.message || 'Unknown error'));
                            $btn.prop('disabled', false).text('📥 Import Now to WordPress');
                        }
                    },
                    error: function(xhr, status, error) {
                        alert('❌ Network error:\n\n' + error);
                        $btn.prop('disabled', false).text('📥 Import Now to WordPress');
                    }
                });
            });

            // Generate AI Instructions - Template (Quick)
            $(document).on('click', '#generate-instructions-template', function() {
                const $btn = $(this);
                const entryId = $('#entry-id').val();

                $btn.prop('disabled', true).text('📝 Generating...');

                $.ajax({
                    url: wisewandCalendar.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'wisewand_generate_instructions_template',
                        entry_id: entryId,
                        nonce: wisewandCalendar.nonce
                    },
                    success: function(response) {
                        if (response.success && response.data.instructions) {
                            $('textarea[name="search_intention_answer"]').val(response.data.instructions.search_intention_answer || '');
                            $('textarea[name="additional_information"]').val(response.data.instructions.additional_information || '');
                            $('textarea[name="avoid_information"]').val(response.data.instructions.avoid_information || '');

                            $btn.text('✅ Generated!');
                            setTimeout(() => $btn.prop('disabled', false).text('📝 Quick Generate (Template)'), 2000);
                        } else {
                            alert('Failed to generate: ' + (response.data?.message || 'Unknown error'));
                            $btn.prop('disabled', false).text('📝 Quick Generate (Template)');
                        }
                    },
                    error: function() {
                        alert('Network error');
                        $btn.prop('disabled', false).text('📝 Quick Generate (Template)');
                    }
                });
            });

            // Generate AI Instructions - ChatGPT (AI-Powered)
            $(document).on('click', '#generate-instructions-ai', function() {
                const $btn = $(this);
                const entryId = $('#entry-id').val();

                $btn.prop('disabled', true).text('✨ Generating with AI...');

                $.ajax({
                    url: wisewandCalendar.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'wisewand_generate_instructions_ai',
                        entry_id: entryId,
                        nonce: wisewandCalendar.nonce
                    },
                    success: function(response) {
                        if (response.success && response.data.instructions) {
                            $('textarea[name="search_intention_answer"]').val(response.data.instructions.search_intention_answer || '');
                            $('textarea[name="additional_information"]').val(response.data.instructions.additional_information || '');
                            $('textarea[name="avoid_information"]').val(response.data.instructions.avoid_information || '');

                            $btn.text('✅ Generated!');
                            setTimeout(() => $btn.prop('disabled', false).text('✨ AI Generate (ChatGPT) ~$0.0001'), 2000);
                        } else {
                            alert('❌ AI Generation Failed\n\n' + (response.data?.message || 'Unknown error') + '\n\nTry "Quick Generate" (template) instead, or check your OpenAI API key in Settings.');
                            $btn.prop('disabled', false).text('✨ AI Generate (ChatGPT) ~$0.0001');
                        }
                    },
                    error: function(xhr, status, error) {
                        alert('❌ Network Error\n\n' + error + '\n\nTry "Quick Generate" (template) instead.');
                        $btn.prop('disabled', false).text('✨ AI Generate (ChatGPT) ~$0.0001');
                    }
                });
            });

            // Close panel
            $('.close-panel, .panel-overlay').on('click', function() {
                $('#entry-side-panel').hide();
            });

            // Clear all calendar entries (Editorial Calendar page)
            $('#clear-calendar-editorial').on('click', function() {
                if (!confirm('🗑️ Clear ALL Calendar Entries?\n\nThis will delete all scheduled, generating, and pending entries.\nPublished posts will be kept.\n\nCannot be undone. Continue?')) {
                    return;
                }

                const $btn = $(this);
                $btn.prop('disabled', true).text('🗑️ Clearing...');

                $.ajax({
                    url: wisewandCalendar.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'wisewand_clear_all_calendar',
                        nonce: wisewandCalendar.seoNonce
                    },
                    success: function(response) {
                        if (response.success) {
                            alert('✅ ' + response.data.message);
                            location.reload();
                        } else {
                            alert('❌ ' + (response.data?.message || 'Failed'));
                        }
                    },
                    complete: function() {
                        $btn.prop('disabled', false).text('🗑️ Clear All Scheduled');
                    }
                });
            });

            // View switcher
            $('.view-btn').on('click', function() {
                const view = $(this).data('view');
                $('.view-btn').removeClass('active');
                $(this).addClass('active');
                if (calendar) {
                    calendar.changeView(view);
                }
            });

            // Source filter
            $('#source-filter').on('change', function() {
                if (calendar) {
                    calendar.refetchEvents();
                }
            });

            // ===================================
            // CTA REPEATER MANAGEMENT
            // ===================================

            $(document).on('click', '#add-cta-btn', function() {
                const ctaCount = $('.cta-row').length + 1;
                const html = `
                    <div class="cta-row" data-index="${ctaCount}">
                        <div class="cta-row-header">
                            <span class="cta-number">CTA #${ctaCount}</span>
                            <button type="button" class="btn-remove-cta">🗑️</button>
                        </div>
                        <div class="cta-row-fields">
                            <div class="form-col">
                                <label>Anchor Text</label>
                                <input type="text" name="cta_anchor[]" class="panel-input cta-anchor" placeholder="Click here to learn more">
                            </div>
                            <div class="form-col">
                                <label>Target URL</label>
                                <input type="url" name="cta_url[]" class="panel-input cta-url" placeholder="https://example.com/product">
                            </div>
                        </div>
                    </div>
                `;
                $('#ctas-container').append(html);
                updateCTANumbers();
            });

            $(document).on('click', '.btn-remove-cta', function() {
                if ($('.cta-row').length > 1) {
                    $(this).closest('.cta-row').remove();
                    updateCTANumbers();
                }
            });

            // ===================================
            // CONDITIONAL FIELD VISIBILITY (Delegated Events)
            // ===================================

            $(document).on('change', '#toggle-cta', function() {
                $('#ctas-section').toggle($(this).is(':checked'));
            });

            $(document).on('change', '#toggle-faq', function() {
                $('#faq-advanced').toggle($(this).is(':checked'));
            });

            $(document).on('change', '#toggle-social', function() {
                $('#social-networks-container').toggle($(this).is(':checked'));
            });

            $(document).on('change', '#toggle-featured-image', function() {
                $('#featured-image-config').toggle($(this).is(':checked'));
            });

            $(document).on('change', '#toggle-image-palette', function() {
                $('#image-colors-config').toggle($(this).is(':checked'));
            });

            $(document).on('change', '#toggle-inline-images', function() {
                $('#inline-images-config').toggle($(this).is(':checked'));
            });

            $(document).on('change', '#toggle-inline-palette', function() {
                $('#inline-colors-config').toggle($(this).is(':checked'));
            });

            $(document).on('change', '#toggle-audio', function() {
                $('#audio-config').toggle($(this).is(':checked'));
            });

            $(document).on('change', '#toggle-manual-links', function() {
                $('#manual-links-config').toggle($(this).is(':checked'));
            });

            $(document).on('change', '#writing-style-mode', function() {
                $('#persona-select-container').toggle($(this).val() === 'persona');
            });

            // ===================================
            // AFFILIATION FIELDS REPEATERS
            // ===================================

            // Product Review - Review URLs
            $(document).on('click', '.btn-add-review-url', function() {
                const html = `
                    <div class="repeater-row">
                        <input type="url" name="affiliation_product_review_urls[]" class="panel-input" placeholder="https://...">
                        <button type="button" class="btn-remove-repeater">🗑️</button>
                    </div>
                `;
                $('#review-urls-container').append(html);
            });

            $(document).on('click', '.btn-remove-repeater', function() {
                $(this).closest('.repeater-row').remove();
            });

            // Product Review - Affiliation Links
            $(document).on('click', '#add-affiliation-link-btn', function() {
                const count = $('#affiliation-links-container .affiliation-link-row').length + 1;
                const html = `
                    <div class="affiliation-link-row">
                        <div class="affiliation-link-header">
                            <span class="link-number">Link #${count}</span>
                            <button type="button" class="btn-remove-affiliation-link">🗑️</button>
                        </div>
                        <div class="form-row-two">
                            <div class="form-col">
                                <label>URL</label>
                                <input type="url" name="affiliation_link_url[]" class="panel-input affiliation-link-url" placeholder="https://amazon.fr/product/...">
                            </div>
                            <div class="form-col">
                                <label>Anchor Text</label>
                                <input type="text" name="affiliation_link_anchor[]" class="panel-input affiliation-link-anchor" placeholder="Buy on Amazon">
                            </div>
                        </div>
                    </div>
                `;
                $('#affiliation-links-container').append(html);
            });

            $(document).on('click', '.btn-remove-affiliation-link', function() {
                if ($('#affiliation-links-container .affiliation-link-row').length > 1) {
                    $(this).closest('.affiliation-link-row').remove();
                }
            });

            // Compare Products - Review URLs for each product
            $(document).on('click', '[class^="btn-add-review-url-"]', function() {
                const productNum = $(this).data('product');
                const container = $(`.review-urls-product-${productNum}`);
                const html = `
                    <div class="repeater-row">
                        <input type="url" name="affiliation_product_${productNum}_review_urls[]" class="panel-input" placeholder="https://...">
                        <button type="button" class="btn-remove-repeater">🗑️</button>
                    </div>
                `;
                container.append(html);
            });

            // Compare Products - Affiliation Links for each product
            $(document).on('click', '[class^="btn-add-affiliation-link-"]', function() {
                const productNum = $(this).data('product');
                const container = $(`.affiliation-links-product-${productNum}`);
                const html = `
                    <div class="affiliation-link-row-small">
                        <div class="form-row-two">
                            <div class="form-col">
                                <input type="url" name="affiliation_links_product_${productNum}_url[]" class="panel-input" placeholder="URL">
                            </div>
                            <div class="form-col">
                                <input type="text" name="affiliation_links_product_${productNum}_anchor[]" class="panel-input" placeholder="Anchor">
                            </div>
                        </div>
                        <button type="button" class="btn-remove-affiliation-link-small">🗑️</button>
                    </div>
                `;
                container.append(html);
            });

            $(document).on('click', '.btn-remove-affiliation-link-small', function() {
                $(this).closest('.affiliation-link-row-small').remove();
            });

            // Top Products - Add entire product card
            $(document).on('click', '#add-top-product-btn', function() {
                const count = $('#top-products-container .top-product-card').length + 1;
                const html = `
                    <div class="top-product-card" data-product-index="${count}">
                        <div class="top-product-header">
                            <span class="top-product-number">🥇 Product #${count}</span>
                            <button type="button" class="btn-remove-top-product">🗑️</button>
                        </div>

                        <label>Product Name</label>
                        <input type="text" class="panel-input top-product-name" placeholder="e.g., iPhone 15 Pro">

                        <label>Review URLs</label>
                        <div class="top-product-urls-container">
                            <div class="repeater-row">
                                <input type="url" class="panel-input top-product-url" placeholder="https://...">
                                <button type="button" class="btn-remove-top-product-url" style="visibility:hidden;">🗑️</button>
                            </div>
                        </div>
                        <button type="button" class="btn-add-top-product-url btn-add-field-small">+ Add URL</button>

                        <label>Affiliation Links</label>
                        <div class="top-product-affiliation-links-container">
                            <div class="affiliation-link-row-small">
                                <div class="form-row-two">
                                    <div class="form-col">
                                        <input type="url" class="panel-input top-product-link-url" placeholder="URL">
                                    </div>
                                    <div class="form-col">
                                        <input type="text" class="panel-input top-product-link-anchor" placeholder="Anchor">
                                    </div>
                                </div>
                                <button type="button" class="btn-remove-top-product-link" style="visibility:hidden;">🗑️</button>
                            </div>
                        </div>
                        <button type="button" class="btn-add-top-product-link btn-add-field-small">+ Add Link</button>

                        <div class="form-row-two">
                            <div class="form-col">
                                <label>Promo Code</label>
                                <input type="text" class="panel-input top-product-promo-code" placeholder="PROMO20">
                            </div>
                            <div class="form-col">
                                <label>Discount %</label>
                                <input type="text" class="panel-input top-product-promo-percentage" placeholder="20">
                            </div>
                        </div>
                    </div>
                `;
                $('#top-products-container').append(html);
            });

            $(document).on('click', '.btn-remove-top-product', function() {
                if ($('#top-products-container .top-product-card').length > 1) {
                    $(this).closest('.top-product-card').remove();
                    // Renumber products
                    $('#top-products-container .top-product-card').each(function(index) {
                        $(this).find('.top-product-number').text('🥇 Product #' + (index + 1));
                    });
                }
            });

            // Top Products - Add URL to specific product
            $(document).on('click', '.btn-add-top-product-url', function() {
                const container = $(this).prev('.top-product-urls-container');
                const html = `
                    <div class="repeater-row">
                        <input type="url" class="panel-input top-product-url" placeholder="https://...">
                        <button type="button" class="btn-remove-top-product-url">🗑️</button>
                    </div>
                `;
                container.append(html);
            });

            $(document).on('click', '.btn-remove-top-product-url', function() {
                $(this).closest('.repeater-row').remove();
            });

            // Top Products - Add affiliation link to specific product
            $(document).on('click', '.btn-add-top-product-link', function() {
                const container = $(this).prev('.top-product-affiliation-links-container');
                const html = `
                    <div class="affiliation-link-row-small">
                        <div class="form-row-two">
                            <div class="form-col">
                                <input type="url" class="panel-input top-product-link-url" placeholder="URL">
                            </div>
                            <div class="form-col">
                                <input type="text" class="panel-input top-product-link-anchor" placeholder="Anchor">
                            </div>
                        </div>
                        <button type="button" class="btn-remove-top-product-link">🗑️</button>
                    </div>
                `;
                container.append(html);
            });

            $(document).on('click', '.btn-remove-top-product-link', function() {
                $(this).closest('.affiliation-link-row-small').remove();
            });

            // ===================================
            // CONTENT TYPE SELECTOR & AUTO-CONFIGURATION
            // ===================================

            $(document).on('change', '#content-type-selector', function() {
                const value = $(this).val();
                const [endpoint, type] = value.split('|');

                // Update hidden fields
                $('#api-endpoint').val(endpoint);
                $('#article-type').val(type);

                // Switch visible fields based on endpoint and type
                switchFieldsForContentType(endpoint, type);

                // Apply type-specific auto-configuration
                applyTypeAutoConfiguration(endpoint, type);

                // Recalculate credits
                calculateCredits();
            });

            function applyTypeAutoConfiguration(endpoint, type) {
                // Articles endpoint - type-specific config
                if (endpoint === 'articles') {
                    if (type === 'affiliation-product-review') {
                        $('input[name="use_cta"]').prop('checked', true).trigger('change');
                        $('input[name="use_infotable"]').prop('checked', true);
                        $('input[name="use_faq"]').prop('checked', true).trigger('change');
                        $('input[name="use_social"]').prop('checked', true).trigger('change');
                    } else if (type === 'affiliation-compare-products') {
                        $('input[name="use_cta"]').prop('checked', true).trigger('change');
                        $('input[name="use_infotable"]').prop('checked', true);
                        $('input[name="use_bulletlist"]').prop('checked', true);
                        $('input[name="use_faq"]').prop('checked', true).trigger('change');
                    } else if (type === 'affiliation-top-product') {
                        $('input[name="use_cta"]').prop('checked', true).trigger('change');
                        $('input[name="use_infotable"]').prop('checked', true);
                        $('input[name="use_bulletlist"]').prop('checked', true);
                    } else if (type === 'news') {
                        $('input[name="use_externalsources"]').prop('checked', true);
                        $('input[name="use_social"]').prop('checked', true).trigger('change');
                        $('input[name="use_audio"]').prop('checked', false).trigger('change');
                    }
                }

                // Category/Product Pages
                else if (endpoint === 'categorypages' || endpoint === 'productpages') {
                    $('input[name="use_cta"]').prop('checked', true).trigger('change');
                    $('input[name="use_infotable"]').prop('checked', true);
                    $('input[name="use_summary"]').prop('checked', true);
                    $('input[name="use_blockquotes"]').prop('checked', true);
                }

                // Discover Articles
                else if (endpoint === 'discoverarticles') {
                    // Discover articles optimized for visual engagement
                    $('input[name="use_image"]').prop('checked', true).trigger('change');
                    $('input[name="use_inlineimages"]').prop('checked', true).trigger('change');
                    $('input[name="use_summary"]').prop('checked', true);
                    $('input[name="use_blockquotes"]').prop('checked', true);
                }
            }

            // Credit Calculator - Update on media checkbox changes
            $(document).on('change', 'input[name="use_image"], input[name="use_inlineimages"], input[name="use_social"], input[name="use_audio"]', function() {
                calculateCredits();
            });

            // Inline images count slider - Update display and cost in real-time
            $(document).on('input', '#panel-inline-count-slider', function() {
                const count = parseInt($(this).val()) || 1;
                const cost = count * 0.5;
                $('#panel-inline-count-value').text(count + ' images');
                $('#panel-inline-count-cost').text(count + ' × 0.5 = ' + cost.toFixed(1) + ' credits');
                $('#panel-inline-cost').text('+' + cost.toFixed(1));
                calculateCredits(); // Recalculate total
            });

            // Load Projects and Personas on panel open
            function loadProjectsAndPersonas() {
                // Load Projects
                $.ajax({
                    url: wisewandCalendar.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'wisewand_get_projects',
                        nonce: wisewandCalendar.nonce
                    },
                    success: function(response) {
                        if (response.success && response.data.projects) {
                            const $select = $('#project-select');
                            $select.html('<option value="">No Project (Use Default)</option>');

                            response.data.projects.forEach(function(project) {
                                const option = `<option value="${project.id}">${project.name}${project.website ? ' (' + project.website + ')' : ''}</option>`;
                                $select.append(option);
                            });

                            // Restore selected value if exists
                            const currentProject = $select.data('current-value');
                            if (currentProject) {
                                $select.val(currentProject);
                            }
                        }
                    }
                });

                // Load Personas
                $.ajax({
                    url: wisewandCalendar.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'wisewand_get_personas',
                        nonce: wisewandCalendar.nonce
                    },
                    success: function(response) {
                        if (response.success && response.data.personas) {
                            const $select = $('#persona-select');
                            $select.html('<option value="">Select Persona...</option>');

                            response.data.personas.forEach(function(persona) {
                                const option = `<option value="${persona.id}">${persona.name}${persona.description ? ' - ' + persona.description : ''}</option>`;
                                $select.append(option);
                            });

                            // Restore selected value if exists
                            const currentPersona = $select.data('current-value');
                            if (currentPersona) {
                                $select.val(currentPersona);
                            }
                        }
                    }
                });
            }

            // Trigger loading when panel opens and initialize CTA counter
            let panelInitialized = false;
            setInterval(function() {
                if ($('#project-select').length && !panelInitialized) {
                    panelInitialized = true;
                    loadProjectsAndPersonas();
                    updateCTANumbers();
                    calculateCredits(); // Initialize credit calculator

                    // Reset flag when panel closes
                    setTimeout(function() {
                        if (!$('#project-select').length) {
                            panelInitialized = false;
                        }
                    }, 1000);
                }
            }, 500);
    }); // End jQuery(document).ready()
