/**
 * AYSA Schema Generator - Frontend Implementation
 * Generates Schema.org JSON-LD markup based on entity type
 */

// Helper functions for schema generation
function getPageTitleFromUrl(url) {
    const currentRow = jQuery(`tr[data-page-type] a[href="${url}"]`).closest('tr');
    if (currentRow.length) {
        return currentRow.find('.aysa-page-title').text() || url;
    }
    return url;
}

function getPageDescriptionFromUrl(url) {
    // Try to get actual meta description from WordPress
    return new Promise((resolve) => {
        jQuery.ajax({
            url: aysaSchemaAjax.ajaxurl,
            method: 'POST',
            data: {
                action: 'aysa_get_page_meta',
                nonce: aysaSchemaAjax.nonce,
                url: url
            },
            dataType: 'json'
        })
        .done(function(result) {
            if (result.success && result.data) {
                resolve(result.data.description || `Learn more about ${getPageTitleFromUrl(url)} on our website.`);
            } else {
                resolve(`Learn more about ${getPageTitleFromUrl(url)} on our website.`);
            }
        })
        .fail(function() {
            resolve(`Learn more about ${getPageTitleFromUrl(url)} on our website.`);
        });
    });
}

function detectFAQContent(pageUrl) {
    const faqElements = document.querySelectorAll('[itemscope][itemtype="https://schema.org/FAQPage"]');
    
    if (faqElements.length === 0) {
        return {
            found: false,
            count: 0,
            schema: null
        };
    }
    
    console.log('🔍 FAQ content detected, extracting questions and answers');
    
    const faqQuestions = [];
    faqElements.forEach(faqElement => {
        const questions = faqElement.querySelectorAll('[itemscope][itemtype="https://schema.org/Question"]');
        questions.forEach(questionElement => {
            const questionName = questionElement.querySelector('[itemprop="name"]');
            const answerElement = questionElement.querySelector('[itemscope][itemtype="https://schema.org/Answer"] [itemprop="text"]');
            
            if (questionName && answerElement) {
                faqQuestions.push({
                    "@type": "Question",
                    "name": questionName.textContent.trim(),
                    "acceptedAnswer": {
                        "@type": "Answer",
                        "text": answerElement.textContent.trim()
                    }
                });
            }
        });
    });
    
    const faqSchema = faqQuestions.length > 0 ? {
        "@type": "FAQPage",
        "@id": `${pageUrl}#faq`,
        "mainEntity": faqQuestions
    } : null;
    
    return {
        found: faqQuestions.length > 0,
        count: faqQuestions.length,
        schema: faqSchema
    };
}

function generateSchemaForType(type, pageData) {
    const baseUrl = pageData.siteUrl;
    const logoUrl = pageData.logoUrl || `${baseUrl}/wp-content/uploads/logo.png`;
    
    // Common elements for all schema types (following documentation guidelines)
    const organization = {
        "@type": "Organization",
        "@id": `${baseUrl}/#org`,
        "name": pageData.companyName,
        "url": baseUrl,
        "logo": {
            "@type": "ImageObject",
            "url": logoUrl
        }
    };
    
    const website = {
        "@type": "WebSite",
        "@id": `${baseUrl}/#website`,
        "url": baseUrl,
        "name": pageData.companyName,
        "publisher": {"@id": `${baseUrl}/#org`},
        "potentialAction": {
            "@type": "SearchAction",
            "target": `${baseUrl}/?s={search_term_string}`,
            "query-input": "required name=search_term_string"
        }
    };
    
    const breadcrumbs = {
        "@type": "BreadcrumbList",
        "@id": `${pageData.url}#breadcrumbs`,
        "itemListElement": [
            {
                "@type": "ListItem",
                "position": 1,
                "name": "Acasă",
                "item": baseUrl
            },
            {
                "@type": "ListItem",
                "position": 2,
                "name": pageData.title,
                "item": pageData.url
            }
        ]
    };
    
    // Auto-detect FAQ content in the page
    const faqData = detectFAQContent(pageData.url);
    let faqSchema = faqData.schema;
    
    let specificSchema = {};
    
    // Generate specific schema based on exact entity type (following documentation)
    switch(type.toLowerCase()) {
            case 'product':
                // Use real product data if available
                const productPrice = pageData.productPrice || "0.00";
                const productCurrency = pageData.productCurrency || "RON";
                const productSku = pageData.productSku || ("SKU-" + Date.now());
                const productAvailability = pageData.productAvailability || "https://schema.org/InStock";
                const productImages = pageData.productImages && pageData.productImages.length > 0 ? pageData.productImages : [logoUrl];
                
                console.log('🛒 Product Schema Data:', {
                    price: productPrice,
                    currency: productCurrency,
                    sku: productSku,
                    availability: productAvailability,
                    images: productImages
                });
                
                specificSchema = {
                    "@type": "Product",
                    "@id": `${pageData.url}#product`,
                    "name": pageData.title,
                    "description": pageData.description,
                    "sku": productSku,
                    "brand": {
                        "@type": "Brand",
                        "name": pageData.companyName
                    },
                    "image": productImages,
                    "offers": {
                        "@type": "Offer",
                        "url": pageData.url,
                        "priceCurrency": productCurrency,
                        "price": productPrice,
                        "priceValidUntil": "2025-12-31",
                        "availability": productAvailability,
                        "itemCondition": "https://schema.org/NewCondition",
                        "seller": {"@id": `${baseUrl}/#org`}
                    }
                };
                break;
            
        case 'article':
        case 'post':
            specificSchema = {
                "@type": "BlogPosting",
                "@id": `${pageData.url}#post`,
                "mainEntityOfPage": {
                    "@type": "WebPage",
                    "@id": pageData.url
                },
                "headline": pageData.title,
                "description": pageData.description,
                "image": {
                    "@type": "ImageObject",
                    "url": logoUrl,
                    "width": 1200,
                    "height": 630
                },
                "datePublished": pageData.currentDate,
                "dateModified": pageData.currentDate,
                "author": {
                    "@type": "Person",
                    "name": "Admin"
                },
                "publisher": {"@id": `${baseUrl}/#org`}
            };
            break;
            
        case 'category':
        case 'tag':
        case 'collectionpage':
            specificSchema = {
                "@type": "CollectionPage",
                "@id": `${pageData.url}#page`,
                "name": pageData.title,
                "url": pageData.url,
                "isPartOf": {"@id": `${baseUrl}/#website`}
            };
            break;
            
        // FAQ schema is now auto-detected from content, no manual case needed
            
        case 'webpage':
        case 'page':
        default:
            specificSchema = {
                "@type": "WebPage",
                "@id": `${pageData.url}#webpage`,
                "url": pageData.url,
                "name": pageData.title,
                "isPartOf": {"@id": `${baseUrl}/#website`},
                "about": [
                    {
                        "@type": "Thing",
                        "name": pageData.description
                    }
                ]
            };
            break;
    }
    
    // Build the @graph array
    const graphElements = [
        organization,
        website,
        breadcrumbs,
        specificSchema
    ];
    
    // Add FAQ schema if detected
    if (faqSchema) {
        graphElements.push(faqSchema);
        console.log('✅ FAQ schema added to @graph');
    }
    
    return {
        "@context": "https://schema.org",
        "@graph": graphElements
    };
}

function displaySchemaResult(schema, url, type) {
    const formattedJSON = JSON.stringify(schema, null, 2);
    
    // Remove existing modal if present
    jQuery('#aysa-schema-result-modal, #aysa-schema-result-overlay').remove();
    
    jQuery('body').append(`
        <div id="aysa-schema-result-modal" style="
            position: fixed; top: 50%; left: 50%; 
            transform: translate(-50%, -50%); 
            background: white; padding: 20px; 
            border: 2px solid #28a745; 
            border-radius: 8px; 
            box-shadow: 0 4px 20px rgba(0,0,0,0.3);
            z-index: 10001;
            max-width: 90%;
            max-height: 90%;
            overflow-y: auto;
        ">
            <h3>🎉 Generated Schema.org JSON-LD</h3>
            <p><strong>URL:</strong> ${url}</p>
            <p><strong>Type:</strong> ${type}</p>
            <pre style="background: #f4f4f4; padding: 15px; border-radius: 4px; overflow-x: auto; font-size: 12px; max-height: 400px; overflow-y: auto;">${formattedJSON}</pre>
            <div style="margin-top: 15px; text-align: right;">
                <button id="insert-schema-btn" style="background: #28a745; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; margin-right: 10px;">🚀 Insert into Page</button>
                <button id="copy-schema-btn" style="background: #0073aa; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; margin-right: 10px;">📋 Copy to Clipboard</button>
                <button id="close-schema-result" style="background: #666; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer;">✕ Close</button>
            </div>
        </div>
        <div id="aysa-schema-result-overlay" style="
            position: fixed; top: 0; left: 0; 
            width: 100%; height: 100%; 
            background: rgba(0,0,0,0.5); 
            z-index: 10000;
        "></div>
    `);
    
    // Insert schema functionality
    jQuery('#insert-schema-btn').click(function() {
        const button = jQuery(this);
        const originalText = button.text();
        button.text('🔄 Inserting...').prop('disabled', true);
        
        // Use WordPress AJAX to insert schema
        jQuery.ajax({
            url: aysaSchemaAjax.ajaxurl,
            method: 'POST',
            data: {
                action: 'aysa_insert_schema',
                nonce: aysaSchemaAjax.nonce,
                url: url,
                schemaType: type,
                schemaData: formattedJSON,
                replaceExisting: 'true'
            },
            dataType: 'json'
        })
        .done(function(result) {
            if (result.success) {
                button.text('✅ Inserted!').css('background', '#28a745');
                        console.log('🎉 Schema successfully inserted into page!');
                
                // Update table status
                const targetRow = jQuery(`tr[data-page-type] a[href="${url}"]`).closest('tr');
                if (targetRow.length) {
                    const schemaTypeLabel = String(type || 'webpage')
                        .toLowerCase()
                        .split(/[-_]/g)
                        .filter(Boolean)
                        .map(part => part.charAt(0).toUpperCase() + part.slice(1))
                        .join(' ');
                    targetRow.find('.aysa-status-label')
                        .removeClass('error')
                        .addClass('success')
                        .html('<span class="dashicons dashicons-yes-alt" style="color: #46b450; font-size: 16px; vertical-align: middle;"></span>Schema Active (' + schemaTypeLabel + ')');
                    targetRow.find('.aysa-add-schema').text('Update Schema');
                }
                
                // Close modal after success
                setTimeout(() => {
                    jQuery('#aysa-schema-result-modal, #aysa-schema-result-overlay').remove();
                }, 2000);
            } else {
                button.text('❌ Failed').css('background', '#dc3545');
                console.error('❌ Failed to insert schema: ' + (result.data || 'Unknown error'));
            }
        })
        .fail(function(xhr, status, error) {
            button.text('❌ Error').css('background', '#dc3545');
            console.error('❌ Network error: ' + error);
        })
        .always(function() {
            setTimeout(() => {
                button.text(originalText).css('background', '#28a745').prop('disabled', false);
            }, 3000);
        });
    });
    
    // Copy to clipboard functionality
    jQuery('#copy-schema-btn').click(function() {
        navigator.clipboard.writeText(formattedJSON).then(() => {
            const button = jQuery(this);
            const originalText = button.text();
            button.text('✅ Copied!');
            setTimeout(() => {
                button.text(originalText);
            }, 2000);
        });
    });
    
    // Close modal
    jQuery('#close-schema-result, #aysa-schema-result-overlay').click(function() {
        jQuery('#aysa-schema-result-modal, #aysa-schema-result-overlay').remove();
    });
    
    jQuery('#aysa-schema-result-modal, #aysa-schema-result-overlay').show();
}

        function detectSchemaType(url, originalType) {
            // This function is now deprecated - real detection happens in backend
            // Keep for backward compatibility but will be overridden by AJAX response
            console.log('⚠️ detectSchemaType is deprecated - using real entity detection from backend');
            
            // Fallback mapping for old originalType values
            if (originalType === 'CollectionPage') return 'category';
            if (originalType === 'Article' || originalType === 'BlogPosting') return 'article';
            if (originalType === 'Product') return 'product';
            
            return 'webpage'; // Default fallback
        }

function openSchemaModal(url, type, title) {
    // Will detect real entity type via AJAX call below
    let detectedType = 'webpage'; // Default fallback
    
    if (!jQuery('#aysa-simple-schema-modal').length) {
        const modalHtml = `
            <div id="aysa-simple-schema-modal" class="aysa-modal-overlay" style="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:10000;display:none;align-items:center;justify-content:center;">
                <div class="aysa-modal-content" style="background:#fff;border-radius:10px;box-shadow:0 20px 60px rgba(15,23,42,0.18);width:95%;max-width:540px;overflow:hidden;font-family:'Segoe UI',sans-serif;">
                    <div class="aysa-modal-header" style="display:flex;justify-content:space-between;align-items:center;padding:20px 24px;border-bottom:1px solid #eaeef3;background:linear-gradient(135deg,#2563eb,#1d4ed8);color:#fff;">
                        <h3 style="margin:0;font-size:18px;font-weight:600;">Generate Schema.org Markup</h3>
                        <button type="button" class="aysa-close-modal" style="background:rgba(255,255,255,0.15);border:none;border-radius:50%;width:32px;height:32px;color:#fff;font-size:18px;cursor:pointer;display:flex;align-items:center;justify-content:center;">×</button>
                    </div>
                    <div class="aysa-modal-body" style="padding:24px;">
                        <div class="aysa-form-group" style="margin-bottom:18px;">
                            <label for="aysa-modal-url" style="display:block;font-weight:600;font-size:13px;color:#1f2937;margin-bottom:6px;">Page URL</label>
                            <input type="text" id="aysa-modal-url" class="aysa-modal-input" style="width:100%;padding:12px;border:1px solid #d1d9e6;border-radius:6px;background:#f9fbfd;color:#374151;">
                        </div>
                        <div class="aysa-form-group" style="margin-bottom:18px;">
                            <label for="aysa-modal-type" style="display:block;font-weight:600;font-size:13px;color:#1f2937;margin-bottom:6px;">Schema Type</label>
                            <select id="aysa-modal-type" class="aysa-modal-input" style="width:100%;padding:12px;border:1px solid #d1d9e6;border-radius:6px;background:#fff;color:#374151;">
                        <option value="webpage">Web Page</option>
                        <option value="article">Article / Blog Post</option>
                        <option value="product">Product</option>
                        <option value="collectionpage">Collection / Category</option>
                            </select>
                        </div>
                        <div class="aysa-form-group" style="margin-bottom:18px;">
                            <label for="aysa-schema-modal-title" style="display:block;font-weight:600;font-size:13px;color:#1f2937;margin-bottom:6px;">Page Title</label>
                            <input type="text" id="aysa-schema-modal-title" class="aysa-modal-input" style="width:100%;padding:12px;border:1px solid #d1d9e6;border-radius:6px;color:#374151;">
                        </div>
                        <div class="aysa-form-group" style="margin-bottom:18px;">
                            <label for="aysa-modal-description" style="display:block;font-weight:600;font-size:13px;color:#1f2937;margin-bottom:6px;">Page Description</label>
                            <textarea id="aysa-modal-description" rows="3" class="aysa-modal-input" style="width:100%;padding:12px;border:1px solid #d1d9e6;border-radius:6px;color:#374151;resize:vertical;background:#fff;"></textarea>
                        </div>
                        <div class="aysa-form-group" style="margin-bottom:18px;">
                            <label for="aysa-modal-company" style="display:block;font-weight:600;font-size:13px;color:#1f2937;margin-bottom:6px;">Company / Organization Name</label>
                            <input type="text" id="aysa-modal-company" class="aysa-modal-input" style="width:100%;padding:12px;border:1px solid #d1d9e6;border-radius:6px;color:#374151;background:#fff;">
                        </div>
                        <div class="aysa-form-group" style="margin-bottom:0;">
                            <label style="display:block;font-weight:600;font-size:13px;color:#1f2937;margin-bottom:6px;">FAQ Detection</label>
                            <div id="aysa-faq-status" style="padding:10px;border-radius:6px;font-size:13px;font-weight:500;">
                                <span id="aysa-faq-icon">🔍</span> <span id="aysa-faq-text">Checking for FAQ content...</span>
                            </div>
                        </div>
                    </div>
                    <div class="aysa-modal-footer" style="padding:18px 24px;border-top:1px solid #eaeef3;display:flex;justify-content:flex-end;gap:12px;background:#f9fbfd;">
                        <button type="button" class="aysa-close-modal" style="padding:10px 18px;border:1px solid #cbd5f5;border-radius:6px;background:#fff;color:#1d4ed8;font-weight:600;cursor:pointer;">Cancel</button>
                        <button type="button" id="aysa-modal-generate" style="padding:10px 18px;border:none;border-radius:6px;background:linear-gradient(135deg,#2563eb,#1d4ed8);color:#fff;font-weight:600;cursor:pointer;display:flex;align-items:center;gap:8px;">Generate Schema</button>
                    </div>
                </div>
            </div>`;
        jQuery('body').append(modalHtml);

                jQuery(document).on('click', '.aysa-close-modal', function() {
                    jQuery('#aysa-simple-schema-modal').fadeOut(150);
                });

                jQuery(document).on('click', '#aysa-simple-schema-modal', function(e) {
                    if (e.target.id === 'aysa-simple-schema-modal') {
                        jQuery('#aysa-simple-schema-modal').fadeOut(150);
                    }
                });
                
                // Track manual schema type changes
                jQuery(document).on('change', '#aysa-modal-type', function() {
                    const selectedType = jQuery(this).val();
                    console.log('👤 User manually changed schema type to:', selectedType);
                });

                jQuery(document).on('click', '#aysa-modal-generate', function() {
                    const button = jQuery(this);
                    const originalText = button.text();
                    button.text('🔄 Generating...').prop('disabled', true);
                    
                    const urlValue = jQuery('#aysa-modal-url').val().trim();
                    const typeValue = jQuery('#aysa-modal-type').val(); // User's selected type (may be manually changed)
                    const titleValue = jQuery('#aysa-schema-modal-title').val().trim();
                    const descriptionValue = jQuery('#aysa-modal-description').val().trim();
                    const companyValue = jQuery('#aysa-modal-company').val().trim() || aysaSchemaAjax.siteName;

                    if (!urlValue || !typeValue) {
                        console.error('Please provide both the URL and the schema type.');
                        button.text(originalText).prop('disabled', false);
                        return;
                    }

                    console.log('🎯 User selected schema type:', typeValue, '(respecting manual selection)');

                    // Use async description if not provided
                    const descPromise = descriptionValue ? 
                        Promise.resolve(descriptionValue) : 
                        getPageDescriptionFromUrl(urlValue);

                    descPromise.then(description => {
                        // Get the original AJAX response data to preserve product data
                        const originalPageData = jQuery('#aysa-modal-url').data('originalPageData') || {};
                        
                        const pageData = {
                            url: urlValue,
                            type: typeValue, // Use user's selected type
                            title: titleValue || getPageTitleFromUrl(urlValue),
                            description: description,
                            companyName: companyValue,
                            siteUrl: aysaSchemaAjax.siteUrl,
                            logoUrl: aysaSchemaAjax.logoUrl,
                            currentDate: new Date().toISOString().split('T')[0],
                            // Preserve product data if available (even if user changed schema type)
                            productPrice: originalPageData.productPrice,
                            productCurrency: originalPageData.productCurrency,
                            productSku: originalPageData.productSku,
                            productAvailability: originalPageData.productAvailability,
                            productImages: originalPageData.productImages
                        };

                        try {
                            const schema = generateSchemaForType(typeValue, pageData);
                            displaySchemaResult(schema, urlValue, typeValue);
                            jQuery('#aysa-simple-schema-modal').fadeOut(150);
                        } catch (error) {
                            console.error('Schema generation error:', error);
                            console.error('Failed to generate schema: ' + error.message);
                        } finally {
                            button.text(originalText).prop('disabled', false);
                        }
                    }).catch(error => {
                        console.error('Error getting description:', error);
                        button.text(originalText).prop('disabled', false);
                    });
                });
    }

    jQuery('#aysa-modal-url').val(url);
    
    // Get real page data from WordPress (including real entity type)
    jQuery.ajax({
        url: aysaSchemaAjax.ajaxurl,
        method: 'POST',
        data: {
            action: 'aysa_get_page_meta',
            nonce: aysaSchemaAjax.nonce,
            url: url
        },
        dataType: 'json'
    })
    .done(function(result) {
        console.log('🔍 Page Meta AJAX Response:', result);
        
        let finalTitle = '';
        let finalDescription = '';
        let realEntityType = 'webpage'; // Default
        
        if (result.success && result.data) {
            console.log('✅ Meta data received:', result.data);
            finalTitle = result.data.title || title || getPageTitleFromUrl(url);
            finalDescription = result.data.description || '';
            realEntityType = result.data.entity_type || 'webpage';
            
            console.log('📝 Setting title:', finalTitle);
            console.log('📝 Setting description:', finalDescription);
            console.log('🎯 Real entity type detected:', realEntityType);
            
            // Store original page data for later use (preserve product data even if user changes schema type)
            jQuery('#aysa-modal-url').data('originalPageData', result.data);
            
            // Map backend entity types to frontend schema types
            let schemaType = 'webpage';
            switch(realEntityType) {
                case 'product':
                    schemaType = 'product';
                    break;
                case 'article':
                    schemaType = 'article';
                    break;
                case 'category':
                    schemaType = 'collectionpage';
                    break;
                case 'webpage':
                default:
                    schemaType = 'webpage';
                    break;
            }
            
            // Set the correct schema type in dropdown (auto-detected, but user can change it)
            jQuery('#aysa-modal-type').val(schemaType);
            console.log('✅ Schema type auto-set to:', schemaType, '(user can override this)');
            
            // Set values directly like description works
            jQuery('#aysa-schema-modal-title').val(finalTitle);
            jQuery('#aysa-modal-description').val(finalDescription);
            console.log('✅ Title set to:', finalTitle);
            console.log('✅ Description set successfully');
        } else {
            console.log('❌ No meta data, using fallback');
            finalTitle = title || getPageTitleFromUrl(url);
            console.log('📝 Setting fallback title:', finalTitle);
            
            // Fallback to basic extraction
            jQuery('#aysa-schema-modal-title').val(finalTitle);
            jQuery('#aysa-modal-type').val('webpage'); // Default fallback
            getPageDescriptionFromUrl(url).then(description => {
                finalDescription = description;
                jQuery('#aysa-modal-description').val(description);
            });
        }
        
        // Open modal after data is loaded
        jQuery('#aysa-simple-schema-modal').fadeIn(150).css('display', 'flex');
        
        // Force set values after modal is fully rendered
        setTimeout(() => {
            console.log('🔄 FORCE setting values after modal render...');
            
            // Force set title exactly like description
            jQuery('#aysa-schema-modal-title').val(finalTitle);
            jQuery('#aysa-modal-description').val(finalDescription);
            
            console.log('🔄 FORCED Title to:', finalTitle);
            console.log('🔄 FORCED Description set');
            
            // Verify they were set
            console.log('🔍 Final verification - Title value:', jQuery('#aysa-schema-modal-title').val());
            console.log('🔍 Final verification - Description value:', jQuery('#aysa-modal-description').val());
        }, 300);
    })
    .fail(function(xhr, status, error) {
        console.error('❌ Page Meta AJAX failed:', { xhr, status, error });
        // Fallback to basic extraction
        const fallbackTitle = title || getPageTitleFromUrl(url);
        jQuery('#aysa-schema-modal-title').val(fallbackTitle);
        getPageDescriptionFromUrl(url).then(description => {
            jQuery('#aysa-modal-description').val(description);
        });
        
        // Open modal even if AJAX failed
        jQuery('#aysa-simple-schema-modal').fadeIn(150).css('display', 'flex');
    });
    
    jQuery('#aysa-modal-company').val(aysaSchemaAjax.companyName || aysaSchemaAjax.siteName);

    // Check for FAQ content and update indicator
    updateFAQIndicator(url);
}

function updateFAQIndicator(url) {
    const statusDiv = jQuery('#aysa-faq-status');
    const iconSpan = jQuery('#aysa-faq-icon');
    const textSpan = jQuery('#aysa-faq-text');
    
    // Set loading state
    statusDiv.css({
        'background': '#fef3c7',
        'border': '1px solid #f59e0b',
        'color': '#92400e'
    });
    iconSpan.text('🔍');
    textSpan.text('Checking for FAQ content...');
    
    // Check FAQ content via AJAX
    jQuery.ajax({
        url: aysaSchemaAjax.ajaxurl,
        method: 'POST',
        data: {
            action: 'aysa_check_faq_content',
            nonce: aysaSchemaAjax.nonce,
            url: url
        },
        dataType: 'json'
    })
    .done(function(result) {
        if (result.success && result.data.found) {
            // FAQ found - green styling
            statusDiv.css({
                'background': '#d1fae5',
                'border': '1px solid #10b981',
                'color': '#065f46'
            });
            iconSpan.text('✅');
            textSpan.text(`FAQ Found (${result.data.count} questions detected)`);
            console.log(`✅ FAQ detected: ${result.data.count} questions`);
        } else {
            // No FAQ - gray styling
            statusDiv.css({
                'background': '#f3f4f6',
                'border': '1px solid #9ca3af',
                'color': '#374151'
            });
            iconSpan.text('❌');
            textSpan.text('No FAQ content detected');
            console.log('❌ No FAQ content found');
        }
    })
    .fail(function() {
        // Error - red styling
        statusDiv.css({
            'background': '#fee2e2',
            'border': '1px solid #ef4444',
            'color': '#991b1b'
        });
        iconSpan.text('⚠️');
        textSpan.text('Error checking FAQ content');
        console.error('❌ Failed to check FAQ content');
    });
}

function attachSchemaButtons() {
    jQuery(document).on('click', '.aysa-add-schema', function(e) {
        e.preventDefault();
        const url = jQuery(this).data('url');
        const type = jQuery(this).data('type');
        const title = jQuery(this).data('title') || '';

        if (!url || !type) {
            console.error('Missing page data. Please refresh the page.');
            return;
        }

        openSchemaModal(url, type, title);
    });
}

attachSchemaButtons();

// Make functions available globally immediately
window.getPageTitleFromUrl = getPageTitleFromUrl;
window.getPageDescriptionFromUrl = getPageDescriptionFromUrl;
window.generateSchemaForType = generateSchemaForType;
window.displaySchemaResult = displaySchemaResult;

// Expose helpers globally
window.openSchemaModal = openSchemaModal;

// Debug log to confirm functions are loaded
console.log('✅ AYSA Schema Frontend functions loaded:', {
    getPageTitleFromUrl: typeof window.getPageTitleFromUrl,
    getPageDescriptionFromUrl: typeof window.getPageDescriptionFromUrl,
    generateSchemaForType: typeof window.generateSchemaForType,
    displaySchemaResult: typeof window.displaySchemaResult
});

// Also make them available when DOM is ready
jQuery(document).ready(function() {
    console.log('✅ AYSA Schema Frontend: DOM Ready - functions available');
    console.log('✅ Functions check:', {
        getPageTitleFromUrl: typeof window.getPageTitleFromUrl,
        generateSchemaForType: typeof window.generateSchemaForType,
        displaySchemaResult: typeof window.displaySchemaResult
    });
});
