jQuery(document).ready(function($) {
    var $list = $('.qcld-faq-data-sortable-list');
    var template = $('#qcld-faq-data-template').html();

    // 1. Tab Navigation Controller Interface
    $('.qcld-faq-data-tabs').on('click', 'a[data-tab]', function(e) {
        e.preventDefault();
        var targetTab = $(this).data('tab');

        $('.qcld-faq-data-tabs .nav-tab').removeClass('nav-tab-active');
        $(this).addClass('nav-tab-active');

        $('.qcld-faq-data-tab-content').removeClass('qcld-faq-data-tab-active-content').hide();
        $('#faq-tab-' + targetTab).addClass('qcld-faq-data-tab-active-content').show();

        if (targetTab === 'json') {
            generateJsonLdPreview();
        }
    });

    // 2. Dynamic Component Repeater Framework Instantiation
    if ($list.length && $.fn.sortable) {
        $list.sortable({
            handle: '.qcld-faq-data-drag-handle',
            placeholder: 'qcld-faq-data-row-placeholder',
            axis: 'y',
            opacity: 0.75,
            update: function() { generateJsonLdPreview(); }
        });
    }

    $('#qcld-faq-data-add-row').on('click', function(e) {
        e.preventDefault();
        var $newRow = $(template);
        $list.append($newRow);
        $newRow.hide().slideDown(300);
    });

    $list.on('click', '.qcld-faq-data-remove-btn', function(e) {
        e.preventDefault();
        var $row = $(this).closest('.qcld-faq-data-row');
        $row.fadeOut(200, function() {
            $row.remove();
            generateJsonLdPreview();
        });
    });

    // Fire real-time preview refreshes on input change events
    $(document).on('input propertychange change', '.faq-input-sync', function() {
        if ($('#faq-tab-json').is(':visible')) {
            generateJsonLdPreview();
        }
    });

    // 3. Automated Interactive JSON-LD Preview Compilation Block Builder
    function generateJsonLdPreview() {
        var graph = [];
        
        // Match custom manual inputs or use localized defaults
        var customTitle = $('#qcld_faq_data_webpage_title').val();
        var finalTitle = customTitle ? customTitle : (typeof faqMagicContext !== 'undefined' ? faqMagicContext.pageTitle : '');

        var customDesc = $('#qcld_faq_data_webpage_desc').val();
        var finalDesc = customDesc ? customDesc : (typeof faqMagicContext !== 'undefined' ? faqMagicContext.defaultDesc : '');

        // Base Document Object Structure Template Context Mapping Definition
        var webPageSchema = {
            "@type": "WebPage",
            "@id": typeof faqMagicContext !== 'undefined' ? faqMagicContext.pageUrl : '',
            "url": typeof faqMagicContext !== 'undefined' ? faqMagicContext.pageUrl : '',
            "name": finalTitle,
            "description": finalDesc
        };

        var licenseUrl = $('#qcld_faq_data_webpage_license').val();
        if (licenseUrl) { webPageSchema["license"] = licenseUrl; }

        graph.push(webPageSchema);

        // Map and extract existing items from standard dynamic question data loops
        var faqItems = [];
        $('.qcld-faq-data-row').each(function() {
            var q = $(this).find('input[name="qcld_faq_data_questions[]"]').val();
            var a = $(this).find('textarea[name="qcld_faq_data_answers[]"]').val();
            
            if (q || a) {
                faqItems.push({
                    "@type": "Question",
                    "name": q || "",
                    "acceptedAnswer": {
                        "@type": "Answer",
                        "text": a || ""
                    }
                });
            }
        });

        if (faqItems.length > 0) {
            graph.push({
                "@type": "FAQPage",
                "@id": (typeof faqMagicContext !== 'undefined' ? faqMagicContext.pageUrl : '') + "#faq",
                "mainEntity": faqItems
            });
        }

        var fullSchemaJson = {
            "@context": "https://schema.org",
            "@graph": graph
        };

        $('#qcld-faq-data-json-preview').text(JSON.stringify(fullSchemaJson, null, 4));
    }

    // 5. Dynamic AI UI Visibility Controller
    $('input[name="qcld_faq_ai_source"]').on('change', function() {
        var source = $(this).val();
        if (source === 'content') {
            $('#qcld-faq-ai-prompt-wrap').slideUp(200);
        } else {
            $('#qcld-faq-ai-prompt-wrap').slideDown(200);
        }
    });

    // 4. AI FAQ Generation Engine
    $('#qcld-faq-generate-ai-btn').on('click', function(e) {
        e.preventDefault();
        var $btn = $(this);
        var $spinner = $btn.find('.qcld-spin');
        var $feedback = $('#qcld-faq-ai-feedback');
        var source = $('input[name="qcld_faq_ai_source"]:checked').val();
        var provider = $('input[name="qcld_faq_ai_provider"]:checked').val() || 'openai';
        var prompt = $('#qcld_faq_ai_prompt').val();
        var count = $('#qcld_faq_ai_count').val();
        var pageContent = '';

        if (source === 'content') {
            // Attempt to get content from Gutenberg
            if (typeof wp !== 'undefined' && wp.data && wp.data.select('core/editor')) {
                pageContent = wp.data.select('core/editor').getEditedPostContent();
            } 
            // Fallback to Classic Editor (TinyMCE)
            else if (typeof tinyMCE !== 'undefined' && tinyMCE.activeEditor) {
                pageContent = tinyMCE.activeEditor.getContent();
            } 
            // Fallback to standard textarea
            else {
                pageContent = $('#content').val();
            }

            if (!pageContent || pageContent.length < 50) {
                alert('Please ensure you have entered some content in the editor first so the AI can analyze it.');
                return;
            }
        } else if (!prompt) {
            alert('Please enter a topic or prompt.');
            return;
        }

        $btn.prop('disabled', true);
        $spinner.show();
        $feedback.html('<span style="color: #4f46e5;">Generating your FAQs, please wait...</span>');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'qcld_faq_generate_ai',
                security: typeof faqMagicContext !== 'undefined' ? faqMagicContext.nonce : '',
                provider: provider,
                prompt: prompt,
                count: count,
                page_content: pageContent
            },
            success: function(response) {
                $btn.prop('disabled', false);
                $spinner.hide();

                if (response.success) {
                    var items = response.data;
                    
                    // Normalize items to an array if it's an object or wrapped
                    if (!Array.isArray(items)) {
                        if (items && items.faq && Array.isArray(items.faq)) {
                            items = items.faq;
                        } else if (items && items.faqs && Array.isArray(items.faqs)) {
                            items = items.faqs;
                        } else if (items && typeof items === 'object') {
                            items = Object.values(items);
                        }
                    }

                    if (Array.isArray(items)) {
                        items.forEach(function(item) {
                            var q = item.question || item.q || item.title || "";
                            var a = item.answer || item.a || item.desc || item.description || "";
                            if (q || a) {
                                var $newRow = $(template);
                                $newRow.find('input[name="qcld_faq_data_questions[]"]').val(q);
                                $newRow.find('textarea[name="qcld_faq_data_answers[]"]').val(a);
                                $list.append($newRow);
                                $newRow.show();
                            }
                        });
                        $feedback.html('<span style="color: #10b981;">Successfully generated ' + items.length + ' FAQ items!</span>');
                        
                        // Switch to the FAQs tab to show the new items
                        $('a[data-tab="faqs"]').trigger('click');
                    } else {
                        $feedback.html('<span style="color: #ef4444;">Error: AI returned an unrecognized format.</span>');
                    }
                } else {
                    $feedback.html('<span style="color: #ef4444;">Error: ' + (response.data && response.data.message ? response.data.message : 'Unknown error') + '</span>');
                }
            },
            error: function() {
                $btn.prop('disabled', false);
                $spinner.hide();
                $feedback.html('<span style="color: #ef4444;">Connection error. Please check your console.</span>');
            }
        });
    });
});
