/**
 * AYSA Scoring System - Complete Implementation Based on Google Docs Specification
 * Total: 100 points across 12 categories as per the official scoring guide
 * Updated to match the exact criteria and point allocations from the documentation
 */

// API Configuration
const AYSA_API_CONFIG = {
    baseUrl: (() => {
        const globalBase = window.AYSA_API_BASE_URL || (window.aysaApiConfig && window.aysaApiConfig.baseUrl);
        const resolved = (typeof globalBase === 'string' && globalBase.trim() !== '')
            ? globalBase.trim()
            : 'https://api.aysa.ai/';
        return resolved.replace(/\/$/, '');
    })(),
    endpoints: {
        pagespeed: '/api/pagespeed',
        technicalSeo: '/api/seo/technical',
        backlinks: '/api/backlinks'
    }
};

function buildAysaApiUrl(path) {
    const baseUrl = String(AYSA_API_CONFIG.baseUrl || 'https://api.aysa.ai').replace(/\/$/, '');
    const normalizedPath = String(path || '').replace(/^\/+/, '');
    return `${baseUrl}/${normalizedPath}`;
}

// Scoring Configuration - Updated to match Google Docs specification
const SCORING_CONFIG = {
    categories: {
        // Chapter 1 – Page Title (Meta Title) – 8 points
        metaTitle: {
            name: 'Page Title',
            maxScore: 8,
            criteria: {
                keywordAtStart: { name: 'Main keyword present at the beginning', maxScore: 3 },
                optimalLength: { name: 'Length between 50–60 characters', maxScore: 2.5 },
                uniqueTitle: { name: 'Unique title', maxScore: 2.5 }
            }
        },
        // Chapter 2 – Meta Description – 5 points
        metaDescription: {
            name: 'Meta Description',
            maxScore: 5,
            criteria: {
                optimalLength: { name: 'Length 150–160 characters', maxScore: 1.5 },
                keywordIncluded: { name: 'Keyword included naturally', maxScore: 1.5 },
                uniqueDescription: { name: 'Unique', maxScore: 2 }
            }
        },
        // Chapter 3 – URL (Slug) – 5 points
        url: {
            name: 'URL (Slug)',
            maxScore: 5,
            criteria: {
                keywordInUrl: { name: 'Keyword included', maxScore: 2 },
                seoFriendlyFormat: { name: 'SEO-friendly format', maxScore: 1.5 },
                shortDescriptive: { name: 'Short and descriptive', maxScore: 1.5 }
            }
        },
        // Chapter 4 – Headings (H1–H3) – 8 points
        headings: {
            name: 'Headings (H1–H3)',
            maxScore: 8,
            criteria: {
                singleH1: { name: 'Single correct H1', maxScore: 3 },
                h1HasKeyword: { name: 'H1 contains main keyword', maxScore: 2.5 },
                logicalStructure: { name: 'Logical H2, H3 structure', maxScore: 2.5 }
            }
        },
        // Chapter 5 – Content – 20 points
        content: {
            name: 'Content',
            maxScore: 20,
            criteria: {
                minWordCount: { name: 'Minimum 300 words', maxScore: 3 },
                keywordDensity: { name: 'Correct keyword density', maxScore: 3 },
                lsiTerms: { name: 'Synonyms and LSI terms', maxScore: 2 },
                formatting: { name: 'Lists, bold text, short paragraphs', maxScore: 2 },
                uniqueContent: { name: 'Unique content', maxScore: 3 },
                tldrPresent: { name: 'TL;DR present', maxScore: 2 },
                noKeywordLink: { name: 'No link on main keyword', maxScore: 2 },
                relevantLinks: { name: 'Relevant internal and external links', maxScore: 3 }
            }
        },
        // Chapter 6 – Images – 6 points
        images: {
            name: 'Images',
            maxScore: 6,
            criteria: {
                altTexts: { name: 'Each image has alt text', maxScore: 2 },
                seoFilenames: { name: 'SEO-friendly filename', maxScore: 1 },
                optimizedSize: { name: 'Optimized dimensions (<200kb)', maxScore: 2 },
                lazyLoading: { name: 'Lazy loading active (Images)', maxScore: 1 }
            }
        },
        // Chapter 7 – Internal Links – 4 points
        internalLinks: {
            name: 'Internal Links',
            maxScore: 4,
            criteria: {
                hasInternalLink: { name: 'At least one internal link', maxScore: 1.5 },
                functionalLinks: { name: 'Functional links (no 404)', maxScore: 1.5 },
                optimizedAnchor: { name: 'Optimized anchor text', maxScore: 1 }
            }
        },
        // Chapter 8 – External Links – 4 points (NEW)
        externalLinks: {
            name: 'External Links',
            maxScore: 4,
            criteria: {
                hasExternalLink: { name: 'At least one external link', maxScore: 2 },
                functionalExternal: { name: 'Links are functional', maxScore: 1 },
                authorityDomains: { name: 'Links to authority domains', maxScore: 1 }
            }
        },
        // Chapter 9 – Backlinks – 15 points (NEW)
        backlinks: {
            name: 'Backlinks',
            maxScore: 15,
            criteria: {
                domainBacklinks: { name: 'Backlinks to domain', maxScore: 7 },
                pageBacklinks: { name: 'Backlinks to page', maxScore: 6 },
                sourceQuality: { name: 'Source quality', maxScore: 2 }
            }
        },
        // Chapter 10 – Speed & Performance – 6 points
        performance: {
            name: 'Speed & Performance',
            maxScore: 6,
            criteria: {
                mobilePageSpeed: { name: 'PageSpeed > 80 on mobile', maxScore: 3 },
                minifiedAssets: { name: 'CSS/JS minified', maxScore: 2 },
                lazyLoadingActive: { name: 'Lazy loading active (Performance)', maxScore: 1 }
            }
        },
        // Chapter 11 – Mobile-Friendly – 4 points
        mobileFriendly: {
            name: 'Mobile-Friendly',
            maxScore: 4,
            criteria: {
                responsiveDesign: { name: 'Responsive (Google test OK)', maxScore: 2.5 },
                uiElements: { name: 'Correct UI elements (font, spacing, buttons)', maxScore: 1.5 }
            }
        },
        // Chapter 12 – Indexing & Technical SEO – 5 points
        technicalSeo: {
            name: 'Indexing & Technical SEO',
            maxScore: 5,
            criteria: {
                noUnwantedTags: { name: 'No unintentional noindex/nofollow tags', maxScore: 1.5 },
                canonicalTag: { name: 'Correct canonical tag', maxScore: 1.5 },
                schemaMarkup: { name: 'Valid Schema.org', maxScore: 1.5 },
                hreflang: { name: 'Correct hreflang (if multilingual versions exist)', maxScore: 0.5 }
            }
        }
    }
};

document.addEventListener('DOMContentLoaded', function() {
    console.log('📚 AYSA Scoring System - Google Docs Implementation v2.0');
    console.log('🎯 Total possible score: 100 points across 12 categories');
    console.log('📋 Categories:', Object.keys(SCORING_CONFIG.categories));
    
    // Initialize scoring system
    initScoringSystem();
    
    // Cache API results to avoid repeated calls
    let cachedApiResults = null;
    let lastContentHash = null; // Track content changes
    let scoringInProgress = false; // Prevent multiple simultaneous scoring runs
    let lastScoringTime = 0; // Debounce scoring calls
    let hasInitialScoringRun = false; // Track if initial scoring has already run
    
    // REMOVED: No more event listeners on field changes to prevent duplicate calls
    console.log('📋 Field change listeners DISABLED - scoring will only run on page refresh');
        
    // REMOVED: WordPress save detection to prevent duplicate calls
    console.log('💾 WordPress save detection DISABLED - scoring will only run on page refresh');
    
    // Add TinyMCE editor detection
    if (typeof tinymce !== 'undefined') {
        console.log('📝 Adding TinyMCE change detection...');
        
        // Wait for TinyMCE to initialize
        const checkTinyMCE = () => {
            if (tinymce.editors && tinymce.editors.length > 0) {
                tinymce.editors.forEach(editor => {
                    if (editor.id) {
                        console.log(`✅ Added TinyMCE listener to: ${editor.id}`);
                        
                        // REMOVED: TinyMCE change detection to prevent duplicate calls
                        console.log('📝 TinyMCE change detection DISABLED - scoring only on page refresh');
                    }
                });
            } else {
                setTimeout(checkTinyMCE, 1000); // Check again in 1 second
            }
        };
        
        setTimeout(checkTinyMCE, 2000); // Initial check after 2 seconds
    }
    
    // Function to generate hash from current content for change detection
    function generateContentHash() {
        const formData = getFormFieldData();
        const contentElements = [
            formData.mainKeyword,
            formData.metaTitle,
            formData.metaDescription,
            formData.metaKeywords,
            document.getElementById('title')?.value || '',
            getMainContent().substring(0, 1000) // First 1000 chars of content
        ];
        
        // Simple hash function
        return contentElements.join('|').length + '_' + 
               contentElements.join('').replace(/\s+/g, '').length;
    }
    
    // Function to check if content has changed
    function hasContentChanged() {
        const currentHash = generateContentHash();
        const changed = lastContentHash !== null && lastContentHash !== currentHash;
        lastContentHash = currentHash;
        return changed;
    }
    
    // Function to analyze with cached API results - OPTIMIZED to reduce calls
    async function analyzeAndScoreWithCache() {
        // Check if initial scoring has already run - prevent duplicate calls
        if (hasInitialScoringRun) {
            console.log('✅ Initial scoring already completed, skipping to prevent duplicates...');
            return;
        }
        
        // Prevent multiple simultaneous scoring runs
        if (scoringInProgress) {
            console.log('⏳ Scoring already in progress, skipping...');
            return;
        }
        
        // Stronger debounce for page initialization
        const now = Date.now();
        if (now - lastScoringTime < 5000) { // Increased from 1s to 5s
            console.log('⏳ Debouncing rapid scoring calls (5s minimum interval)...');
            return;
        }
        lastScoringTime = now;
        
        scoringInProgress = true;
        
        try {
            console.log('🚀 Running ONE-TIME scoring analysis...');
                const publicUrl = getEntityPublicUrl();
                console.log('🎯 Analyzing URL:', publicUrl);
                
                if (!isValidPublicUrl(publicUrl)) {
                    console.warn('⚠️ URL validation warning:', publicUrl);
                }
                
            // Run comprehensive analysis with API calls
            console.log('⚡ Starting comprehensive analysis with API calls...');
            
            // Single comprehensive run - API calls are made within each criterion function
                        await analyzeAndScore(null);
            
            console.log('✅ Comprehensive analysis completed (API calls made within each criterion)');
            
            // Mark as completed to prevent future calls
            hasInitialScoringRun = true;
            
            console.log('✅ ONE-TIME comprehensive scoring completed');
            
        } finally {
            scoringInProgress = false;
        }
    }
    
    // SINGLE timeout for initial scoring - no duplicates
    setTimeout(async () => {
        console.log('🚀 AYSA SEO System - ONE-TIME Initialization...');
        
        try {
            await analyzeAndScoreWithCache();
            console.log('✅ ONE-TIME initialization completed!');
        } catch (error) {
            console.error('❌ Initialization failed:', error);
        }
    }, 1500); // Single timeout after DOM is fully ready
    
    // Clean production code - test functions removed


    
    // REMOVED: Window focus and click listeners to prevent duplicate calls
    console.log('👀 Window focus and click listeners DISABLED - preventing duplicate scoring on tab switches');
    

    

    

    

    

    
    console.log('🎯 AYSA SEO Scoring System Ready - OPTIMIZED VERSION');
    console.log('📊 Total possible score: 100 points across 12 categories');
    console.log('⚡ OPTIMIZATION: Scoring runs ONLY ONCE per page load - no more duplicate API calls');
    console.log('🎯 AYSA SEO Scoring System Ready - Clean Production Version');
    

});

/**
 * Debounce function to prevent excessive API calls
 */
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

/**
 * Initialize the scoring system
 */
function initScoringSystem() {
    console.log('🚀 Initializing AYSA Real Data Scoring System...');
    
    // REMOVED: Tab switching listeners to prevent duplicate calls on tab changes
    console.log('📑 Tab switching listeners DISABLED - scoring runs only once on page load');
    
    // REMOVED: Active tab check to prevent duplicate calls
    console.log('🎯 Active tab detection DISABLED - scoring runs independently of tab state');
    
    console.log('✅ Real data scoring system initialized');
}

/**
 * Get the current content type
 */
function getContentType() {
    if (document.querySelector('.post-type-product') || document.body.classList.contains('single-product')) {
        return 'product';
    } else if (document.querySelector('.post-type-page') || document.body.classList.contains('page')) {
        return 'page';
    } else if (document.body.classList.contains('category') || document.body.classList.contains('tax-')) {
        return 'category';
    }
    return 'page'; // default
}

/**
 * Get the actual public URL for the current entity being edited
 * This extracts the real product/page URL, not the admin edit URL
 */
function getEntityPublicUrl() {
    try {
        console.log('🔍 Detecting entity public URL...');
        const baseUrl = window.location.origin;
        
        // Method 1: Try to get permalink from WordPress admin interface (most reliable)
        const permalinkEl = document.querySelector('#sample-permalink a');
        if (permalinkEl && permalinkEl.href && !permalinkEl.href.includes('/wp-admin/')) {
            console.log('📄 Found WordPress permalink:', permalinkEl.href);
            return cleanUrl(permalinkEl.href);
        }
        
        // Method 2: Try to get from "View" or "Preview" buttons
        const viewPostLink = document.querySelector('#view-post-btn a, .preview, a[href*="preview=true"]');
        if (viewPostLink && viewPostLink.href && !viewPostLink.href.includes('/wp-admin/')) {
            const cleanedUrl = viewPostLink.href
                .replace(/[?&]preview=true/g, '')
                .replace(/[?&]preview_id=\d+/g, '')
                .replace(/[?&]preview_nonce=[^&]+/g, '');
            console.log('📄 Found view/preview link:', cleanedUrl);
            return cleanUrl(cleanedUrl);
        }
        
        // Method 3: Try to construct from post data and WordPress REST API info
        const postId = getPostId();
        if (postId > 0) {
            // Try to get permalink from REST API if available
            if (typeof wp !== 'undefined' && wp.api) {
                // This would require WordPress REST API to be loaded
                console.log('📄 WordPress REST API available, but async call needed');
            }
            
            // Construct URL based on content type and available data
            const contentType = getContentType();
            const slug = getEntitySlug();
            
            if (slug) {
                let constructedUrl = baseUrl;
                
                // Get WordPress site structure hints
                const siteUrl = getSiteUrlFromDOM();
                if (siteUrl && siteUrl !== baseUrl) {
                    constructedUrl = siteUrl;
                }
                
                if (contentType === 'product') {
                    // Try to detect WooCommerce shop base
                    const shopBase = getWooCommerceProductBase();
                    constructedUrl += shopBase + slug + '/';
                } else if (contentType === 'page') {
                    // For pages, they're usually at root level unless there's a page hierarchy
                    const parentPageSlug = getParentPageSlug();
                    if (parentPageSlug) {
                        constructedUrl += '/' + parentPageSlug + '/' + slug + '/';
                    } else {
                        constructedUrl += '/' + slug + '/';
                    }
                } else {
                    // Default for posts
                    constructedUrl += '/' + slug + '/';
                }
                
                console.log('📄 Constructed URL:', constructedUrl);
                return cleanUrl(constructedUrl);
            }
        }
        
        // Method 4: Category/Taxonomy pages
        if (isTaxonomyPage()) {
            const taxonomyUrl = getTaxonomyPublicUrl();
            if (taxonomyUrl) {
                console.log('📄 Found taxonomy URL:', taxonomyUrl);
                return cleanUrl(taxonomyUrl);
            }
        }
        
        // Method 5: Last resort - try to get homepage URL and warn
        console.warn('⚠️ Could not determine specific entity URL');
        const homepageUrl = getHomepageUrl();
        if (homepageUrl && !homepageUrl.includes('/wp-admin/')) {
            console.log('📄 Using homepage as fallback:', homepageUrl);
            return cleanUrl(homepageUrl);
        }
        
        // Final fallback - clean current URL but warn
        console.error('❌ Unable to determine public URL, using current URL (may be admin URL)');
        return cleanUrl(window.location.href);
        
    } catch (error) {
        console.error('❌ Error getting entity public URL:', error);
        return cleanUrl(window.location.href);
    }
}

/**
 * Clean and validate URL
 */
function cleanUrl(url) {
    if (!url) return '';
    
    // Remove common WordPress admin parameters
    return url
        .replace(/[?&]action=edit/g, '')
        .replace(/[?&]post=\d+/g, '')
        .replace(/[?&]preview=true/g, '')
        .replace(/[?&]preview_id=\d+/g, '')
        .replace(/[?&]preview_nonce=[^&]+/g, '')
        .replace(/\?$/, '') // Remove trailing ?
        .replace(/\?&/, '?') // Fix malformed query strings
        .trim();
}

/**
 * Get site URL from DOM elements
 */
function getSiteUrlFromDOM() {
    // Try to get from WordPress admin bar
    const adminBarSiteLink = document.querySelector('#wp-admin-bar-site-name a');
    if (adminBarSiteLink && adminBarSiteLink.href) {
        return adminBarSiteLink.href.replace(/\/$/, ''); // Remove trailing slash
    }
    
    // Try to get from meta tags
    const canonicalLink = document.querySelector('link[rel="canonical"]');
    if (canonicalLink && canonicalLink.href) {
        const url = new URL(canonicalLink.href);
        return url.origin;
    }
    
    return window.location.origin;
}

/**
 * Get WooCommerce product base URL structure
 */
function getWooCommerceProductBase() {
    // Check if we can detect WooCommerce structure
    if (document.body.classList.contains('woocommerce') || 
        document.querySelector('.woocommerce') ||
        document.querySelector('.post-type-product')) {
        
        // Try to get from any existing product links in admin
        const productLinks = document.querySelectorAll('a[href*="/product/"]');
        if (productLinks.length > 0) {
            const firstLink = productLinks[0].href;
            const productMatch = firstLink.match(/.*?(\/product\/)/);
            if (productMatch) {
                return productMatch[1];
            }
        }
        
        // Default WooCommerce structure
        return '/product/';
    }
    
    // Fallback for custom post types
    return '/product/';
}

/**
 * Get parent page slug for hierarchical pages
 */
function getParentPageSlug() {
    const parentSelect = document.querySelector('#parent_id');
    if (parentSelect && parentSelect.value && parentSelect.value !== '0') {
        const selectedOption = parentSelect.querySelector(`option[value="${parentSelect.value}"]`);
        if (selectedOption && selectedOption.textContent) {
            // Convert parent page title to slug
            return selectedOption.textContent.toLowerCase()
                .replace(/[^a-z0-9\s-]/g, '')
                .replace(/\s+/g, '-')
                .replace(/-+/g, '-')
                .trim('-');
        }
    }
    return null;
}

/**
 * Check if current page is a taxonomy edit page
 */
function isTaxonomyPage() {
    return document.body.classList.contains('taxonomy') ||
           document.body.classList.contains('term-php') ||
           document.querySelector('#taxonomy') ||
           window.location.href.includes('term.php') ||
           window.location.href.includes('edit-tags.php');
}

/**
 * Get public URL for taxonomy/category pages
 */
function getTaxonomyPublicUrl() {
    const baseUrl = getSiteUrlFromDOM();
    
    // Get taxonomy type
    const taxonomyField = document.querySelector('#taxonomy');
    const taxonomy = taxonomyField ? taxonomyField.value : 'category';
    
    // Get term slug
    const slugField = document.querySelector('#slug');
    const nameField = document.querySelector('#name');
    
    let termSlug = '';
    if (slugField && slugField.value) {
        termSlug = slugField.value;
    } else if (nameField && nameField.value) {
        termSlug = nameField.value.toLowerCase()
            .replace(/[^a-z0-9\s-]/g, '')
            .replace(/\s+/g, '-')
            .replace(/-+/g, '-')
            .trim('-');
    }
    
    if (termSlug) {
        // Common taxonomy URL patterns
        if (taxonomy === 'product_cat') {
            return baseUrl + '/product-category/' + termSlug + '/';
        } else if (taxonomy === 'category') {
            return baseUrl + '/category/' + termSlug + '/';
        } else if (taxonomy === 'post_tag') {
            return baseUrl + '/tag/' + termSlug + '/';
        } else {
            // Generic taxonomy
            return baseUrl + '/' + taxonomy + '/' + termSlug + '/';
        }
    }
    
    return null;
}

/**
 * Get homepage URL
 */
function getHomepageUrl() {
    const siteUrl = getSiteUrlFromDOM();
    return siteUrl || window.location.origin;
}

/**
 * Validate that the URL is a proper public URL and not an admin URL
 */
function isValidPublicUrl(url) {
    if (!url || typeof url !== 'string') {
        return false;
    }
    
    // Check for admin-related patterns
    const adminPatterns = [
        '/wp-admin/',
        '/wp-content/plugins/',
        '/wp-content/themes/',
        'action=edit',
        'post.php',
        'term.php',
        'edit-tags.php',
        'admin.php',
        'preview=true',
        'preview_id=',
        'preview_nonce='
    ];
    
    const lowerUrl = url.toLowerCase();
    const hasAdminPattern = adminPatterns.some(pattern => lowerUrl.includes(pattern));
    
    if (hasAdminPattern) {
        console.log('🚫 URL validation failed - contains admin patterns:', url);
        return false;
    }
    
    // Check if URL looks like a proper public URL
    try {
        const urlObj = new URL(url);
        
        // Should have a proper domain
        if (!urlObj.hostname || urlObj.hostname === 'localhost' && urlObj.pathname.includes('/wp-admin/')) {
            return false;
        }
        
        // Should use http or https
        if (!['http:', 'https:'].includes(urlObj.protocol)) {
            return false;
        }
        
        console.log('✅ URL validation passed:', url);
        return true;
        
    } catch (error) {
        console.log('🚫 URL validation failed - invalid URL format:', url);
        return false;
    }
}

/**
 * Get the current post ID from various sources
 */
function getPostId() {
    // Try to get post ID from hidden field
    const postIdElement = document.querySelector('#post_ID');
    if (postIdElement && postIdElement.value) {
        return parseInt(postIdElement.value);
    }
    
    // Try to get from URL parameters
    const urlParams = new URLSearchParams(window.location.search);
    const postParam = urlParams.get('post');
    if (postParam) {
        return parseInt(postParam);
    }
    
    // Try to get from body classes
    const bodyClasses = document.body.className;
    const postIdMatch = bodyClasses.match(/postid-(\d+)/);
    if (postIdMatch) {
        return parseInt(postIdMatch[1]);
    }
    
    return 0;
}

/**
 * Get the entity slug from various sources
 */
function getEntitySlug() {
    // Try to get from permalink sample
    const permalinkEl = document.querySelector('#editable-post-name-full');
    if (permalinkEl) {
        return permalinkEl.textContent.trim();
    }
    
    // Try to get from name field
    const nameField = document.querySelector('#post_name');
    if (nameField && nameField.value) {
        return nameField.value;
    }
    
    // Try to get from title (convert to slug)
    const titleField = document.querySelector('#title, #aysa-entity-meta-title');
    if (titleField && titleField.value) {
        return titleField.value.toLowerCase()
            .replace(/[^a-z0-9\s-]/g, '')
            .replace(/\s+/g, '-')
            .replace(/-+/g, '-')
            .trim('-');
    }
    
    return null;
}

/**
 * Call the SEO API for advanced analysis with fallback to real data
 */
async function callSeoApi(url) {
    console.log('🔍 SEO API calls disabled - using DOM-based analysis only');
    console.log('🎯 Analyzing URL:', url || window.location.href);
    
    // Return null to force DOM-based analysis for all criteria
    // This eliminates API calls to PageSpeed and Technical SEO
    return null;
}

/**
 * PageSpeed API disabled - using DOM-based analysis only
 */
async function callPagespeedApi(url, strategy = 'mobile') {
    console.log(`🚫 PageSpeed API calls disabled - using DOM fallback for ${strategy}`);
    return null;
}

/**
 * Technical SEO API disabled - using DOM-based analysis only
 */
async function callTechnicalSeoApi(url) {
    console.log('🚫 Technical SEO API calls disabled - using DOM fallback');
    return null;
}

/**
 * Comprehensive SEO Analysis - Google Docs Implementation (100 points)
 * Analyzes all 12 categories with precise scoring as per documentation
 */
async function analyzeAndScore(apiResults = null) {
    console.log('🎯 Starting Comprehensive SEO Analysis - Google Docs v2.0...');
    
    const contentType = getContentType();
    console.log('📄 Content type:', contentType);
    console.log('🔍 API Results available:', !!apiResults);
    
    let totalScore = 0;
    let maxPossibleScore = 100; // Fixed total from Google Docs
    const categoryScores = {};

    // Analyze each category according to Google Docs specification
    const allCategories = Object.keys(SCORING_CONFIG.categories);
    console.log(`🏭 Analyzing ${allCategories.length} categories: ${allCategories.join(', ')}`);
    
    for (const [categoryKey, categoryConfig] of Object.entries(SCORING_CONFIG.categories)) {
        console.log(`\n📋 Analyzing Category: ${categoryConfig.name} (${categoryConfig.maxScore} points)`);
        
        const categoryScore = await analyzeCategoryComprehensive(categoryKey, categoryConfig, apiResults);
        categoryScores[categoryKey] = categoryScore;
        totalScore += categoryScore.totalScore;
        
        console.log(`✅ ${categoryConfig.name}: ${categoryScore.totalScore}/${categoryConfig.maxScore} points`);
        
        // Update UI for this category
        updateCategoryScoreDisplay(categoryKey, categoryScore);
    }

    const percentageScore = Math.round((totalScore / maxPossibleScore) * 100);
    console.log(`\n🎯 FINAL ANALYSIS COMPLETE:`);
    console.log(`📊 Total Score: ${totalScore}/${maxPossibleScore} points`);
    console.log(`🎯 Percentage: ${percentageScore}%`);
    console.log(`📈 Grade: ${getScoreGrade(percentageScore)}`);

    // Update total score displays
    updateTotalScoreDisplay(totalScore, percentageScore);
    updateScoreBox(percentageScore);
    
    // Force update of main score display elements
    const mainScoreElements = document.querySelectorAll('.score-text, .score-value');
    mainScoreElements.forEach(element => {
        if (element.classList.contains('score-text')) {
            element.textContent = (totalScore / 10).toFixed(1);
        } else if (element.classList.contains('score-value')) {
            element.textContent = (totalScore / 10).toFixed(1);
        }
    });
    console.log(`🎯 Force updated main score displays: ${(totalScore / 10).toFixed(1)}/10`);
    
    // Generate SEO conclusions
    generateComprehensiveConclusions(categoryScores, totalScore, percentageScore);
    
    console.log('✅ Google Docs SEO Analysis Complete!');
    return { totalScore, percentageScore, categoryScores };
}

/**
 * Analyze a complete category with all its criteria - Google Docs Implementation
 */
async function analyzeCategoryComprehensive(categoryKey, categoryConfig, apiResults = null) {
    console.log(`\n🏷️ Starting analysis of: ${categoryKey} (${categoryConfig.name})`);
    console.log(`  Max score: ${categoryConfig.maxScore}, Criteria: ${Object.keys(categoryConfig.criteria).join(', ')}`);
    
    const categoryScores = {
        categoryKey,
        categoryName: categoryConfig.name,
        maxScore: categoryConfig.maxScore,
        criteriaScores: {},
        totalScore: 0
    };

    // Get form field data once for all criteria
    const formData = getFormFieldData();
    
    // Analyze each criterion in the category
    for (const [criterionKey, criterionConfig] of Object.entries(categoryConfig.criteria)) {
        console.log(`  🔍 ${criterionConfig.name} (max: ${criterionConfig.maxScore})`);
        
        const result = await analyzeSingleCriterion(
            categoryKey, 
            criterionKey, 
            criterionConfig, 
            formData, 
            apiResults
        );
        
        console.log(`  📊 Result for ${categoryKey}.${criterionKey}: ${result}`);
        
        // Check if criterion is in development
        if (result && typeof result === 'object' && result.inDevelopment) {
            categoryScores.criteriaScores[criterionKey] = {
                name: criterionConfig.name,
                score: 0, // Nu contribuie la scorul total
                maxScore: result.maxScore,
                percentage: 0,
                inDevelopment: true,
                developmentText: result.text
            };
            console.log(`    🚧 Status: ${result.text}`);
        } else {
            const score = result || 0;
            categoryScores.criteriaScores[criterionKey] = {
                name: criterionConfig.name,
                score,
                maxScore: criterionConfig.maxScore,
                percentage: Math.round((score / criterionConfig.maxScore) * 100)
            };
            
            categoryScores.totalScore += score;
            console.log(`    ✅ Score: ${score}/${criterionConfig.maxScore}`);
        }
    }

    console.log(`🏁 Completed ${categoryKey}: ${categoryScores.totalScore}/${categoryConfig.maxScore}p`);
    console.log(`  Criteria results:`, Object.fromEntries(
        Object.entries(categoryScores.criteriaScores).map(([key, data]) => [key, `${data.score}/${data.maxScore}p`])
    ));

    return categoryScores;
}

/**
 * Analyze a single criterion according to Google Docs specifications
 */
async function analyzeSingleCriterion(categoryKey, criterionKey, criterionConfig, formData, apiResults) {
    // Exact list of criteria that should be 'in development'
    const inDevCriteria = [
        // ✅ ALL MAJOR CRITERIA NOW IMPLEMENTED!
        
        // Content - ✅ IMPLEMENTED with ChatGPT APIs
        // 'content.lsiTerms',              // ✅ IMPLEMENTED with ChatGPT
        // 'content.uniqueContent',         // ✅ IMPLEMENTED with ChatGPT  
        // 'content.relevantLinks',         // ✅ IMPLEMENTED with ChatGPT
        
        // Internal Links - ✅ IMPLEMENTED with API
        // 'internalLinks.hasInternalLink',    // ✅ IMPLEMENTED (simple logic)
        // 'internalLinks.functionalLinks',    // ✅ IMPLEMENTED with Links API
        // 'internalLinks.optimizedAnchor',    // ✅ IMPLEMENTED with ChatGPT
        
        // External Links - ✅ IMPLEMENTED with API  
        // 'externalLinks.hasExternalLink',    // ✅ IMPLEMENTED (simple logic)
        // 'externalLinks.functionalExternal', // ✅ IMPLEMENTED with Links API
        // 'externalLinks.authorityDomains',   // ✅ IMPLEMENTED with Links API
        
        // Backlinks - ✅ IMPLEMENTED with DataForSeo API
        // 'backlinks.domainBacklinks',        // ✅ IMPLEMENTED with Backlinks API
        // 'backlinks.pageBacklinks',          // ✅ IMPLEMENTED with Backlinks API  
        // 'backlinks.sourceQuality',          // ✅ IMPLEMENTED with Backlinks API
        
        // Speed & Performance - ✅ IMPLEMENTED with PageSpeed API
        // 'performance.mobilePageSpeed',      // ✅ IMPLEMENTED with Performance API
        // 'performance.minifiedAssets',       // ✅ IMPLEMENTED with Performance API
        
        // Mobile-Friendly - ✅ IMPLEMENTED with Mobile API
        // 'mobileFriendly.responsiveDesign',  // ✅ IMPLEMENTED with Mobile API
        // 'mobileFriendly.uiElements',        // ✅ IMPLEMENTED with Mobile API
        
        // Technical SEO - ✅ IMPLEMENTED with Technical API
        // 'technicalSeo.noUnwantedTags',      // ✅ IMPLEMENTED with Technical API
        // 'technicalSeo.canonicalTag',        // ✅ IMPLEMENTED with Technical API
        // 'technicalSeo.schemaMarkup',        // ✅ IMPLEMENTED with Technical API  
        // 'technicalSeo.hreflang'             // ✅ IMPLEMENTED with Technical API
        
        // 🎉 NO MORE "IN DEVELOPMENT" CRITERIA - ALL 100 POINTS IMPLEMENTED!
    ];
    
    // Note: ALL Content criteria now work with ChatGPT integration (minWordCount, keywordDensity, formatting, tldrPresent, noKeywordLink, lsiTerms, uniqueContent, relevantLinks)
    // ✅ ChatGPT Enhanced: lsiTerms, uniqueContent, relevantLinks 
    // Headings and Images criteria work normally
    // Lazy loading active remains with normal scoring (not in list)
    const key = `${categoryKey}.${criterionKey}`;
    console.log(`🔍 Checking criterion: ${key} - ${inDevCriteria.includes(key) ? 'IN DEVELOPMENT' : 'ACTIVE'}`);
    
    if (inDevCriteria.includes(key)) {
        console.log(`🚧 Criterion ${key} is in development`);
        return {
            inDevelopment: true,
            text: 'in development',
            maxScore: criterionConfig.maxScore
        };
    }
    console.log(`✅ Criterion ${key} is ACTIVE - executing analysis`);
    
    switch (categoryKey) {
        case 'metaTitle':
            return analyzeMetaTitleCriterion(criterionKey, criterionConfig, formData);
        case 'metaDescription':
            return analyzeMetaDescriptionCriterion(criterionKey, criterionConfig, formData);
        case 'url':
            return analyzeUrlCriterion(criterionKey, criterionConfig, formData);
        case 'headings':
            return analyzeHeadingsCriterion(criterionKey, criterionConfig, formData);
        case 'content':
            return await analyzeContentCriterion(criterionKey, criterionConfig, formData);
        case 'images':
            return analyzeImagesCriterion(criterionKey, criterionConfig);
        case 'internalLinks':
            return await analyzeInternalLinksCriterion(criterionKey, criterionConfig);
        case 'externalLinks':
            return await analyzeExternalLinksCriterion(criterionKey, criterionConfig);
        case 'backlinks':
            return await analyzeBacklinksCriterion(criterionKey, criterionConfig, apiResults);
        case 'performance':
            return await analyzePerformanceCriterion(criterionKey, criterionConfig, apiResults);
        case 'mobileFriendly':
            return await analyzeMobileFriendlyCriterion(criterionKey, criterionConfig, apiResults);
        case 'technicalSeo':
            return await analyzeTechnicalSeoCriterion(criterionKey, criterionConfig, apiResults);
        default:
            console.warn(`⚠️ Unknown category: ${categoryKey}`);
            return 0;
    }
}

/**
 * Get form field data once for efficiency
 */
function getFormFieldData() {
    const keywordElement = document.getElementById('aysa-entity-keyword');
    const titleElement = document.getElementById('aysa-entity-meta-title');
    const descElement = document.getElementById('aysa-entity-meta-description');
    const keywordsElement = document.getElementById('aysa-entity-meta-keywords');
    
    const formData = {
        mainKeyword: keywordElement ? keywordElement.value.trim().toLowerCase() : '',
        metaTitle: titleElement ? titleElement.value.trim() : '',
        metaDescription: descElement ? descElement.value.trim() : '',
        metaKeywords: keywordsElement ? keywordsElement.value.trim() : '',
        currentUrl: window.location.href,
        publicUrl: getEntityPublicUrl()
    };
    
    // ✅ ENHANCED LOGGING: Log all SEO elements side by side for scoring analysis
    logScoringElementsComparison(formData);
    
    return formData;
}

/**
 * Log all SEO elements side by side for comprehensive scoring analysis
 */
function logScoringElementsComparison(formData) {
    // Extract H1 from content if available
    const h1Elements = document.querySelectorAll('h1');
    const h1Text = h1Elements.length > 0 ? h1Elements[0].textContent.trim() : '';
    
    // Get content type and entity info
    const contentType = getContentType();
    const entityId = getPostId();
    
    console.log('🔥 SCORING_ELEMENTS_LOG: ═══════════════════════════════════════');
    console.log('🔥 SCORING_ELEMENTS_LOG: SEO ELEMENTS SIDE-BY-SIDE COMPARISON');
    console.log('🔥 SCORING_ELEMENTS_LOG: ═══════════════════════════════════════');
    console.log('🔥 SCORING_ELEMENTS_LOG: Entity Info:', {
        contentType: contentType,
        entityId: entityId,
        timestamp: new Date().toISOString()
    });
    console.log('🔥 SCORING_ELEMENTS_LOG: ───────────────────────────────────────');
    console.log('🔥 SCORING_ELEMENTS_LOG: KEYWORD    :', formData.mainKeyword || '[EMPTY]');
    console.log('🔥 SCORING_ELEMENTS_LOG: H1         :', h1Text || '[NOT_FOUND]');
    console.log('🔥 SCORING_ELEMENTS_LOG: META_TITLE :', formData.metaTitle || '[EMPTY]');
    console.log('🔥 SCORING_ELEMENTS_LOG: META_DESC  :', formData.metaDescription || '[EMPTY]');
    console.log('🔥 SCORING_ELEMENTS_LOG: META_KEYS  :', formData.metaKeywords || '[EMPTY]');
    console.log('🔥 SCORING_ELEMENTS_LOG: ───────────────────────────────────────');
    console.log('🔥 SCORING_ELEMENTS_LOG: Element Lengths:');
    console.log('🔥 SCORING_ELEMENTS_LOG:   - Keyword    :', formData.mainKeyword.length, 'chars');
    console.log('🔥 SCORING_ELEMENTS_LOG:   - H1         :', h1Text.length, 'chars');
    console.log('🔥 SCORING_ELEMENTS_LOG:   - Meta Title :', formData.metaTitle.length, 'chars');
    console.log('🔥 SCORING_ELEMENTS_LOG:   - Meta Desc  :', formData.metaDescription.length, 'chars');
    console.log('🔥 SCORING_ELEMENTS_LOG: ───────────────────────────────────────');
    console.log('🔥 SCORING_ELEMENTS_LOG: Keyword Analysis:');
    
    if (formData.mainKeyword) {
        const keyword = formData.mainKeyword.toLowerCase();
        console.log('🔥 SCORING_ELEMENTS_LOG:   - In H1         :', h1Text.toLowerCase().includes(keyword) ? '✅ YES' : '❌ NO');
        console.log('🔥 SCORING_ELEMENTS_LOG:   - In Meta Title :', formData.metaTitle.toLowerCase().includes(keyword) ? '✅ YES' : '❌ NO');
        console.log('🔥 SCORING_ELEMENTS_LOG:   - In Meta Desc  :', formData.metaDescription.toLowerCase().includes(keyword) ? '✅ YES' : '❌ NO');
        
        // Check if keyword is at the start of meta title
        const titleStart = formData.metaTitle.toLowerCase().substring(0, 30);
        console.log('🔥 SCORING_ELEMENTS_LOG:   - At Title Start:', titleStart.includes(keyword) ? '✅ YES' : '❌ NO');
    } else {
        console.log('🔥 SCORING_ELEMENTS_LOG:   - No keyword provided for analysis');
    }
    
    console.log('🔥 SCORING_ELEMENTS_LOG: ───────────────────────────────────────');
    console.log('🔥 SCORING_ELEMENTS_LOG: Length Validation:');
    console.log('🔥 SCORING_ELEMENTS_LOG:   - Meta Title (50-60):', 
        formData.metaTitle.length >= 50 && formData.metaTitle.length <= 60 ? '✅ OPTIMAL' : 
        formData.metaTitle.length > 0 ? '⚠️ SUBOPTIMAL' : '❌ EMPTY');
    console.log('🔥 SCORING_ELEMENTS_LOG:   - Meta Desc (150-160):', 
        formData.metaDescription.length >= 150 && formData.metaDescription.length <= 160 ? '✅ OPTIMAL' : 
        formData.metaDescription.length > 0 ? '⚠️ SUBOPTIMAL' : '❌ EMPTY');
    console.log('🔥 SCORING_ELEMENTS_LOG: ═══════════════════════════════════════');
}

/**
     * Chapter 1 – Page Title (Meta Title) – 8 points
 */
function analyzeMetaTitleCriterion(criterionKey, criterionConfig, formData) {
    const { metaTitle, mainKeyword } = formData;
    
    // ✅ ENHANCED LOGGING: Log meta title scoring analysis
    console.log('🔥 META_TITLE_SCORING_LOG: ═══════════════════════════════════════');
    console.log('🔥 META_TITLE_SCORING_LOG: Meta Title Criterion Analysis');
    console.log('🔥 META_TITLE_SCORING_LOG: ═══════════════════════════════════════');
    console.log('🔥 META_TITLE_SCORING_LOG: Criterion:', criterionKey);
    console.log('🔥 META_TITLE_SCORING_LOG: Max Score:', criterionConfig.maxScore);
    console.log('🔥 META_TITLE_SCORING_LOG: Meta Title:', metaTitle || '[EMPTY]');
    console.log('🔥 META_TITLE_SCORING_LOG: Main Keyword:', mainKeyword || '[EMPTY]');
    
    if (!metaTitle) {
        console.log('🔥 META_TITLE_SCORING_LOG: ❌ RESULT: 0 points - No meta title provided');
        console.log('🔥 META_TITLE_SCORING_LOG: ═══════════════════════════════════════');
        return 0;
    }
    
    let score = 0;
    let reason = '';
    
    switch (criterionKey) {
        case 'keywordAtStart': // 3 points
            console.log('🔥 META_TITLE_SCORING_LOG: Analyzing keywordAtStart criterion...');
            
            // Check if the main keyword is present at the beginning
            if (!mainKeyword) {
                score = 0;
                reason = 'No main keyword provided';
                console.log('🔥 META_TITLE_SCORING_LOG: ❌ No main keyword provided');
                break;
            }
            
            const normalizedTitle = normalizeText(metaTitle);
            const normalizedKeyword = normalizeText(mainKeyword);
            
            console.log('🔥 META_TITLE_SCORING_LOG: Normalized title:', normalizedTitle);
            console.log('🔥 META_TITLE_SCORING_LOG: Normalized keyword:', normalizedKeyword);
            
            // Check if the complete keyword appears in the first 30 characters
            const titleStart = normalizedTitle.substring(0, 30);
            console.log('🔥 META_TITLE_SCORING_LOG: Title start (30 chars):', titleStart);
            
            // Full score (3p) for complete keyword at the beginning
            if (titleStart.includes(normalizedKeyword)) {
                score = criterionConfig.maxScore;
                reason = `Full keyword "${normalizedKeyword}" found at start`;
                console.log(`🔥 META_TITLE_SCORING_LOG: ✅ Full keyword "${normalizedKeyword}" found at start: "${titleStart}"`);
                break;
            }
            
            // Partial score for individual keyword words
            const keywordWords = normalizedKeyword.split(/\s+/).filter(word => word.length > 2);
            console.log('🔥 META_TITLE_SCORING_LOG: Keyword words:', keywordWords);
            
            if (keywordWords.length > 1) {
                const matchingWords = keywordWords.filter(word => titleStart.includes(word));
                console.log('🔥 META_TITLE_SCORING_LOG: Matching words at start:', matchingWords);
                
                if (matchingWords.length > 0) {
                    score = Math.round((matchingWords.length / keywordWords.length) * criterionConfig.maxScore * 0.5);
                    reason = `Partial keyword match: ${matchingWords.length}/${keywordWords.length} words`;
                    console.log(`🔥 META_TITLE_SCORING_LOG: ⚠️ Partial keyword match at start: ${matchingWords.length}/${keywordWords.length} words, score: ${score}`);
                    break;
                }
            }
            
            score = 0;
            reason = `Keyword "${normalizedKeyword}" not found at start of title`;
            console.log(`🔥 META_TITLE_SCORING_LOG: ❌ Keyword "${normalizedKeyword}" not found at start of title: "${titleStart}"`);
            break;
            
        case 'optimalLength': // 2.5 points
            console.log('🔥 META_TITLE_SCORING_LOG: Analyzing optimalLength criterion...');
            
            // Length between 50–60 characters
            const length = metaTitle.length;
            console.log('🔥 META_TITLE_SCORING_LOG: Title length:', length, 'characters');
            
            if (length >= 50 && length <= 60) {
                score = criterionConfig.maxScore;
                reason = `Optimal length: ${length} characters (50-60 range)`;
                console.log('🔥 META_TITLE_SCORING_LOG: ✅ Optimal length achieved');
            } else if (length >= 45 && length <= 65) {
                score = Math.round(criterionConfig.maxScore * 0.7);
                reason = `Good length: ${length} characters (45-65 range, 70% score)`;
                console.log('🔥 META_TITLE_SCORING_LOG: ⚠️ Good length, partial score');
            } else if (length >= 40 && length <= 70) {
                score = Math.round(criterionConfig.maxScore * 0.4);
                reason = `Acceptable length: ${length} characters (40-70 range, 40% score)`;
                console.log('🔥 META_TITLE_SCORING_LOG: ⚠️ Acceptable length, low score');
            } else {
                score = 0;
                reason = `Poor length: ${length} characters (outside 40-70 range)`;
                console.log('🔥 META_TITLE_SCORING_LOG: ❌ Poor length, no score');
            }
            break;
            
        case 'uniqueTitle': // 2.5 points
            console.log('🔥 META_TITLE_SCORING_LOG: Analyzing uniqueTitle criterion...');
            
            // Pentru verificarea unicității, folosim o euristic simplă
            // În implementarea reală, aceasta ar trebui verificată prin API
            const genericTitles = [
                'home', 'homepage', 'pagina principala', 'untitled',
                'page', 'post', 'article', 'produs', 'categorie'
            ];
            
            const isGeneric = genericTitles.some(generic => 
                metaTitle.toLowerCase().includes(generic)
            );
            
            console.log('🔥 META_TITLE_SCORING_LOG: Generic title check:', isGeneric ? 'GENERIC' : 'UNIQUE');
            
            // Verifică dacă titlul este suficient de specific
            const hasSpecificContent = metaTitle.length > 20 && 
                                     metaTitle.split(' ').length >= 4;
            
            console.log('🔥 META_TITLE_SCORING_LOG: Specific content check:', {
                length: metaTitle.length,
                wordCount: metaTitle.split(' ').length,
                hasSpecificContent: hasSpecificContent
            });
            
            if (!isGeneric && hasSpecificContent) {
                score = criterionConfig.maxScore;
                reason = 'Title is unique and specific';
                console.log('🔥 META_TITLE_SCORING_LOG: ✅ Title is unique and specific');
            } else {
                score = 0;
                reason = isGeneric ? 'Title contains generic terms' : 'Title is not specific enough';
                console.log('🔥 META_TITLE_SCORING_LOG: ❌ Title failed uniqueness test:', reason);
            }
            break;
            
        default:
            score = 0;
            reason = 'Unknown criterion';
            console.log('🔥 META_TITLE_SCORING_LOG: ❌ Unknown criterion:', criterionKey);
    }
    
    // ✅ ENHANCED LOGGING: Log final result
    console.log('🔥 META_TITLE_SCORING_LOG: ───────────────────────────────────────');
    console.log('🔥 META_TITLE_SCORING_LOG: FINAL RESULT:');
    console.log('🔥 META_TITLE_SCORING_LOG:   - Score:', score, '/', criterionConfig.maxScore);
    console.log('🔥 META_TITLE_SCORING_LOG:   - Reason:', reason);
    console.log('🔥 META_TITLE_SCORING_LOG: ═══════════════════════════════════════');
    
    return score;
}

/**
     * Chapter 2 – Meta Description – 5 points
 */
function analyzeMetaDescriptionCriterion(criterionKey, criterionConfig, formData) {
    const { metaDescription, mainKeyword } = formData;
    
    if (!metaDescription) return 0;
    
    // Normalize meta description and keyword for diacritics-aware comparison
    const normalizedDescription = normalizeText(metaDescription);
    const normalizedKeyword = mainKeyword ? normalizeText(mainKeyword) : '';
    
    switch (criterionKey) {
        case 'optimalLength': // 1.5 points
            // Lungime 150–160 caractere
        const length = metaDescription.length;
            if (length >= 150 && length <= 160) {
                return criterionConfig.maxScore;
            } else if (length >= 140 && length <= 170) {
                return Math.round(criterionConfig.maxScore * 0.8);
            } else if (length >= 120 && length <= 180) {
                return Math.round(criterionConfig.maxScore * 0.5);
        }
        return 0;
            
        case 'keywordIncluded': // 1.5 points
            // Cuvânt cheie inclus natural
            if (!mainKeyword) return 0;
            
            const normalizedDesc = normalizeText(metaDescription);
            const normalizedKeyword = normalizeText(mainKeyword);
            
            console.log(`🔍 Meta Description Keyword Analysis:`);
            console.log(`  Description: "${metaDescription}"`);
            console.log(`  Keyword: "${mainKeyword}"`);
            
            // Verifică dacă keyword-ul complet apare în descriere
            const exactKeywordFound = normalizedDesc.includes(normalizedKeyword);
            console.log(`  Exact keyword found: ${exactKeywordFound}`);
            
            if (exactKeywordFound) {
                // Verifică că nu e keyword stuffing pentru keyword-ul complet (max 2 apariții)
                const exactKeywordCount = (normalizedDesc.split(normalizedKeyword).length - 1);
                console.log(`  Exact keyword count: ${exactKeywordCount}`);
                
                if (exactKeywordCount <= 2) {
                    console.log(`✅ Keyword found naturally in meta description`);
                    return criterionConfig.maxScore;
        } else {
                    console.log(`⚠️ Keyword stuffing detected (${exactKeywordCount} occurrences)`);
                    return Math.round(criterionConfig.maxScore * 0.5);
                }
            }
            
            // Verifică cuvinte individuale pentru punctaj parțial
            const keywordWords = normalizedKeyword.split(/\s+/).filter(word => word.length > 2);
            if (keywordWords.length > 1) {
                const foundWords = keywordWords.filter(word => normalizedDesc.includes(word));
                if (foundWords.length > 0) {
                    const partialScore = Math.round((foundWords.length / keywordWords.length) * criterionConfig.maxScore * 0.6);
                    console.log(`⚠️ Partial keyword match: ${foundWords.length}/${keywordWords.length} words, score: ${partialScore}`);
                    return partialScore;
                }
            }
            
            console.log(`❌ Keyword not found in meta description`);
        return 0;
            
        case 'uniqueDescription': // 2 points
            // Verifică dacă meta description nu este generică
            const genericPhrases = [
                'lorem ipsum', 'sample text', 'descriere pagina',
                'text default', 'coming soon', 'in constructie'
            ];
            
            const isGeneric = genericPhrases.some(phrase => 
                metaDescription.toLowerCase().includes(phrase)
            );
            
            // Verifică specificitatea
            const hasSpecificContent = metaDescription.length > 50 && 
                                     metaDescription.split(' ').length >= 15;
            
            return !isGeneric && hasSpecificContent ? criterionConfig.maxScore : 0;
            
        default:
            return 0;
    }
}

/**
     * Chapter 3 – URL (Slug) – 5 points
 */
function analyzeUrlCriterion(criterionKey, criterionConfig, formData) {
    const { publicUrl, mainKeyword } = formData;
    
    if (!publicUrl) return 0;
    
    // Extrage slug-ul din URL
    const url = new URL(publicUrl);
    const slug = url.pathname.toLowerCase();
    const slugParts = slug.split('/').filter(part => part.length > 0);
    const mainSlug = slugParts[slugParts.length - 1] || '';
    
    console.log(`🔍 URL Analysis:`);
    console.log(`  Full URL: "${publicUrl}"`);
    console.log(`  Slug: "${slug}"`);
    console.log(`  Main Slug: "${mainSlug}"`);
    console.log(`  Keyword: "${mainKeyword}"`);
    
    switch (criterionKey) {
        case 'keywordInUrl': // 2 puncte
            // Cuvânt cheie inclus într-un mod natural
            if (!mainKeyword) return 0;
            
            const normalizedKeyword = normalizeText(mainKeyword);
            const keywordSlugified = normalizedKeyword.replace(/\s+/g, '-');
            
            // Verifică dacă keyword-ul complet apare în URL (slugified)
            const exactKeywordInUrl = slug.includes(keywordSlugified);
            console.log(`  Exact keyword "${keywordSlugified}" in URL: ${exactKeywordInUrl}`);
            
            if (exactKeywordInUrl) {
                console.log(`✅ Keyword naturally included in URL`);
                return criterionConfig.maxScore;
            }
            
            // Verifică cuvinte individuale pentru punctaj parțial
            const keywordLower = normalizedKeyword.toLowerCase();
            const keywordWords = keywordLower.split(/\s+/).filter(word => word.length > 2);
            if (keywordWords.length > 1) {
                const foundWords = keywordWords.filter(word => slug.includes(word));
                if (foundWords.length > 0) {
                    const partialScore = Math.round((foundWords.length / keywordWords.length) * criterionConfig.maxScore * 0.7);
                    console.log(`⚠️ Partial keyword match in URL: ${foundWords.length}/${keywordWords.length} words, score: ${partialScore}`);
                    return partialScore;
                }
            }
            
            console.log(`❌ Keyword not found in URL`);
        return 0;
            
        case 'seoFriendlyFormat': // 1.5 puncte
            // Format SEO-friendly: doar litere mici, fără stopwords, fără caractere speciale
            console.log(`🔍 SEO-Friendly Format Analysis:`);
            
            // Verifică pattern-ul de bază (doar lowercase, cifre, cratimă, slash)
            const seoFriendlyPattern = /^[a-z0-9\-\/]+$/;
            const isSeoFriendly = seoFriendlyPattern.test(slug);
            console.log(`  Basic SEO pattern (a-z0-9-/): ${isSeoFriendly}`);
            
            if (!isSeoFriendly) {
                console.log(`❌ URL contains special characters or uppercase letters`);
                return 0;
            }
            
            // Verifică stopwords românești și engleze
            const stopwords = [
                // Românești
                'si', 'și', 'la', 'in', 'în', 'cu', 'de', 'pentru', 'din', 'pe', 'ca', 'sau', 'dar', 'este', 'sunt',
                // Engleze
                'and', 'the', 'or', 'but', 'with', 'for', 'from', 'on', 'as', 'is', 'are', 'at', 'to', 'a', 'an'
            ];
            
            const hasStopwords = stopwords.some(word => {
                const patterns = [
                    `-${word}-`,    // între cuvinte: -și-
                    `/${word}-`,    // după slash: /la-
                    `-${word}/`,    // înainte de slash: -în/
                    `-${word}$`,    // la sfârșit: -de
                    `^${word}-`,    // la început: și-
                ];
                return patterns.some(pattern => new RegExp(pattern).test(slug));
            });
            
            console.log(`  Has stopwords: ${hasStopwords}`);
            
            if (hasStopwords) {
                console.log(`⚠️ URL contains stopwords - partial score`);
                return Math.round(criterionConfig.maxScore * 0.3);
            }
            
            console.log(`✅ SEO-friendly format - clean URL`);
            return criterionConfig.maxScore;
            
        case 'shortDescriptive': // 1.5 puncte
            // Scurt și descriptiv: fără cuvinte vagi, fără coduri, fără cifre irelevante
            console.log(`🔍 Short & Descriptive Analysis:`);
            console.log(`  Main slug: "${mainSlug}"`);
            
            if (!mainSlug) {
                console.log(`❌ No main slug found`);
                return 0;
            }
            
            const words = mainSlug.split('-').filter(word => word.length > 0);
            const wordCount = words.length;
            const slugLength = mainSlug.length;
            
            console.log(`  Word count: ${wordCount}, Length: ${slugLength}`);
            
            // Verifică pentru elemente nedorite
            const hasNumbers = /\d{3,}/.test(mainSlug); // 3+ cifre consecutive
            const hasVagueWords = /\b(pagina|articol|post|item|page|article)\b/.test(mainSlug);
            const hasGenericWords = /\b(ultim|noutati|nou|new|latest)\b/.test(mainSlug);
            
            console.log(`  Has numbers (3+): ${hasNumbers}`);
            console.log(`  Has vague words: ${hasVagueWords}`);
            console.log(`  Has generic words: ${hasGenericWords}`);
            
            // Penalizări pentru elemente nedorite
            if (hasNumbers || hasVagueWords || hasGenericWords) {
                console.log(`⚠️ URL contains undesirable elements - reduced score`);
                return Math.round(criterionConfig.maxScore * 0.2);
            }
            
            // Scoring bazat pe lungime și numărul de cuvinte
            if (wordCount >= 2 && wordCount <= 5 && slugLength >= 10 && slugLength <= 50) {
                console.log(`✅ Perfect length and word count`);
                return criterionConfig.maxScore;
            } else if (wordCount >= 2 && wordCount <= 7 && slugLength >= 8 && slugLength <= 60) {
                console.log(`⚠️ Acceptable length and word count`);
                return Math.round(criterionConfig.maxScore * 0.7);
            } else if (wordCount >= 1 && slugLength >= 5 && slugLength <= 80) {
                console.log(`⚠️ Borderline acceptable`);
                return Math.round(criterionConfig.maxScore * 0.4);
            }
            
            console.log(`❌ URL too long, too short, or has too many/few words`);
            return 0;
            
        default:
        return 0;
    }
}

/**
     * Chapter 4 – Headings (H1–H3) – 8 points
 */
function analyzeHeadingsCriterion(criterionKey, criterionConfig, formData) {
    const { mainKeyword } = formData;
    const contentType = getContentType(); // Declare once at function level
    
    // Normalize keyword for diacritics-aware comparison
    const normalizedKeyword = normalizeText(mainKeyword) ? normalizeText(mainKeyword) : '';
    
    switch (criterionKey) {
        case 'singleH1': // 3 puncte
            // Single correct H1 - according to Google Docs
            console.log(`🔍 Single H1 Analysis:`);
            
            if (contentType === 'product' || contentType === 'page') {
                // Pentru paginile admin, verifică title field-ul pentru H1 viitor
                const titleField = document.getElementById('title');
                if (titleField && titleField.value && titleField.value.trim().length > 10) {
                    console.log(`✅ Found valid title in field: "${titleField.value}"`);
                    console.log(`✅ Single H1 assumed from title field - full score`);
                    return criterionConfig.maxScore;
                } else {
                    console.log(`⚠️ Title field empty or too short: "${titleField ? titleField.value : 'NOT FOUND'}"`);
                    return Math.round(criterionConfig.maxScore * 0.3);
                }
            } else {
                // Pentru alte pagini, verifică H1-urile actuale din DOM
        const h1Elements = document.querySelectorAll('h1');
                console.log(`  Found ${h1Elements.length} H1 elements`);
                
        if (h1Elements.length === 1) {
                    const h1Text = h1Elements[0].textContent.trim();
                    console.log(`  H1 text: "${h1Text}"`);
                    
                    if (h1Text.length > 10) {
                        console.log(`✅ Single H1 with meaningful content - full score`);
                        return criterionConfig.maxScore;
                    } else {
                        console.log(`⚠️ H1 too short - partial score`);
                        return Math.round(criterionConfig.maxScore * 0.5);
                    }
                } else if (h1Elements.length === 0) {
                    console.log(`❌ No H1 elements found`);
                    return 0;
                } else {
                    console.log(`⚠️ Multiple H1s found (${h1Elements.length}) - should be only one`);
                    // Multiple H1s - major penalty as per Google Docs
                    return Math.round(criterionConfig.maxScore * 0.2);
                }
            }
            
        case 'h1HasKeyword': // 2.5 puncte
            // H1 conține cuvânt cheie principal
            if (!mainKeyword) {
                console.warn('⚠️ No main keyword provided for H1 analysis');
                return 0;
            }
            
            // For admin pages, get H1 from the actual product title, not the admin page H1
            let h1Text = '';
            
            if (contentType === 'product') {
                // Try to get the product title from the title field
                const titleField = document.getElementById('title') || document.querySelector('#title');
                if (titleField && titleField.value) {
                    h1Text = normalizeText(titleField.value);
                    console.log(`📝 Using product title field: "${h1Text}"`);
                } else {
                    // Fallback to page H1
                    const h1 = document.querySelector('h1');
                    h1Text = h1 ? normalizeText(h1.textContent) : '';
                    console.log(`📄 Using page H1: "${h1Text}"`);
                }
            } else {
                // For other content types, try title field first, then H1
                const titleField = document.getElementById('title') || document.querySelector('#title');
                if (titleField && titleField.value) {
                    h1Text = titleField.value.toLowerCase().trim();
                    console.log(`📝 Using title field: "${h1Text}"`);
                } else {
                    const h1 = document.querySelector('h1');
                    h1Text = h1 ? h1.textContent.toLowerCase().trim() : '';
                    console.log(`📄 Using page H1: "${h1Text}"`);
                }
            }
            
            if (!h1Text) {
                console.warn('⚠️ No H1 text found');
                return 0;
            }
            
            const keywordVariations = generateKeywordVariations(mainKeyword);
            
            console.log(`🔍 H1 Analysis:`);
            console.log(`  H1 Text: "${h1Text}"`);
            console.log(`  Main Keyword: "${mainKeyword}"`);
            console.log(`  Variations: [${keywordVariations.join(', ')}]`);
            
            // Verifică keyword-ul complet întâi
            const normalizedKeyword = normalizeText(mainKeyword);
            const exactMatch = h1Text.includes(normalizedKeyword);
            console.log(`  Exact keyword match: "${normalizedKeyword}" in "${h1Text}" = ${exactMatch}`);
            
            if (exactMatch) {
                console.log(`✅ Full keyword found naturally in H1 - full score`);
                return criterionConfig.maxScore;
            }
            
            // Verifică cuvinte individuale pentru punctaj parțial
            const keywordWords = normalizedKeyword.split(/\s+/).filter(word => word.length > 2);
            if (keywordWords.length > 1) {
                const foundWords = keywordWords.filter(word => h1Text.includes(word));
                if (foundWords.length > 0) {
                    const partialScore = Math.round((foundWords.length / keywordWords.length) * criterionConfig.maxScore * 0.6);
                    console.log(`⚠️ Partial keyword match in H1: ${foundWords.length}/${keywordWords.length} words, score: ${partialScore}`);
                    return partialScore;
                }
            }
            
            console.log(`❌ Keyword not found in H1`);
            return 0;
            
        case 'logicalStructure': // 2.5 puncte
            // Structură logică H2, H3 - ierahie corectă fără a sări niveluri
            console.log(`🔍 Heading Structure Analysis:`);
            
            const h1Elements = document.querySelectorAll('h1');
            let h2Elements = document.querySelectorAll('h2');
            let h3Elements = document.querySelectorAll('h3');
            let h4Elements = document.querySelectorAll('h4');
            const h5Elements = document.querySelectorAll('h5');
            const h6Elements = document.querySelectorAll('h6');
            
            console.log(`  Page DOM - H1: ${h1Elements.length}, H2: ${h2Elements.length}, H3: ${h3Elements.length}`);
            console.log(`  Page DOM - H4: ${h4Elements.length}, H5: ${h5Elements.length}, H6: ${h6Elements.length}`);
            
            // Pentru paginile admin, verifică și content-ul din editor
            if (contentType === 'product' || contentType === 'page') {
                // Get content from TinyMCE editor if available
                let editorContent = '';
                if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
                    editorContent = tinyMCE.get('content').getContent();
                } else {
                    const contentField = document.getElementById('content');
                    if (contentField) {
                        editorContent = contentField.value;
                    }
                }
                
                if (editorContent) {
                    const tempDiv = document.createElement('div');
                    tempDiv.innerHTML = editorContent;
                    
                    const editorH2 = tempDiv.querySelectorAll('h2');
                    const editorH3 = tempDiv.querySelectorAll('h3');
                    const editorH4 = tempDiv.querySelectorAll('h4');
                    
                    console.log(`  Editor content - H2: ${editorH2.length}, H3: ${editorH3.length}, H4: ${editorH4.length}`);
                    
                    // Update counts with editor content if it has more headings
                    if (editorH2.length > 0 || editorH3.length > 0 || editorH4.length > 0) {
                        console.log(`  Using editor content for structure analysis`);
                        h2Elements = editorH2;
                        h3Elements = editorH3;
                        h4Elements = editorH4;
                    }
                } else {
                    console.log(`  No editor content found - using page DOM only`);
                }
            }
            
            // Check logical hierarchy according to Google Docs
            // Exemplu corect: H1 -> H2 -> H3 -> H2 (fără a sări niveluri)
            // Exemplu greșit: H1 -> H3 (sare H2)
            
            let structureScore = 0;
            let hasProperHierarchy = true;
            
            // Verifică dacă există structură minimă (măcar H2)
            if (h2Elements.length === 0) {
                console.log(`❌ No H2 elements found - no structure`);
                return 0;
            }
            
            // Punctaj pentru existența H2-urilor (1 punct)
            structureScore += 1;
            console.log(`✅ H2 elements found (+1 point)`);
            
            // Verifică dacă există H3 după H2 (ierarhie logică)
            if (h3Elements.length > 0) {
                console.log(`✅ H3 elements found - checking hierarchy`);
                
                // Pentru pagini admin cu editor content, verifică ierarhia în editor
                let hierarchyBroken = false;
                
                if (contentType === 'product' || contentType === 'page') {
                    // Pentru editor content, presupunem ierarhie corectă dacă avem și H2 și H3
                    // deoarece utilizatorul le-a adăugat manual în ordine în editor
                    if (h2Elements.length > 0 && h3Elements.length > 0) {
                        console.log(`✅ Editor content has both H2 and H3 - assuming proper hierarchy`);
                        hierarchyBroken = false;
                    }
                } else {
                    // Pentru pagini publice, verifică ierarhia reală din DOM
                    const allHeadings = document.querySelectorAll('h1, h2, h3, h4, h5, h6');
                    let lastLevel = 1; // Începem cu H1
                    
                    for (let heading of allHeadings) {
                        const currentLevel = parseInt(heading.tagName.substring(1));
                        
                        // Verifică că nu sărim nivele (ex: H1 -> H3 fără H2)
                        if (currentLevel > lastLevel + 1) {
                            console.log(`⚠️ Hierarchy broken: jumped from H${lastLevel} to H${currentLevel}`);
                            hierarchyBroken = true;
                    break;
                }
                        
                        lastLevel = Math.max(lastLevel, currentLevel);
                    }
                }
                
                if (!hierarchyBroken) {
                    structureScore += 1; // +1 pentru H3 cu ierarhie corectă
                    console.log(`✅ H3 elements with proper hierarchy (+1 point)`);
                } else {
                    structureScore += 0.5; // +0.5 pentru H3 dar cu ierarhie spartă
                    console.log(`⚠️ H3 elements but broken hierarchy (+0.5 points)`);
                }
            } else {
                console.log(`⚠️ No H3 elements - incomplete structure`);
                // Without H3, structure is incomplete - 0.5 points bonus for H2
                structureScore += 0.5;
            }
            
            // Bonus pentru structură foarte bună (H2 + H3 + logică)  
            if (h2Elements.length >= 2 && h3Elements.length >= 1) {
                console.log(`✅ Excellent structure with multiple levels (+0.5 bonus)`);
                structureScore = Math.min(structureScore + 0.5, criterionConfig.maxScore);
            }
            
            const finalScore = Math.min(structureScore, criterionConfig.maxScore);
            console.log(`📊 Structure score: ${finalScore}/${criterionConfig.maxScore}`);
            
            return finalScore;
            
        default:
        return 0;
    }
}

/**
 * Generate keyword variations for better matching
 */
function generateKeywordVariations(keyword) {
    if (!keyword) return [];
    
    const variations = [keyword.toLowerCase()];
    
    // Split multi-word keywords and add individual words
    const words = keyword.toLowerCase().split(/\s+/);
    if (words.length > 1) {
        words.forEach(word => {
            if (word.length > 2) { // Only meaningful words
                variations.push(word);
            }
        });
        
        // Add partial combinations for phrases
        for (let i = 0; i < words.length - 1; i++) {
            variations.push(words.slice(i, i + 2).join(' ')); // 2-word combinations
        }
        
        // Add exact phrase matching
        variations.push(keyword.toLowerCase().trim());
    }
    
    // Add singular/plural variations for each word
    words.forEach(word => {
        if (word.endsWith('i') && word.length > 3) {
            variations.push(word.slice(0, -1)); // Remove 'i' for singular
        } else if (!word.endsWith('i') && word.length > 2) {
            variations.push(word + 'i'); // Add 'i' for plural
        }
        
        // Add common Romanian plural forms
        if (word.endsWith('e') && word.length > 3) {
            variations.push(word.slice(0, -1)); // Remove 'e'
        }
        if (word.endsWith('uri') && word.length > 5) {
            variations.push(word.slice(0, -3)); // Remove 'uri'
        }
    });
    
    // Add with/without diacritics for all variations
    const cleanVariations = [];
    variations.forEach(variation => {
        const withoutDiacritics = variation
            .replace(/[ăâ]/g, 'a')
            .replace(/[îî]/g, 'i')
            .replace(/[șş]/g, 's')
            .replace(/[țţ]/g, 't')
            .replace(/[ç]/g, 'c');
            
        cleanVariations.push(variation);
        if (withoutDiacritics !== variation) {
            cleanVariations.push(withoutDiacritics);
        }
    });
    
    console.log(`🔍 Generated keyword variations for "${keyword}":`, [...new Set(cleanVariations)]);
    return [...new Set(cleanVariations)]; // Remove duplicates
}

/**
 * Analyze content using real data only
 */
function analyzeContentReal(criterion, mainKeyword, maxScore, contentType) {
    let content = '';
    
    // Get real content from TinyMCE or textarea
    if (contentType === 'product') {
        const contentField = document.getElementById('content');
        if (contentField) {
            if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
                content = tinyMCE.get('content').getContent({format: 'text'});
            } else {
                content = contentField.value;
            }
        }
    } else if (contentType === 'category') {
        const descField = document.getElementById('description');
        if (descField) {
            if (typeof tinyMCE !== 'undefined' && tinyMCE.get('description')) {
                content = tinyMCE.get('description').getContent({format: 'text'});
            } else {
                content = descField.value;
            }
        }
    }
    
    // If no admin content, try to get from page content
    if (!content.trim()) {
        const contentElements = document.querySelectorAll('main, .content, .entry-content, article p, .product-description');
        content = Array.from(contentElements).map(el => el.textContent).join(' ');
    }
    
    if (!content.trim()) return null; // No content found
    
    const plainText = content.replace(/<[^>]*>/g, '').trim();
    const words = plainText.split(/\s+/).filter(word => word.length > 0);
    const wordCount = words.length;
    
    if (criterion.includes('300 cuvinte') || criterion.includes('word count')) {
        if (wordCount >= 300) return maxScore;
        if (wordCount >= 200) return Math.floor(maxScore * 0.7);
        if (wordCount >= 100) return Math.floor(maxScore * 0.4);
        return 0;
    } else if (criterion.includes('Densitate') || criterion.includes('density')) {
        if (!mainKeyword || wordCount === 0) return null;
        
        const keywordMatches = (plainText.toLowerCase().match(new RegExp(mainKeyword, 'g')) || []).length;
        const density = (keywordMatches / wordCount) * 100;
        
        if (density >= 0.5 && density <= 2.5) return maxScore;
        if (density >= 0.3 && density <= 3.0) return Math.floor(maxScore * 0.7);
        if (density > 0) return Math.floor(maxScore * 0.3);
        return 0;
    } else if (criterion.includes('Sinonime') || criterion.includes('LSI') || criterion.includes('variations')) {
        if (!mainKeyword) return null;
        
        const variations = generateKeywordVariations(mainKeyword);
        const hasVariations = variations.some(variation => 
            plainText.toLowerCase().includes(variation.toLowerCase())
        );
        
        return hasVariations ? maxScore : 0;
    }
    return null;
}

/**
 * Analyze images using real DOM data only
 */
function analyzeImagesReal(criterion, maxScore) {
    const images = document.querySelectorAll('img');
    if (images.length === 0) return null; // No images to analyze
    
    if (criterion.includes('alt text') || criterion.includes('alt')) {
        let imagesWithAlt = 0;
        images.forEach(img => {
            if (img.alt && img.alt.trim()) {
                imagesWithAlt++;
            }
        });
        
        const percentage = (imagesWithAlt / images.length) * 100;
        if (percentage === 100) return maxScore;
        if (percentage >= 80) return Math.floor(maxScore * 0.8);
        if (percentage >= 50) return Math.floor(maxScore * 0.5);
        return 0;
    } else if (criterion.includes('SEO-friendly') || criterion.includes('filename')) {
        let seoFriendlyImages = 0;
        images.forEach(img => {
            const src = img.src.toLowerCase();
            const filename = src.split('/').pop().split('?')[0]; // Get filename without query params
            // Check if filename contains descriptive words (not just numbers/random chars)
            const hasDescriptiveFilename = /[a-z]{3,}/.test(filename) && !filename.startsWith('img_') && !filename.startsWith('image');
            if (hasDescriptiveFilename) {
                seoFriendlyImages++;
            }
        });
        
        const percentage = (seoFriendlyImages / images.length) * 100;
        if (percentage >= 80) return maxScore;
        if (percentage >= 50) return Math.floor(maxScore * 0.7);
        if (percentage >= 25) return Math.floor(maxScore * 0.4);
        return 0;
    } else if (criterion.includes('optimizate') || criterion.includes('optimize') || criterion.includes('size')) {
        // Check for reasonable image dimensions and format
        let optimizedImages = 0;
        let loadedImages = 0;
        
        images.forEach(img => {
            if (img.complete && img.naturalWidth > 0) {
                loadedImages++;
                // Consider optimized if reasonable dimensions and modern format
                const hasReasonableSize = img.naturalWidth <= 2000 && img.naturalHeight <= 2000;
                const hasModernFormat = /\.(webp|jpg|jpeg|png)$/i.test(img.src);
                
                if (hasReasonableSize && hasModernFormat) {
                    optimizedImages++;
                }
            }
        });
        
        if (loadedImages === 0) return null; // Can't determine optimization
        
        const percentage = (optimizedImages / loadedImages) * 100;
        if (percentage >= 80) return maxScore;
        if (percentage >= 60) return Math.floor(maxScore * 0.7);
        if (percentage >= 40) return Math.floor(maxScore * 0.4);
        return 0;
    }
    return null;
}

/**
 * Analyze internal links using real DOM data only
 */
function analyzeInternalLinksReal(criterion, maxScore) {
    const allLinks = document.querySelectorAll('a[href]');
    if (allLinks.length === 0) return null;
    
    const internalLinks = Array.from(allLinks).filter(link => {
        const href = link.href;
        return href && (
            href.startsWith(window.location.origin) || 
            href.startsWith('/') ||
            !href.includes('://')
        );
    });
    
            if (criterion.includes('At least one') || criterion.includes('at least one')) {
        return internalLinks.length >= 1 ? maxScore : 0;
            } else if (criterion.includes('Functional') || criterion.includes('working') || criterion.includes('404')) {
        // Can't reliably check for 404s without making requests
        // But we can check for obvious broken patterns
        let validLinks = 0;
        internalLinks.forEach(link => {
            const href = link.href;
            // Basic validity checks
            const isValid = href && 
                          !href.includes('undefined') && 
                          !href.includes('null') &&
                          !href.endsWith('#') &&
                          href.length > 1;
            if (isValid) validLinks++;
        });
        
        if (internalLinks.length === 0) return null;
        const percentage = (validLinks / internalLinks.length) * 100;
        if (percentage >= 95) return maxScore;
        if (percentage >= 80) return Math.floor(maxScore * 0.7);
        return 0;
    } else if (criterion.includes('Anchor text') || criterion.includes('anchor')) {
        let optimizedAnchors = 0;
        internalLinks.forEach(link => {
            const anchorText = link.textContent.trim().toLowerCase();
            // Check if anchor text is descriptive (not just "click here", "read more", etc.)
            const isDescriptive = anchorText.length >= 3 && 
                                !anchorText.includes('click here') &&
                                !anchorText.includes('read more') &&
                                !anchorText.includes('here') &&
                                !/^(more|vezi|citește)$/i.test(anchorText);
            if (isDescriptive) optimizedAnchors++;
        });
        
        if (internalLinks.length === 0) return null;
        const percentage = (optimizedAnchors / internalLinks.length) * 100;
        if (percentage >= 70) return maxScore;
        if (percentage >= 50) return Math.floor(maxScore * 0.7);
        if (percentage >= 30) return Math.floor(maxScore * 0.4);
        return 0;
    }
    return null;
}

/**
 * Analyze performance using API data with browser fallback
 */
function analyzePerformanceWithFallback(criterion, maxScore, apiResults = null) {
    // First try to use API data if available
    if (apiResults?.pagespeed?.mobile && typeof apiResults.pagespeed.mobile.score === 'number') {
        const mobileScore = apiResults.pagespeed.mobile.score;
        console.log(`📱 Using API Mobile PageSpeed score: ${mobileScore}`);
        
        if (criterion.includes('PageSpeed') || criterion.includes('performance score')) {
            if (mobileScore >= 80) return maxScore; // Excellent
            if (mobileScore >= 60) return Math.floor(maxScore * 0.8); // Good
            if (mobileScore >= 40) return Math.floor(maxScore * 0.5); // Fair
            return 0; // Poor
        } else if (criterion.includes('încărcare') || criterion.includes('load time')) {
            // Estimate load time based on PageSpeed score
            if (mobileScore >= 90) return maxScore; // Very fast
            if (mobileScore >= 70) return Math.floor(maxScore * 0.8); // Fast
            if (mobileScore >= 50) return Math.floor(maxScore * 0.5); // Average
            return 0; // Slow
        } else if (criterion.includes('Core Web Vitals') || criterion.includes('vitals')) {
            // Estimate Web Vitals based on PageSpeed score
            if (mobileScore >= 75) return maxScore;
            if (mobileScore >= 50) return Math.floor(maxScore * 0.6);
            return 0;
        }
    }
    
    // Fallback to browser performance data
    console.log('📊 API data unavailable, falling back to browser performance...');
    return analyzePerformanceReal(criterion, maxScore);
}

/**
 * Analyze performance using real browser data only
 */
function analyzePerformanceReal(criterion, maxScore) {
    if (criterion.includes('PageSpeed') || criterion.includes('performance score')) {
        // Use Navigation Timing API for real performance data
        if (window.performance && window.performance.timing) {
            const timing = window.performance.timing;
            const loadTime = timing.loadEventEnd - timing.navigationStart;
            
            if (loadTime <= 2000) return maxScore; // Under 2s = excellent
            if (loadTime <= 3000) return Math.floor(maxScore * 0.8); // Under 3s = good
            if (loadTime <= 5000) return Math.floor(maxScore * 0.5); // Under 5s = fair
            return 0; // Over 5s = poor
        }
        return null; // No performance data available
    } else if (criterion.includes('încărcare') || criterion.includes('load time')) {
        if (window.performance && window.performance.timing) {
            const timing = window.performance.timing;
            const loadTime = timing.loadEventEnd - timing.navigationStart;
            
            if (loadTime <= 3000) return maxScore;
            if (loadTime <= 5000) return Math.floor(maxScore * 0.7);
            if (loadTime <= 8000) return Math.floor(maxScore * 0.4);
            return 0;
        }
        return null;
    } else if (criterion.includes('Core Web Vitals') || criterion.includes('vitals')) {
        // Use Performance Observer for Web Vitals if available
        if ('PerformanceObserver' in window) {
            // This is a simplified check - real implementation would need more complex measurement
            const resourceCount = window.performance.getEntriesByType('resource').length;
            if (resourceCount <= 50) return maxScore; // Fewer resources = better performance
            if (resourceCount <= 100) return Math.floor(maxScore * 0.7);
            if (resourceCount <= 150) return Math.floor(maxScore * 0.4);
            return 0;
        }
        return null;
    }
    return null;
}

/**
 * Analyze mobile-friendliness using API data with browser fallback
 */
function analyzeMobileFriendlyWithFallback(criterion, maxScore, apiResults = null) {
    // First try to use API data if available
    if (apiResults?.pagespeed?.mobile && typeof apiResults.pagespeed.mobile.score === 'number') {
        const mobileScore = apiResults.pagespeed.mobile.score;
        console.log(`📱 Using API Mobile PageSpeed score for mobile analysis: ${mobileScore}`);
        
        if (criterion.includes('Responsive') || criterion.includes('responsive')) {
            // Use PageSpeed mobile score as indicator of mobile-friendliness
            if (mobileScore >= 70) return maxScore;
            if (mobileScore >= 50) return Math.floor(maxScore * 0.7);
            if (mobileScore >= 30) return Math.floor(maxScore * 0.4);
            return 0;
        }
    }
    
    // For other mobile criteria or when API unavailable, use browser analysis
    console.log('📊 API data unavailable for mobile criteria, falling back to browser analysis...');
    return analyzeMobileFriendlyReal(criterion, maxScore);
}

/**
 * Analyze mobile-friendliness using real browser data
 */
function analyzeMobileFriendlyReal(criterion, maxScore) {
    if (criterion.includes('Responsive') || criterion.includes('responsive')) {
        // Check for viewport meta tag
        const viewportMeta = document.querySelector('meta[name="viewport"]');
        if (!viewportMeta) return 0;
        
        const viewportContent = viewportMeta.getAttribute('content');
        const hasProperViewport = viewportContent && 
                                 viewportContent.includes('width=device-width') &&
                                 viewportContent.includes('initial-scale=1');
        
        return hasProperViewport ? maxScore : Math.floor(maxScore * 0.5);
    } else if (criterion.includes('Font size') || criterion.includes('font')) {
        // Check if main content font size is >= 16px
        const bodyStyle = window.getComputedStyle(document.body);
        const bodyFontSize = parseFloat(bodyStyle.fontSize);
        
        const contentElements = document.querySelectorAll('main p, .content p, .entry-content p, article p');
        let maxFontSize = bodyFontSize;
        
        contentElements.forEach(el => {
            const fontSize = parseFloat(window.getComputedStyle(el).fontSize);
            if (fontSize > maxFontSize) maxFontSize = fontSize;
        });
        
        if (maxFontSize >= 16) return maxScore;
        if (maxFontSize >= 14) return Math.floor(maxScore * 0.7);
        return 0;
    } else if (criterion.includes('Touch elements') || criterion.includes('touch')) {
        // Check touch target sizes
        const touchElements = document.querySelectorAll('button, a, input[type="button"], input[type="submit"], .btn');
        if (touchElements.length === 0) return null;
        
        let adequateSizeElements = 0;
        touchElements.forEach(el => {
            const rect = el.getBoundingClientRect();
            if (rect.width >= 44 && rect.height >= 44) {
                adequateSizeElements++;
            }
        });
        
        const percentage = (adequateSizeElements / touchElements.length) * 100;
        if (percentage >= 90) return maxScore;
        if (percentage >= 70) return Math.floor(maxScore * 0.7);
        if (percentage >= 50) return Math.floor(maxScore * 0.4);
        return 0;
    }
    return null;
}

/**
 * Analyze technical SEO using API data with DOM fallback
 */
function analyzeTechnicalSeoWithFallback(criterion, maxScore, apiResults = null) {
    // First try to use API data if available
    if (apiResults?.technical?.data) {
        const techData = apiResults.technical.data;
        console.log('🔧 Using API Technical SEO data:', techData);
        
        if (criterion.includes('Schema') || criterion.includes('schema')) {
            if (typeof techData.schemaCount === 'number') {
                return techData.schemaCount > 0 ? maxScore : 0;
            }
        } else if (criterion.includes('Canonical') || criterion.includes('canonical')) {
            if (typeof techData.hasCanonical === 'boolean') {
                return techData.hasCanonical ? maxScore : 0;
            }
        } else if (criterion.includes('Robots') || criterion.includes('robots')) {
            if (typeof techData.hasNoIndexTag === 'boolean') {
                // If no noindex tag, robots is probably OK
                return !techData.hasNoIndexTag ? maxScore : Math.floor(maxScore * 0.5);
            }
        }
    }
    
    // Fallback to DOM analysis when API data unavailable
    console.log('📊 API data unavailable for technical SEO, falling back to DOM analysis...');
    return analyzeTechnicalSeoReal(criterion, maxScore);
}

/**
 * Analyze technical SEO using real DOM data
 */
function analyzeTechnicalSeoReal(criterion, maxScore) {
    if (criterion.includes('Schema') || criterion.includes('schema')) {
        // Check for JSON-LD or microdata
        const jsonLdScripts = document.querySelectorAll('script[type="application/ld+json"]');
        const microdataElements = document.querySelectorAll('[itemtype], [itemscope]');
        
        if (jsonLdScripts.length > 0 || microdataElements.length > 0) {
            return maxScore;
        }
        return 0;
    } else if (criterion.includes('Canonical') || criterion.includes('canonical')) {
        const canonicalLink = document.querySelector('link[rel="canonical"]');
        if (canonicalLink && canonicalLink.href) {
            return maxScore;
        }
        return 0;
    } else if (criterion.includes('Robots') || criterion.includes('robots')) {
        // Check for noindex meta tag
        const robotsMeta = document.querySelector('meta[name="robots"]');
        const noindexMeta = document.querySelector('meta[name="robots"][content*="noindex"]');
        
        if (noindexMeta) {
            return 0; // Page is set to noindex
        } else if (robotsMeta) {
            return maxScore; // Has robots meta tag
        } else {
            return Math.floor(maxScore * 0.8); // No explicit robots tag (default allow)
        }
    } else if (criterion.includes('Meta tags') || criterion.includes('meta')) {
        // Check for essential meta tags
        const titleTag = document.querySelector('title');
        const descriptionMeta = document.querySelector('meta[name="description"]');
        const charsetMeta = document.querySelector('meta[charset]');
        
        let metaScore = 0;
        if (titleTag && titleTag.textContent.trim()) metaScore += 0.4;
        if (descriptionMeta && descriptionMeta.getAttribute('content')) metaScore += 0.4;
        if (charsetMeta) metaScore += 0.2;
        
        return Math.floor(maxScore * metaScore);
    }
    return null;
}

/**
 * Update the score box with the new total score
 */
function updateScoreBox(totalScore) {
    generateSeoConclusions(totalScore);
}

/**
 * Update existing SEO score elements
 */
function generateSeoConclusions(totalScore) {
    console.log(`📊 Updating score display for: ${totalScore}%`);
    
    // Calculate score out of 10
    const scoreOutOf10 = (totalScore / 10).toFixed(1);
    
    // Update all score elements - show numeric score, not text
    const scoreElements = document.querySelectorAll('.score-text');
    const scoreValueElements = document.querySelectorAll('.score-value');
    const scoreTotalElements = document.querySelectorAll('.score-total');
    
    // For .score-text elements, replace "Calculating..." with the numeric score
    scoreElements.forEach((element, index) => {
        element.textContent = scoreOutOf10;
        console.log(`✅ Updated score text element ${index + 1}: "${scoreOutOf10}"`);
    });
    
    scoreValueElements.forEach((element, index) => {
        element.textContent = scoreOutOf10;
        console.log(`✅ Updated score value element ${index + 1}: "${scoreOutOf10}"`);
    });
    
    scoreTotalElements.forEach((element, index) => {
        element.textContent = '/10';
        console.log(`✅ Updated score total element ${index + 1}: "/10"`);
    });
    
    console.log('🎉 Real data score update complete!');
}

/**
 * Get color based on score
 */
function getScoreColor(score) {
    if (score >= 80) return '#00a32a';
    if (score >= 60) return '#dba617';
    return '#d63638';
}

/**
 * Get score description
 */
function getScoreDescription(score) {
    if (score >= 90) return 'Optimizare SEO excelentă! Continuați să monitorizați.';
    if (score >= 80) return 'SEO foarte bun, cu mici îmbunătățiri posibile.';
    if (score >= 70) return 'SEO decent, dar cu spațiu pentru îmbunătățiri.';
    if (score >= 60) return 'SEO acceptabil, necesită atenție suplimentară.';
    if (score >= 50) return 'SEO slab, necesită optimizare urgentă.';
    return 'SEO foarte slab, necesită refacere completă.';
}

/**
     * Chapter 5 – Content – 20 points
 */
async function analyzeContentCriterion(criterionKey, criterionConfig, formData) {
    const { mainKeyword } = formData;
    
    // Normalize keyword for diacritics-aware comparison
    const normalizedKeyword = mainKeyword ? normalizeText(mainKeyword) : '';
    
    console.log(`🔍 Content Analysis - ${criterionConfig.name}:`);
    
    switch (criterionKey) {
        case 'minWordCount': // 3 points
            // Minimum 300 words for real user value
            const wordCount = getContentWordCount();
            console.log(`  Word count: ${wordCount}`);
            
            if (wordCount >= 300) {
                console.log(`✅ Excellent word count (${wordCount} ≥ 300)`);
                return criterionConfig.maxScore;
            } else if (wordCount >= 200) {
                console.log(`⚠️ Good word count (${wordCount} ≥ 200) - partial score`);
                return Math.round(criterionConfig.maxScore * 0.7);
            } else if (wordCount >= 100) {
                console.log(`⚠️ Minimal word count (${wordCount} ≥ 100) - low score`);
                return Math.round(criterionConfig.maxScore * 0.3);
            }
            console.log(`❌ Insufficient word count (${wordCount} < 100)`);
            return 0;
            
        case 'keywordDensity': // 3 points
            // Correct density: 0.8% – 2.5% of total words
            if (!mainKeyword) {
                console.log(`❌ No main keyword provided`);
                return 0;
            }
            
            const mainContent = getMainContent();
            const totalWords = mainContent.split(/\s+/).filter(word => word.length > 0).length;
            
            if (totalWords === 0) {
                console.log(`❌ No content found`);
                return 0;
            }
            
            // Count exact keyword matches (not variations to avoid inflated counts)
            const keywordLower = mainKeyword.toLowerCase();
            const regex = new RegExp(`\\b${keywordLower.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'gi');
            const matches = mainContent.toLowerCase().match(regex) || [];
            const keywordCount = matches.length;
            
            const density = (keywordCount / totalWords) * 100;
            
            console.log(`  ==================== KEYWORD DENSITY ANALYSIS ====================`);
            console.log(`  Keyword: "${mainKeyword}"`);
            console.log(`  Total words in content: ${totalWords}`);
            console.log(`  Exact keyword matches found: ${keywordCount}`);
            console.log(`  Calculated density: ${density.toFixed(2)}%`);
            console.log(`  Content preview (first 200 chars): "${mainContent.substring(0, 200)}..."`);
            
            // Show matches found
            if (matches.length > 0) {
                console.log(`  First 10 matches found: [${matches.slice(0, 10).join(', ')}]`);
            }
            
            console.log(`  Scoring rules:`);
            console.log(`    - Perfect (3p): 0.8% - 2.5%`);
            console.log(`    - Acceptable (2.1p): 0.5% - 3.5%`);
            console.log(`    - Suboptimal (0.9p): 0% - 5%`);
            console.log(`    - Keyword stuffing (0p): > 5%`);
            
            if (density >= 0.8 && density <= 2.5) {
                console.log(`✅ PERFECT keyword density (${density.toFixed(2)}% is within 0.8% - 2.5%) - FULL SCORE`);
                return criterionConfig.maxScore;
            } else if (density >= 0.5 && density <= 3.5) {
                const partialScore = Math.round(criterionConfig.maxScore * 0.7);
                console.log(`⚠️ ACCEPTABLE keyword density (${density.toFixed(2)}% is within 0.5% - 3.5%) - PARTIAL SCORE: ${partialScore}p`);
                return partialScore;
            } else if (density > 0 && density <= 5) {
                const lowScore = Math.round(criterionConfig.maxScore * 0.3);
                console.log(`⚠️ SUBOPTIMAL keyword density (${density.toFixed(2)}% is within 0% - 5%) - LOW SCORE: ${lowScore}p`);
                return lowScore;
            } else if (density > 5) {
                console.log(`❌ KEYWORD STUFFING detected (${density.toFixed(2)}% > 5%) - ZERO SCORE`);
                return 0;
            }
            console.log(`❌ No keyword found in content - ZERO SCORE`);
            return 0;
            
        case 'lsiTerms': // 2 points
            // Synonyms and LSI semantic terms - ChatGPT Enhanced
            if (!mainKeyword) {
                console.log(`❌ No main keyword provided for LSI analysis`);
                return 0;
            }
            
            const lsiContent = getCleanContentForChatGPT();
            console.log(`🤖 Using ChatGPT for LSI Terms analysis...`);
            
            try {
                const lsiResult = await callChatGPTLsiAnalysis(mainKeyword, lsiContent);
                const finalLsiScore = Math.round(criterionConfig.maxScore * lsiResult.lsiScore);
                console.log(`  ChatGPT LSI score: ${finalLsiScore}/${criterionConfig.maxScore}p`);
                console.log(`  Found LSI terms: ${lsiResult.foundLsiTerms.join(', ')}`);
                if (lsiResult.missingSuggestions.length > 0) {
                    console.log(`  Suggested improvements: ${lsiResult.missingSuggestions.join(', ')}`);
                }
                return finalLsiScore;
            } catch (error) {
                console.log(`⚠️ ChatGPT LSI analysis failed, using fallback...`);
                const fallbackScore = checkLSITerms(mainKeyword, lsiContent);
                const finalScore = Math.round(criterionConfig.maxScore * fallbackScore);
                console.log(`  Fallback LSI score: ${finalScore}/${criterionConfig.maxScore}p`);
                return finalScore;
            }
            
        case 'formatting': // 2 points
            // Lists, bold text, short paragraphs for visual scanning
            const formattingScore = checkContentFormatting();
            const finalFormattingScore = Math.round(criterionConfig.maxScore * formattingScore);
            console.log(`  Formatting score: ${finalFormattingScore}/${criterionConfig.maxScore}p`);
            return finalFormattingScore;
            
        case 'uniqueContent': // 3 points
            // Unique, original content - ChatGPT Enhanced
            const content = getCleanContentForChatGPT();
            console.log(`🤖 Using ChatGPT for content uniqueness analysis...`);
            
            try {
                const uniquenessResult = await callChatGPTUniquenessAnalysis(content);
                const finalUniquenessScore = Math.round(criterionConfig.maxScore * uniquenessResult.uniquenessScore);
                console.log(`  ChatGPT uniqueness score: ${finalUniquenessScore}/${criterionConfig.maxScore}p`);
                console.log(`  Vocabulary diversity: ${(uniquenessResult.vocabularyDiversity * 100).toFixed(1)}%`);
                if (uniquenessResult.issues.length > 0) {
                    console.log(`  Issues found: ${uniquenessResult.issues.join(', ')}`);
                }
                if (uniquenessResult.recommendations.length > 0) {
                    console.log(`  Recommendations: ${uniquenessResult.recommendations.join(', ')}`);
                }
                return finalUniquenessScore;
            } catch (error) {
                console.log(`⚠️ ChatGPT uniqueness analysis failed, using fallback...`);
                const fallbackScore = checkContentUniqueness();
                const finalScore = Math.round(criterionConfig.maxScore * fallbackScore);
                console.log(`  Fallback uniqueness score: ${finalScore}/${criterionConfig.maxScore}p`);
                return finalScore;
            }
            
        case 'tldrPresent': // 2 points
            // TL;DR/Introductory summary present
            const hasTLDR = checkForTLDR();
            const tldrScore = hasTLDR ? criterionConfig.maxScore : 0;
            console.log(`  TL;DR present: ${hasTLDR ? 'YES' : 'NO'} - ${tldrScore}/${criterionConfig.maxScore}p`);
            return tldrScore;
            
        case 'noKeywordLink': // 2 points
            // No link on main keyword (avoids manipulation)
            if (!mainKeyword) {
                console.log(`⚠️ No keyword to check for links - assuming good`);
                return criterionConfig.maxScore;
            }
            
            const hasKeywordLink = checkKeywordLink(mainKeyword);
            const linkScore = !hasKeywordLink ? criterionConfig.maxScore : 0;
            console.log(`  Keyword link found: ${hasKeywordLink ? 'YES (BAD)' : 'NO (GOOD)'} - ${linkScore}/${criterionConfig.maxScore}p`);
            return linkScore;
            
        case 'relevantLinks': // 3 points
            // Relevant internal and external links - ChatGPT Enhanced
            console.log(`🤖 Using ChatGPT for links relevance analysis...`);
            
            try {
                const relevantContent = getCleanContentForChatGPT();
                const internalLinks = extractLinksFromContent('internal');
                const externalLinks = extractLinksFromContent('external');
                
                const linksResult = await callChatGPTLinksAnalysis(mainKeyword, relevantContent, internalLinks, externalLinks);
                
                // Calculate weighted score from all relevance factors
                const weightedScore = (
                    linksResult.internalRelevanceScore * 0.4 +
                    linksResult.externalRelevanceScore * 0.4 +
                    linksResult.anchorQualityScore * 0.2
                );
                
                const finalLinksScore = Math.round(criterionConfig.maxScore * weightedScore);
                console.log(`  ChatGPT links relevance score: ${finalLinksScore}/${criterionConfig.maxScore}p`);
                console.log(`  Internal relevance: ${(linksResult.internalRelevanceScore * 100).toFixed(1)}%`);
                console.log(`  External relevance: ${(linksResult.externalRelevanceScore * 100).toFixed(1)}%`);
                console.log(`  Anchor quality: ${(linksResult.anchorQualityScore * 100).toFixed(1)}%`);
                if (linksResult.suggestions.length > 0) {
                    console.log(`  Suggestions: ${linksResult.suggestions.join(', ')}`);
                }
                return finalLinksScore;
            } catch (error) {
                console.log(`⚠️ ChatGPT links analysis failed, using fallback...`);
                const fallbackScore = checkRelevantLinks();
                const finalScore = Math.round(criterionConfig.maxScore * fallbackScore);
                console.log(`  Fallback links score: ${finalScore}/${criterionConfig.maxScore}p`);
                return finalScore;
            }
            
        default:
            console.log(`❌ Unknown content criterion: ${criterionKey}`);
            return 0;
    }
}

/**
 * Chapter 6 – Images – 6 points
 */
/**
 * Chapter 6 – Images – 6 points (according to Google Docs)
 */
function analyzeImagesCriterion(criterionKey, criterionConfig) {
    console.log(`🖼️ Image Analysis - ${criterionConfig.name} (Google Docs specs):`);
    console.log(`🎯 Focus: Product content images only (descriptions, not gallery/decorative)`);
    
    // Get images from product content only (not header, footer, sidebar, etc.)
    let contentImages = [];
    let editorImages = [];
    
    // 1. Check TinyMCE editor content for images (main source for product description)
    if (window.tinymce) {
        const editors = window.tinymce.editors;
        for (let editor of editors) {
            if (editor.getContent) {
                const editorContent = editor.getContent();
                const imageMatches = editorContent.match(/<img[^>]*>/gi) || [];
                editorImages = imageMatches.map(imgTag => {
                    // Create temporary element to parse attributes
                    const tempDiv = document.createElement('div');
                    tempDiv.innerHTML = imgTag;
                    return tempDiv.querySelector('img');
                }).filter(img => img !== null);
                console.log(`  📝 Editor images found: ${imageMatches.length}`);
                break;
            }
        }
    }
    
    // 2. Get images from product content areas only
    const contentSelectors = [
        '.woocommerce-product-details__short-description',
        '.woocommerce-Tabs-panel--description',
        '.product-description',
        '.entry-content',
        '.post-content',
        '.product-content',
        '#content img',
        '.content img',
        'main img'
    ];
    
    // Try each selector and collect images from content areas
    for (const selector of contentSelectors) {
        const contentArea = document.querySelector(selector);
        if (contentArea) {
            const imagesInContent = contentArea.querySelectorAll('img');
            if (imagesInContent.length > 0) {
                contentImages.push(...Array.from(imagesInContent));
                console.log(`  📄 Found ${imagesInContent.length} images in ${selector}`);
                break; // Use first found content area to avoid duplicates
            }
        }
    }
    
    // 3. Fallback: Get ALL images from the page if no content images found
    if (contentImages.length === 0 && editorImages.length === 0) {
        const allPageImages = document.querySelectorAll('img');
        contentImages = Array.from(allPageImages).filter(img => {
            // Exclude common decorative images
            const src = img.src || img.getAttribute('src') || '';
            const isDecorative = src.includes('logo') || 
                                src.includes('icon') || 
                                src.includes('avatar') ||
                                src.includes('banner') ||
                                img.classList.contains('logo') ||
                                img.classList.contains('icon') ||
                                img.classList.contains('avatar');
            return !isDecorative;
        });
        console.log(`  📄 Fallback: Found ${contentImages.length} images from entire page`);
    }
    
    // Remove duplicates and combine editor + content images
    const allImages = [...editorImages];
    contentImages.forEach(img => {
        // Check if image is not already in editor images
        const isDuplicate = editorImages.some(editorImg => 
            (editorImg.src || editorImg.getAttribute('src')) === (img.src || img.getAttribute('src'))
        );
        if (!isDuplicate) {
            allImages.push(img);
        }
    });
    
    const totalImages = allImages;
    const imageCount = totalImages.length;
    
    console.log(`  📝 Editor images: ${editorImages.length}`);
    console.log(`  📄 Content images: ${contentImages.length}`);
    console.log(`  📊 Total product images: ${imageCount}`);
    
    if (imageCount === 0) {
        console.log(`✅ No images found - returning full score for criterion`);
        return criterionConfig.maxScore;
    }
    
    switch (criterionKey) {
        case 'altTexts': // 2 puncte
            // ✅ Fiecare imagine are alt text – 2p
            console.log(`  🔍 Analyzing ALT text for each image...`);
            
            let imagesWithGoodAlt = 0;
            let altDetails = [];
            
            totalImages.forEach((img, index) => {
                const alt = img.alt || '';
                const src = img.src || img.getAttribute('src') || 'unknown';
                const filename = src.split('/').pop() || 'unknown';
                
                // Check alt text quality according to Google Docs
                const hasAlt = alt.trim().length > 0;
                const isDescriptive = alt.length >= 5 && alt.length <= 125; // Lungime rezonabilă
                const notGeneric = !alt.match(/^(image|img|photo|picture|figura?)(\s*\d+)?$/i);
                
                const isGoodAlt = hasAlt && isDescriptive && notGeneric;
                
                altDetails.push({
                    filename,
                    alt: alt || '[MISSING]',
                    status: isGoodAlt ? '✅' : '❌',
                    issues: [
                        !hasAlt ? 'No alt text' : null,
                        hasAlt && !isDescriptive ? 'Too short/long' : null,
                        hasAlt && !notGeneric ? 'Generic text' : null
                    ].filter(Boolean)
                });
                
                if (isGoodAlt) imagesWithGoodAlt++;
            });
            
            // Scoring: Perfect = toate au alt text bun, Partial = proporțional
            const altPercentage = imagesWithGoodAlt / imageCount;
            let altScore;
            
            if (altPercentage === 1) {
                altScore = criterionConfig.maxScore; // 2p pentru toate perfect
            } else if (altPercentage >= 0.8) {
                altScore = Math.round(criterionConfig.maxScore * 0.8); // 80% din punctaj
            } else if (altPercentage >= 0.5) {
                altScore = Math.round(criterionConfig.maxScore * 0.5); // 50% din punctaj
            } else {
                altScore = Math.round(criterionConfig.maxScore * altPercentage); // Proporțional sub 50%
            }
            
            console.log(`  📋 ALT Text Analysis Results:`);
            altDetails.forEach((detail, i) => {
                console.log(`    ${i + 1}. ${detail.filename}: ${detail.status}`);
                console.log(`       Alt: "${detail.alt}"`);
                if (detail.issues.length > 0) {
                    console.log(`       Issues: ${detail.issues.join(', ')}`);
                }
            });
            console.log(`  ✅ Images with good alt text: ${imagesWithGoodAlt}/${imageCount} (${(altPercentage * 100).toFixed(1)}%)`);
            console.log(`  🎯 Score: ${altScore}/${criterionConfig.maxScore}p`);
            
            return altScore;
            
        case 'seoFilenames': // 1 punct
            // ✅ Nume fișier SEO-friendly – 1p
            console.log(`  🔍 Analyzing SEO-friendly filenames...`);
            
            let seoFriendlyCount = 0;
            let filenameDetails = [];
            
            totalImages.forEach((img, index) => {
                const src = img.src || img.getAttribute('src') || '';
                const filename = src.split('/').pop().split('?')[0]; // Remove query params
                
                // SEO-friendly criteria according to Google Docs:
                // - Nume descriptiv, nu generic (IMG_001, foto1, etc.)
                // - Cuvinte separate prin liniuțe
                // - Fără caractere speciale
                // - Lowercase preferat
                
                const isDescriptive = !filename.match(/^(img|image|photo|pic|figura?|dsc|_mg)[\d\-_]/i);
                const hasHyphens = filename.includes('-');
                const noSpecialChars = /^[a-z0-9\-]+\.(jpg|jpeg|png|webp|gif|svg)$/i.test(filename);
                const meaningfulLength = filename.replace(/\.(jpg|jpeg|png|webp|gif|svg)$/i, '').length >= 8;
                
                // Un filename este SEO-friendly dacă îndeplinește majoritatea criteriilor
                const seoScore = [isDescriptive, hasHyphens || meaningfulLength, noSpecialChars].filter(Boolean).length;
                const isSeoFriendly = seoScore >= 2;
                
                const issues = [];
                if (!isDescriptive) issues.push('Generic name');
                if (!hasHyphens && !meaningfulLength) issues.push('Not descriptive enough');
                if (!noSpecialChars) issues.push('Special characters');
                
                filenameDetails.push({
                    filename,
                    status: isSeoFriendly ? '✅' : '❌',
                    issues: issues
                });
                
                if (isSeoFriendly) seoFriendlyCount++;
            });
            
            // Scoring pentru nume fișiere
            const seoPercentage = seoFriendlyCount / imageCount;
            const seoScore = seoPercentage === 1 ? 
                criterionConfig.maxScore : 
                Math.round(criterionConfig.maxScore * seoPercentage);
            
            console.log(`  📋 SEO Filename Analysis Results:`);
            filenameDetails.forEach((detail, i) => {
                console.log(`    ${i + 1}. ${detail.filename}: ${detail.status}`);
                if (detail.issues.length > 0) {
                    console.log(`       Issues: ${detail.issues.join(', ')}`);
                }
            });
            console.log(`  ✅ SEO-friendly filenames: ${seoFriendlyCount}/${imageCount} (${(seoPercentage * 100).toFixed(1)}%)`);
            console.log(`  🎯 Score: ${seoScore}/${criterionConfig.maxScore}p`);
            
            return seoScore;
            
        case 'optimizedSize': // 2 puncte
            // ✅ Dimensiuni optimizate (<200kb) – 2p
            console.log(`  🔍 Analyzing image optimization...`);
            
            let optimizedCount = 0;
            let optimizationDetails = [];
            
            totalImages.forEach((img, index) => {
                const src = img.src || img.getAttribute('src') || '';
                const filename = src.split('/').pop();
                
                // Optimization indicators according to Google Docs:
                // - Format modern (WebP preferat)
                // - Dimensiuni rezonabile
                // - Srcset pentru responsive
                // - Compresie (estimat prin format și practici)
                
                const hasWebP = /\.webp$/i.test(filename);
                const hasJPEG = /\.(jpg|jpeg)$/i.test(filename);
                const hasPNG = /\.png$/i.test(filename);
                const hasResponsive = img.hasAttribute('srcset') || img.hasAttribute('sizes');
                const hasReasonableDimensions = img.width && img.height && 
                    (img.width <= 1920 && img.height <= 1920); // Nu excesiv de mari
                
                // WebP = cel mai bun format pentru optimizare
                // JPEG cu responsive = bun
                // PNG fără responsive = acceptabil pentru imagini simple
                let optimizationScore = 0;
                const features = [];
                
                if (hasWebP) {
                    optimizationScore += 3;
                    features.push('WebP format');
                } else if (hasJPEG) {
                    optimizationScore += 2;
                    features.push('JPEG format');
                } else if (hasPNG) {
                    optimizationScore += 1;
                    features.push('PNG format');
                }
                
                if (hasResponsive) {
                    optimizationScore += 2;
                    features.push('Responsive');
                }
                
                if (hasReasonableDimensions) {
                    optimizationScore += 1;
                    features.push('Good dimensions');
                }
                
                // Considerăm optimizată dacă scorul >= 3 (ex: JPEG + responsive)
                const isOptimized = optimizationScore >= 3;
                
                optimizationDetails.push({
                    filename,
                    status: isOptimized ? '✅' : '❌',
                    features: features,
                    score: optimizationScore
                });
                
                if (isOptimized) optimizedCount++;
            });
            
            // Scoring pentru optimizare
            const optimizedPercentage = optimizedCount / imageCount;
            let optimizationScore;
            
            if (optimizedPercentage === 1) {
                optimizationScore = criterionConfig.maxScore; // 2p pentru toate optimizate
            } else if (optimizedPercentage >= 0.8) {
                optimizationScore = Math.round(criterionConfig.maxScore * 0.8);
            } else if (optimizedPercentage >= 0.5) {
                optimizationScore = Math.round(criterionConfig.maxScore * 0.6);
            } else {
                optimizationScore = Math.round(criterionConfig.maxScore * optimizedPercentage);
            }
            
            console.log(`  📋 Image Optimization Analysis Results:`);
            optimizationDetails.forEach((detail, i) => {
                console.log(`    ${i + 1}. ${detail.filename}: ${detail.status} (score: ${detail.score})`);
                console.log(`       Features: ${detail.features.join(', ') || 'none'}`);
            });
            console.log(`  ✅ Optimized images: ${optimizedCount}/${imageCount} (${(optimizedPercentage * 100).toFixed(1)}%)`);
            console.log(`  🎯 Score: ${optimizationScore}/${criterionConfig.maxScore}p`);
            
            return optimizationScore;
            
        case 'lazyLoading': // 1 punct
            // ✅ Lazy loading activ – 1p
            console.log(`  🔍 Analyzing lazy loading implementation...`);
            console.log(`  📊 Total images found: ${imageCount}`);
            
            let lazyLoadingCount = 0;
            let lazyDetails = [];
            
            totalImages.forEach((img, index) => {
                const src = img.src || img.getAttribute('src') || '';
                const filename = src.split('/').pop();
                
                // Check lazy loading presence according to Google Docs
                const hasLazyAttr = img.hasAttribute('loading') && img.getAttribute('loading') === 'lazy';
                const hasDataSrc = img.hasAttribute('data-src'); // Alternative lazy loading
                const hasLazyClass = img.classList.contains('lazy') || img.classList.contains('lazyload');
                
                const hasLazyLoading = hasLazyAttr || hasDataSrc || hasLazyClass;
                
                const indicators = [];
                if (hasLazyAttr) indicators.push('loading="lazy"');
                if (hasDataSrc) indicators.push('data-src');
                if (hasLazyClass) indicators.push('lazy class');
                
                lazyDetails.push({
                    filename,
                    status: hasLazyLoading ? '✅' : '❌',
                    indicators: indicators
                });
                
                if (hasLazyLoading) lazyLoadingCount++;
            });
            
            // Scoring pentru lazy loading - toate sau niciuny
            const lazyPercentage = lazyLoadingCount / imageCount;
            const lazyScore = lazyPercentage === 1 ? 
                criterionConfig.maxScore : 
                Math.round(criterionConfig.maxScore * lazyPercentage);
            
            console.log(`  📋 Lazy Loading Analysis Results:`);
            lazyDetails.forEach((detail, i) => {
                console.log(`    ${i + 1}. ${detail.filename}: ${detail.status}`);
                if (detail.indicators.length > 0) {
                    console.log(`       Methods: ${detail.indicators.join(', ')}`);
                }
            });
            console.log(`  ✅ Images with lazy loading: ${lazyLoadingCount}/${imageCount} (${(lazyPercentage * 100).toFixed(1)}%)`);
            console.log(`  🎯 Score: ${lazyScore}/${criterionConfig.maxScore}p`);
            
            return lazyScore;
            
        default:
            console.log(`❌ Unknown images criterion: ${criterionKey}`);
            return 0;
    }
}

/**
 * Chapter 7 – Internal Links – 4 points
 */
async function analyzeInternalLinksCriterion(criterionKey, criterionConfig) {
    // Use extractLinksFromContent for consistency - only analyze content, not entire page
    const internalLinksList = extractLinksFromContent('internal');
    
    // Also get DOM links for fallback functionality checks (but not for counting)
    const allLinks = document.querySelectorAll('a[href]');
    const internalLinksDOM = Array.from(allLinks).filter(link => {
        const href = link.href;
        return href && (href.startsWith(window.location.origin) || href.startsWith('/'));
    });
    
    switch (criterionKey) {
        case 'hasInternalLink': // 1.5 puncte
            // At least one internal link - use content-based detection
            console.log(`🔗 Checking for internal links in content...`);
            console.log(`  Found ${internalLinksList.length} internal links in content:`, internalLinksList.map(l => l.url));
            console.log(`  (For comparison: ${internalLinksDOM.length} total internal links in DOM)`);
            return internalLinksList.length >= 1 ? criterionConfig.maxScore : 0;
            
        case 'functionalLinks': // 1.5 puncte
            // Functional links (no 404) - API Enhanced
            console.log(`🔗 Using Links Functionality API for internal links check...`);
            
            try {
                if (internalLinksList.length === 0) {
                    console.log(`  No internal links found - returning 0p (no links to check)`);
                    return 0; // ✅ CORRECTED: Return 0 when no internal links exist
                }
                
                const linksResult = await callLinksFunctionalityAnalysisAPI(internalLinksList);
                const internalWorking = linksResult.linkDetails.filter(link => 
                    link.linkType === 'internal' && link.isWorking).length;
                const internalTotal = linksResult.linkDetails.filter(link => 
                    link.linkType === 'internal').length;
                
                const functionalPercentage = internalTotal > 0 ? (internalWorking / internalTotal) : 1.0;
                const functionalScore = Math.round(criterionConfig.maxScore * functionalPercentage);
                
                console.log(`  Functional internal links API: ${internalWorking}/${internalTotal} - ${functionalScore}/${criterionConfig.maxScore}p`);
                if (linksResult.brokenLinks > 0) {
                    console.log(`  ⚠️ Found ${linksResult.brokenLinks} broken links`);
                }
                
                return functionalScore;
            } catch (error) {
                console.log(`⚠️ Links Functionality API failed, using fallback...`);
                
                // Fallback to original logic using DOM links
                if (internalLinksDOM.length === 0) {
                    console.log(`  No internal links in DOM either - returning 0p`);
                    return 0; // ✅ CORRECTED: Return 0 when no internal links exist
                }
                
                const functionalLinks = internalLinksDOM.filter(link => {
                    const href = link.href.toLowerCase();
                    return !href.includes('404') && 
                           !href.includes('not-found') && 
                           !href.includes('error') &&
                           !href.includes('#') && // Fragment-only links
                           href.length > 5;
                });
                
                const functionalPercentage = (functionalLinks.length / internalLinksDOM.length);
                return Math.round(criterionConfig.maxScore * functionalPercentage);
            }
            
        case 'optimizedAnchor': // 1 punct
            // Anchor text optimizat - analyze content-based links
            console.log(`🔗 Checking optimized anchor text for ${internalLinksList.length} internal links...`);
            
            if (internalLinksList.length === 0) {
                console.log(`  No internal links found in content - returning 0p`);
                return 0; // ✅ CORRECTED: Return 0 when no internal links exist
            }
            
            let optimizedAnchors = 0;
            internalLinksList.forEach(link => {
                const anchorText = link.anchor.trim().toLowerCase();
                // Check if anchor text is descriptive (not just "click here", "read more", etc.)
                const isDescriptive = anchorText.length >= 3 && 
                                    !['click here', 'here', 'more', 'read more', 'link'].includes(anchorText) &&
                                    anchorText.split(' ').length >= 2;
                
                console.log(`    Link: "${anchorText}" → ${isDescriptive ? 'Descriptive' : 'Generic'}`);
                
                if (isDescriptive) optimizedAnchors++;
            });
            
            const percentage = (optimizedAnchors / internalLinksList.length) * 100;
            console.log(`  Optimized anchors: ${optimizedAnchors}/${internalLinksList.length} (${percentage.toFixed(1)}%)`);
            
            if (percentage >= 70) return criterionConfig.maxScore;
            if (percentage >= 50) return Math.floor(criterionConfig.maxScore * 0.7);
            if (percentage >= 30) return Math.floor(criterionConfig.maxScore * 0.4);
            return 0;
            
        default:
            return 0;
    }
}

/**
 * Chapter 8 – External Links – 4 points (NEW)
 */
async function analyzeExternalLinksCriterion(criterionKey, criterionConfig) {
    const allLinks = document.querySelectorAll('a[href]');
    const externalLinks = Array.from(allLinks).filter(link => {
        const href = link.href;
        return href && href.startsWith('http') && !href.startsWith(window.location.origin);
    });
    
    switch (criterionKey) {
        case 'hasExternalLink': // 2 puncte
            // At least one external link
            return externalLinks.length >= 1 ? criterionConfig.maxScore : 0;
            
        case 'functionalExternal': // 1 punct
            // Links are functional - API Enhanced
            console.log(`🔗 Using Links Functionality API for functional external links check...`);
            
            try {
                const externalLinksList = extractLinksFromContent('external');
                
                if (externalLinksList.length === 0) {
                    console.log(`  No external links found - assuming OK`);
                    return criterionConfig.maxScore;
                }
                
                const linksResult = await callLinksFunctionalityAnalysisAPI(externalLinksList);
                const workingLinks = linksResult.workingLinks;
                const totalExternal = linksResult.externalLinks;
                
                const functionalPercentage = totalExternal > 0 ? 
                    (workingLinks / totalExternal) : 1;
                const functionalScore = Math.round(criterionConfig.maxScore * functionalPercentage);
                
                console.log(`  Functional links API: ${workingLinks}/${totalExternal} working - ${functionalScore}/${criterionConfig.maxScore}p`);
                
                return functionalScore;
            } catch (error) {
                console.log(`⚠️ Links Functionality API failed, using fallback heuristic...`);
                
                // Fallback to original heuristic logic
            if (externalLinks.length === 0) return criterionConfig.maxScore;
            
            const validExternalLinks = externalLinks.filter(link => {
                const href = link.href;
                return href.includes('.') && // Has domain
                       !href.includes('javascript:') &&
                       !href.includes('mailto:') &&
                       href.length > 10;
            });
            
            const validPercentage = (validExternalLinks.length / externalLinks.length);
                const heuristicScore = Math.round(criterionConfig.maxScore * validPercentage);
                
                console.log(`  Fallback heuristic: ${validExternalLinks.length}/${externalLinks.length} valid - ${heuristicScore}/${criterionConfig.maxScore}p`);
                
                return heuristicScore;
            }
            
        case 'authorityDomains': // 1 punct
            // Linkuri către domenii de autoritate - API Enhanced
            console.log(`🏛️ Using Links Functionality API for authority domains check...`);
            
            try {
                const externalLinksList = extractLinksFromContent('external');
                
                if (externalLinksList.length === 0) {
                    console.log(`  No external links found - assuming OK`);
                    return criterionConfig.maxScore;
                }
                
                const linksResult = await callLinksFunctionalityAnalysisAPI(externalLinksList);
                const authorityCount = linksResult.authorityLinks;
                const totalExternal = linksResult.externalLinks;
                
                const authorityPercentage = totalExternal > 0 ? 
                    Math.min((authorityCount / totalExternal) * 2, 1) : 0.5;
                const authorityScore = Math.round(criterionConfig.maxScore * authorityPercentage);
                
                console.log(`  Authority domains API: ${authorityCount}/${totalExternal} - ${authorityScore}/${criterionConfig.maxScore}p`);
                
                return authorityScore;
            } catch (error) {
                console.log(`⚠️ Links Functionality API failed, using fallback...`);
                
                // Fallback to original logic
                if (externalLinks.length === 0) return criterionConfig.maxScore;
                
                const authorityDomains = [
                    'wikipedia.org', 'google.com', 'microsoft.com', 'adobe.com',
                    'who.int', 'webmd.com', 'mayo.clinic', 'harvard.edu',
                    'stanford.edu', 'mit.edu', 'gov.', '.edu', '.org'
                ];
                
                let authorityLinks = 0;
                externalLinks.forEach(link => {
                    const href = link.href.toLowerCase();
                    const isAuthority = authorityDomains.some(domain => href.includes(domain));
                    if (isAuthority) authorityLinks++;
                });
                
                const authorityPercentage = Math.min((authorityLinks / externalLinks.length) * 2, 1);
                return Math.round(criterionConfig.maxScore * authorityPercentage);
            }
            
        default:
            return 0;
    }
}

/**
 * Chapter 9 – Backlinks – 15 points (NEW)
 */
async function analyzeBacklinksCriterion(criterionKey, criterionConfig, apiResults) {
    console.log(`🔗 Using Backlinks Analysis API for ${criterionKey}...`);
    
    try {
        const publicUrl = getEntityPublicUrl();
        if (!publicUrl) {
            console.log(`  ⚠️ No public URL found - using neutral score`);
            return Math.round(criterionConfig.maxScore * 0.5);
        }
        
        const backlinksData = await callBacklinksAnalysisAPI(publicUrl);
        
        switch (criterionKey) {
            case 'domainBacklinks': // 7 puncte
                // Backlink-uri către domeniu
                const domainBacklinks = backlinksData.domainBacklinks || 0;
                
                console.log(`  Domain backlinks found: ${domainBacklinks}`);
                
                if (domainBacklinks >= 100) return criterionConfig.maxScore;
                if (domainBacklinks >= 50) return Math.round(criterionConfig.maxScore * 0.8);
                if (domainBacklinks >= 20) return Math.round(criterionConfig.maxScore * 0.6);
                if (domainBacklinks >= 5) return Math.round(criterionConfig.maxScore * 0.4);
                if (domainBacklinks >= 1) return Math.round(criterionConfig.maxScore * 0.2);
                return 0;
                
            case 'pageBacklinks': // 6 puncte
                // Backlink-uri către pagină
                const pageBacklinks = backlinksData.pageBacklinks || 0;
                
                console.log(`  Page backlinks found: ${pageBacklinks}`);
                
                if (pageBacklinks >= 50) return criterionConfig.maxScore;
                if (pageBacklinks >= 20) return Math.round(criterionConfig.maxScore * 0.8);
                if (pageBacklinks >= 10) return Math.round(criterionConfig.maxScore * 0.6);
                if (pageBacklinks >= 3) return Math.round(criterionConfig.maxScore * 0.4);
                if (pageBacklinks >= 1) return Math.round(criterionConfig.maxScore * 0.2);
                return 0;
                
            case 'sourceQuality': // 2 puncte
                // Calitatea sursei
                const domainAuthority = backlinksData.domainAuthority || 0;
                
                console.log(`  Domain authority score: ${domainAuthority}`);
                
                if (domainAuthority >= 70) return criterionConfig.maxScore;
                if (domainAuthority >= 50) return Math.round(criterionConfig.maxScore * 0.8);
                if (domainAuthority >= 30) return Math.round(criterionConfig.maxScore * 0.6);
                if (domainAuthority >= 20) return Math.round(criterionConfig.maxScore * 0.4);
                return 0;
                
            default:
                return 0;
        }
    } catch (error) {
        console.log(`  ⚠️ Backlinks API failed, using neutral score: ${error.message}`);
        return Math.round(criterionConfig.maxScore * 0.3); // Conservative fallback
    }
}

/**
 * Chapter 10 – Speed & Performance – 6 points (according to Google Docs)
 */
async function analyzePerformanceCriterion(criterionKey, criterionConfig, apiResults) {
    console.log(`🚀 Using Performance Analysis API for ${criterionKey}...`);
    
    try {
        const publicUrl = getEntityPublicUrl();
        if (!publicUrl) {
            console.log(`  ⚠️ No public URL found - using neutral score`);
            return Math.round(criterionConfig.maxScore * 0.5);
        }
        
        const performanceData = await callPerformanceAnalysisAPI(publicUrl);
        
        switch (criterionKey) {
            case 'mobilePageSpeed':
                // ✅ PageSpeed > 80 pe mobile – 3p
                console.log(`  🔍 Analyzing mobile PageSpeed score...`);
            
                const mobilePerformanceScore = performanceData.mobilePerformanceScore;
                console.log(`  📊 API Mobile Performance Score: ${mobilePerformanceScore} (raw value)`);
                
                // Convert from 0-1 scale to 0-100 scale
                const pagespeedScore = Math.round(mobilePerformanceScore * 100);
                console.log(`  📊 Converted PageSpeed score: ${pagespeedScore}/100`);
                
                // Scoring according to Google Docs: > 80 = good
                if (pagespeedScore > 80) {
                    const score = criterionConfig.maxScore; // 3p pentru > 80
                    console.log(`  ✅ Excellent PageSpeed: ${pagespeedScore} > 80 → ${score}/${criterionConfig.maxScore}p`);
                    return score;
                } else if (pagespeedScore >= 70) {
                    const score = Math.round(criterionConfig.maxScore * 0.7); // 2p pentru 70-80
                    console.log(`  🟡 Good PageSpeed: ${pagespeedScore} (70-80) → ${score}/${criterionConfig.maxScore}p`);
                    return score;
                } else if (pagespeedScore >= 50) {
                    const score = Math.round(criterionConfig.maxScore * 0.4); // 1p pentru 50-70
                    console.log(`  🟠 Average PageSpeed: ${pagespeedScore} (50-70) → ${score}/${criterionConfig.maxScore}p`);
                    return score;
                } else {
                    console.log(`  ❌ Poor PageSpeed: ${pagespeedScore} < 50 → 0/${criterionConfig.maxScore}p`);
                    return 0;
            }
            
            // Fallback: Browser Performance API
            console.log(`  ⚠️ No API data, using browser Performance API fallback...`);
            if (window.performance && window.performance.timing) {
                const timing = window.performance.timing;
                const loadTime = timing.loadEventEnd - timing.navigationStart;
                
                console.log(`  ⏱️ Load time: ${loadTime}ms`);
                
                if (loadTime <= 2000) {
                    const score = criterionConfig.maxScore;
                    console.log(`  ✅ Fast load time: ${loadTime}ms ≤ 2s → ${score}/${criterionConfig.maxScore}p`);
                    return score;
                } else if (loadTime <= 3000) {
                    const score = Math.round(criterionConfig.maxScore * 0.7);
                    console.log(`  🟡 Good load time: ${loadTime}ms ≤ 3s → ${score}/${criterionConfig.maxScore}p`);
                    return score;
                } else if (loadTime <= 5000) {
                    const score = Math.round(criterionConfig.maxScore * 0.4);
                    console.log(`  🟠 Average load time: ${loadTime}ms ≤ 5s → ${score}/${criterionConfig.maxScore}p`);
                    return score;
                } else {
                    console.log(`  ❌ Slow load time: ${loadTime}ms > 5s → 0/${criterionConfig.maxScore}p`);
                    return 0;
                }
            }
            
            console.log(`  ❌ No performance data available → 0/${criterionConfig.maxScore}p`);
            return 0;
            case 'minifiedAssets':
            // ✅ CSS/JS minificat – 2p
                console.log(`  🔍 Analyzing CSS/JS minification via API...`);
                
                const hasMinifiedResources = performanceData.hasMinifiedResources;
                console.log(`  📊 API hasMinifiedResources: ${hasMinifiedResources}`);
                
                if (hasMinifiedResources) {
                    const score = criterionConfig.maxScore;
                    console.log(`  ✅ Minified resources detected → ${score}/${criterionConfig.maxScore}p`);
                    return score;
                } else {
                    console.log(`  ❌ Resources not minified → 0/${criterionConfig.maxScore}p`);
                    return 0;
                }
            case 'lazyLoadingActive':
                // ✅ Lazy loading activ – 1p (Google PageSpeed analysis)
                console.log(`  🔍 Analyzing lazy loading via Performance API...`);
                console.log(`  📊 Full performanceData:`, performanceData);
                
                const hasLazyLoading = performanceData.hasLazyLoading;
                console.log(`  📊 API hasLazyLoading: ${hasLazyLoading} (type: ${typeof hasLazyLoading})`);
                console.log(`  🎯 criterionConfig.maxScore: ${criterionConfig.maxScore}`);
                
                if (hasLazyLoading === true) {
                    const score = criterionConfig.maxScore;
                                    console.log(`  ✅ LAZY LOADING DETECTED → returning score: ${score}/${criterionConfig.maxScore}p`);
                    return score;
                } else {
                    console.log(`  ❌ No lazy loading detected → 0/${criterionConfig.maxScore}p`);
                    console.log(`  🔍 hasLazyLoading value: "${hasLazyLoading}" (type: ${typeof hasLazyLoading})`);
                    return 0;
                }
                    
                
            default:
                return 0;
        }
    } catch (error) {
        console.error(`  ❌ Performance API failed for ${criterionKey}:`, error);
        console.log(`  ⚠️ Using fallback scoring...`);
        
        // Fallback logic for when API fails
        switch (criterionKey) {
            case 'mobilePageSpeed':
                const fallbackPageSpeed = Math.round(criterionConfig.maxScore * 0.5);
                console.log(`  🔄 PageSpeed fallback: ${fallbackPageSpeed}/${criterionConfig.maxScore}p`);
                return fallbackPageSpeed;
            case 'minifiedAssets':
                const fallbackMinified = Math.round(criterionConfig.maxScore * 0.3);
                console.log(`  🔄 Minified fallback: ${fallbackMinified}/${criterionConfig.maxScore}p`);
                return fallbackMinified;
            case 'lazyLoadingActive':
                const fallbackLazy = Math.round(criterionConfig.maxScore * 0.3);
                console.log(`  🔄 Lazy loading fallback: ${fallbackLazy}/${criterionConfig.maxScore}p`);
                return fallbackLazy;
            default:
                console.log(`  🔄 Unknown criterion fallback: 0p`);
                return 0;
        }
    }
}

/**
 * Chapter 11 – Mobile-Friendly – 4 points
 */
async function analyzeMobileFriendlyCriterion(criterionKey, criterionConfig, apiResults) {
    console.log(`📱 Using Mobile-Friendly Analysis API for ${criterionKey}...`);
    
    try {
        const publicUrl = getEntityPublicUrl();
        if (!publicUrl) {
            console.log(`  ⚠️ No public URL found - using neutral score`);
            return Math.round(criterionConfig.maxScore * 0.5);
        }
        
        const mobileData = await callMobileFriendlyAnalysisAPI(publicUrl);
        
        switch (criterionKey) {
            case 'responsiveDesign': // 2.5 puncte
                // Responsive (test Google OK)
                console.log(`  📱 Checking responsive design via API...`);
                
                const isResponsive = mobileData.isResponsive;
                const mobileScore = mobileData.mobileScore || 0;
                console.log(`  📊 API isResponsive: ${isResponsive}`);
                console.log(`  📊 API Mobile Score: ${mobileScore} (${(mobileScore * 100).toFixed(1)}%)`)
                
                if (isResponsive) {
                    const score = criterionConfig.maxScore;
                    console.log(`  ✅ Responsive design detected → ${score}/${criterionConfig.maxScore}p`);
                    return score;
                } else {
                    console.log(`  ❌ Not responsive (Google test failed) → 0/${criterionConfig.maxScore}p`);
                    return 0;
                }
            case 'uiElements': // 1.5 puncte
                // Elemente UI corecte (font, spacing, butoane)
                console.log(`  📱 Checking UI elements via API...`);
                
                const hasCorrectUIElements = mobileData.hasCorrectUIElements;
                console.log(`  📊 API Correct UI Elements: ${hasCorrectUIElements}`);
                
                if (hasCorrectUIElements) {
                    const score = criterionConfig.maxScore;
                    console.log(`  ✅ Correct UI elements detected → ${score}/${criterionConfig.maxScore}p`);
                    return score;
                } else {
                    console.log(`  ❌ UI elements need improvement → 0/${criterionConfig.maxScore}p`);
                    return 0;
                }
                
            default:
                return 0;
        }
    } catch (error) {
        console.log(`  ⚠️ Mobile-Friendly API failed, using fallback: ${error.message}`);
        
        // Fallback logic for when API fails
        switch (criterionKey) {
            case 'responsiveDesign':
                return Math.round(criterionConfig.maxScore * 0.6);
            case 'uiElements':
                return Math.round(criterionConfig.maxScore * 0.5);
            default:
                return 0;
        }
    }
}

/**
 * Chapter 12 – Indexing & Technical SEO – 5 points (according to Google Docs)
 */
async function analyzeTechnicalSeoCriterion(criterionKey, criterionConfig, apiResults) {
    console.log(`🔧 Using Technical SEO Analysis API for ${criterionKey}...`);
    
    try {
        const publicUrl = getEntityPublicUrl();
        if (!publicUrl) {
            console.log(`  ⚠️ No public URL found - using neutral score`);
            return Math.round(criterionConfig.maxScore * 0.5);
        }
        
        const technicalData = await callTechnicalSeoAnalysisAPI(publicUrl);
        
        switch (criterionKey) {
            case 'noUnwantedTags': // 1.5 puncte
                // ✅ Fără taguri noindex/nofollow neintenționate – 1.5p
                console.log(`  🔍 Checking unwanted robots tags via API...`);
                
                const hasNoIndexTag = technicalData.hasNoIndexTag;
                console.log(`  📊 API hasNoIndexTag: ${hasNoIndexTag}`);
                
                if (!hasNoIndexTag) {
                    const score = criterionConfig.maxScore;
                    console.log(`  ✅ No unwanted noindex tags → ${score}/${criterionConfig.maxScore}p`);
                    return score;
                } else {
                    console.log(`  ❌ Found unwanted noindex tags → 0/${criterionConfig.maxScore}p`);
                    return 0;
                }
            case 'canonicalTag': // 1.5 puncte
                // ✅ Tag canonical corect – 1.5p
                console.log(`  🔍 Checking canonical tag via API...`);
                
                const hasCanonical = technicalData.hasCanonical;
                console.log(`  📊 API Canonical tag: ${hasCanonical}`);
                
                if (hasCanonical) {
                    const score = criterionConfig.maxScore;
                    console.log(`  ✅ Canonical tag found → ${score}/${criterionConfig.maxScore}p`);
                    return score;
                } else {
                    console.log(`  ❌ No canonical tag found → 0/${criterionConfig.maxScore}p`);
                    return 0;
                }
            case 'schemaMarkup': // 1.5 puncte
                // ✅ Schema.org valid – 1.5p
                console.log(`  🔍 Checking Schema markup via API...`);
                
                const schemaCount = technicalData.schemaCount || 0;
                console.log(`  📊 API Schema count: ${schemaCount}`);
                
                if (schemaCount > 0) {
                    const score = criterionConfig.maxScore;
                    console.log(`  ✅ Found ${schemaCount} Schema markup(s) → ${score}/${criterionConfig.maxScore}p`);
                    return score;
                } else {
                    console.log(`  ❌ No Schema markup found → 0/${criterionConfig.maxScore}p`);
                    return 0;
                }
            case 'hreflang': // 0.5 puncte
                // ✅ Hreflang corect (dacă există versiuni multilingve) – 0.5p
                console.log(`  🔍 Checking hreflang via API...`);
                
                const hreflangCount = technicalData.hreflangCount || 0;
                console.log(`  📊 API Hreflang count: ${hreflangCount}`);
                
                // According to Google Docs specification:
                // "Exemplu greșit: Lipsă hreflang, limbi greșite, sau hreflang autoreferențial absent"
                if (hreflangCount > 0) {
                    const score = criterionConfig.maxScore;
                    console.log(`  ✅ Found ${hreflangCount} hreflang tag(s) → ${score}/${criterionConfig.maxScore}p`);
                    return score;
                } else {
                    // Missing hreflang is listed as "wrong example" in documentation
                    console.log(`  ❌ Missing hreflang (listed as wrong example in docs) → 0/${criterionConfig.maxScore}p`);
                    return 0;
                }
            default:
                return 0;
        }
    } catch (error) {
        console.log(`  ⚠️ Technical SEO API failed, using fallback: ${error.message}`);
        
        // Fallback logic for when API fails
        switch (criterionKey) {
            case 'noUnwantedTags':
                return Math.round(criterionConfig.maxScore * 0.7);
            case 'canonicalTag':
                return Math.round(criterionConfig.maxScore * 0.5);
            case 'schemaMarkup':
                return Math.round(criterionConfig.maxScore * 0.3);
            case 'hreflang':
                return 0; // Conservative: assume missing hreflang when API fails
            default:
                return 0;
        }
    }
}

// Helper functions for content analysis

function getContentWordCount() {
    const content = getMainContent();
    // Normalize content to handle diacritics properly
    const normalizedContent = normalizeText(content);
    // Split on whitespace and filter out empty strings
    return normalizedContent.split(/\s+/).filter(word => word.length > 0).length;
}

function getMainContent() {
    // Try to get content from TinyMCE editors first
    if (window.tinymce) {
        const editors = window.tinymce.editors;
        for (let editor of editors) {
            if (editor.getContent) {
                const content = editor.getContent({ format: 'text' });
                if (content && content.length > 50) {
                    return content;
                }
            }
        }
    }
    
    // Fallback to page content
    const contentSelectors = [
        'main', '.content', '.post-content', '.entry-content',
        '.page-content', 'article', '.single-content'
    ];
    
    for (let selector of contentSelectors) {
        const element = document.querySelector(selector);
        if (element) {
            return element.textContent || element.innerText || '';
        }
    }
    
    return document.body.textContent || document.body.innerText || '';
}

/**
 * Get clean content for ChatGPT analysis (WordPress admin focused)
 */
function getCleanContentForChatGPT() {
    let content = '';
    
    // 1. Try to get content from AYSA meta fields first (most relevant)
    const metaTitle = document.getElementById('aysa-entity-meta-title')?.value || '';
    const metaDescription = document.getElementById('aysa-entity-meta-description')?.value || '';
    const metaKeywords = document.getElementById('aysa-entity-meta-keywords')?.value || '';
    
    // 2. Try to get content from TinyMCE editors (product description, content)
    if (window.tinymce) {
        const editors = window.tinymce.editors;
        for (let editor of editors) {
            if (editor.getContent) {
                const editorContent = editor.getContent({ format: 'text' });
                if (editorContent && editorContent.length > 50) {
                    content += editorContent + '\n\n';
                }
            }
        }
    }
    
    // 3. Try to get from WordPress classic editor
    const classicEditor = document.getElementById('content');
    if (classicEditor && classicEditor.value) {
        // Strip HTML tags for clean text
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = classicEditor.value;
        const cleanText = tempDiv.textContent || tempDiv.innerText || '';
        if (cleanText.length > 50) {
            content += cleanText + '\n\n';
        }
    }
    
    // 4. Try to get WooCommerce product short description
    const shortDesc = document.getElementById('excerpt');
    if (shortDesc && shortDesc.value) {
        content += shortDesc.value + '\n\n';
    }
    
    // 5. Try to get from product/category specific fields
    const productTitle = document.getElementById('title')?.value || '';
    const categoryName = document.getElementById('name')?.value || '';
    const categoryDescription = document.getElementById('description')?.value || '';
    
    // 6. Add relevant meta information
    if (metaTitle) content += 'Title: ' + metaTitle + '\n';
    if (metaDescription) content += 'Description: ' + metaDescription + '\n';
    if (metaKeywords) content += 'Keywords: ' + metaKeywords + '\n';
    if (productTitle) content += 'Product Title: ' + productTitle + '\n';
    if (categoryName) content += 'Category Name: ' + categoryName + '\n';
    if (categoryDescription) content += 'Category Description: ' + categoryDescription + '\n';
    
    // Clean up the content
    content = content
        .replace(/\s+/g, ' ')              // Replace multiple spaces with single space
        .replace(/\n\s*\n/g, '\n')         // Replace multiple newlines with single newline
        .trim();                           // Remove leading/trailing whitespace
    
    // If we still don't have meaningful content, try a very selective DOM approach
    if (content.length < 100) {
        console.log('⚠️ Limited content found in admin fields, trying DOM selectors...');
        
        // Look for content in specific WordPress admin areas only
        const adminContentSelectors = [
            '#wp-content-editor-container .wp-editor-area',
            '#wp-excerpt-editor-container .wp-editor-area', 
            '.woocommerce-product-data .inside',
            '.categorydiv .inside'
        ];
        
        for (let selector of adminContentSelectors) {
            const element = document.querySelector(selector);
            if (element) {
                const elementText = element.textContent || element.innerText || '';
                if (elementText.length > 50) {
                    content += elementText + '\n';
                    break;
                }
            }
        }
    }
    
    console.log(`📝 Extracted clean content for ChatGPT (${content.length} chars):`, content.substring(0, 200) + '...');
    
    return content || 'No meaningful content found for analysis.';
}

function checkLSITerms(mainKeyword, content) {
    if (!mainKeyword || !content) {
        console.log(`❌ LSI: Missing keyword or content`);
        return 0;
    }
    
    // Generate semantic related terms
    const lsiTerms = generateLSITerms(mainKeyword);
    const contentLower = content.toLowerCase();
    
    let foundTerms = 0;
    let foundTermsList = [];
    
    lsiTerms.forEach(term => {
        if (contentLower.includes(term.toLowerCase())) {
            foundTerms++;
            foundTermsList.push(term);
        }
    });
    
    const lsiScore = Math.min(foundTerms / Math.max(lsiTerms.length, 1), 1);
    
    console.log(`  LSI Analysis:`);
    console.log(`    Keyword: "${mainKeyword}"`);
    console.log(`    Generated LSI terms: ${lsiTerms.length}`);
    console.log(`    Found terms: ${foundTerms} (${foundTermsList.join(', ')})`);
    console.log(`    LSI score: ${(lsiScore * 100).toFixed(1)}%`);
    
    return lsiScore;
}

function generateLSITerms(keyword) {
    // Enhanced LSI term generation based on Romanian language patterns
    const keywordLower = keyword.toLowerCase();
    const variations = [];
    
    // Basic word variations (plurals, articles)
    variations.push(
        keywordLower + 'uri', keywordLower + 'ul', keywordLower + 'le',
        keywordLower + 'elor', keywordLower + 'ilor'
    );
    
    // Quality descriptors
    variations.push(
        'cel mai bun ' + keywordLower,
        keywordLower + ' de calitate',
        keywordLower + ' profesional',
        keywordLower + ' modern',
        keywordLower + ' premium',
        keywordLower + ' elegant'
    );
    
    // Service/product context
    variations.push(
        'servicii ' + keywordLower,
        'soluții ' + keywordLower,
        'oferte ' + keywordLower,
        'comenzi ' + keywordLower
    );
    
    // Context-specific terms based on keyword
    if (keywordLower.includes('buchet')) {
        variations.push('flori', 'aranjament floral', 'decorațiune florală', 'trandafiri', 'lalele', 'garoafe');
    }
    if (keywordLower.includes('implant')) {
        variations.push('șurub titan', 'lucrare fixă', 'reabilitare orală', 'proteză dentară', 'stomatologie');
    }
    if (keywordLower.includes('web')) {
        variations.push('site', 'pagină web', 'dezvoltare', 'design', 'programare', 'cod');
    }
    
    // Remove duplicates and empty terms
    return [...new Set(variations)].filter(term => term && term.length > 2);
}

function checkContentFormatting() {
    // Check both editor content and DOM content
    let content = document.querySelector('main, .content, .post-content, .entry-content') || document.body;
    
    // Also check TinyMCE editor content if available
    let editorContent = '';
    if (window.tinymce) {
        const editors = window.tinymce.editors;
        for (let editor of editors) {
            if (editor.getContent) {
                editorContent = editor.getContent();
                break;
            }
        }
    }
    
    let formattingScore = 0;
    let details = [];
    
    // Check for lists (bullet/numbered) - 0.35 points
    const lists = content.querySelectorAll('ul, ol');
    const editorLists = editorContent.match(/<(ul|ol)[^>]*>/gi) || [];
    const totalLists = lists.length + editorLists.length;
    
    if (totalLists > 0) {
        formattingScore += 0.35;
        details.push(`✅ Lists found: ${totalLists}`);
    } else {
        details.push(`❌ No lists found`);
    }
    
    // Check for bold/strong text (emphasized keywords) - 0.35 points
    const boldElements = content.querySelectorAll('b, strong');
    const editorBold = editorContent.match(/<(b|strong)[^>]*>/gi) || [];
    const totalBold = boldElements.length + editorBold.length;
    
    if (totalBold > 0) {
        formattingScore += 0.35;
        details.push(`✅ Bold elements found: ${totalBold}`);
    } else {
        details.push(`❌ No bold elements found`);
    }
    
    // Check for short paragraphs (max 4 lines ≈ 250 chars) - 0.3 points
    const paragraphs = content.querySelectorAll('p');
    let shortParagraphs = 0;
    let totalParagraphs = paragraphs.length;
    
    // Also check editor paragraphs
    const editorParagraphs = editorContent.match(/<p[^>]*>.*?<\/p>/gi) || [];
    totalParagraphs += editorParagraphs.length;
    
    paragraphs.forEach(p => {
        const text = p.textContent || p.innerText || '';
        // Max 4 lines ≈ 250 characters, min 20 characters for meaningful content
        if (text.length >= 20 && text.length <= 250) {
            shortParagraphs++;
        }
    });
    
    // Check editor paragraphs too
    editorParagraphs.forEach(p => {
        const text = p.replace(/<[^>]*>/g, ''); // Strip HTML
        if (text.length >= 20 && text.length <= 250) {
            shortParagraphs++;
        }
    });
    
    if (totalParagraphs > 0) {
        const shortParaPercentage = (shortParagraphs / totalParagraphs);
        if (shortParaPercentage >= 0.7) {
            formattingScore += 0.3;
            details.push(`✅ Good paragraph structure: ${shortParagraphs}/${totalParagraphs} (${(shortParaPercentage * 100).toFixed(1)}%)`);
        } else if (shortParaPercentage >= 0.5) {
            formattingScore += 0.15;
            details.push(`⚠️ Acceptable paragraph structure: ${shortParagraphs}/${totalParagraphs} (${(shortParaPercentage * 100).toFixed(1)}%)`);
        } else {
            details.push(`❌ Poor paragraph structure: ${shortParagraphs}/${totalParagraphs} (${(shortParaPercentage * 100).toFixed(1)}%)`);
        }
    } else {
        details.push(`❌ No paragraphs found`);
    }
    
    const finalScore = Math.min(formattingScore, 1);
    
    console.log(`  Content Formatting Analysis:`);
    details.forEach(detail => console.log(`    ${detail}`));
    console.log(`    Final formatting score: ${(finalScore * 100).toFixed(1)}%`);
    
    return finalScore;
}

function checkContentUniqueness() {
    const content = getMainContent();
    
    // Simple uniqueness heuristics
    if (content.length < 100) return 0.2;
    
    const genericPhrases = [
        'lorem ipsum', 'placeholder text', 'sample content',
        'default text', 'coming soon', 'under construction'
    ];
    
    const hasGeneric = genericPhrases.some(phrase => 
        content.toLowerCase().includes(phrase)
    );
    
    if (hasGeneric) return 0.3;
    
    // Check for content diversity
    const words = content.split(/\s+/);
    const uniqueWords = new Set(words.map(w => w.toLowerCase()));
    const uniquenessRatio = uniqueWords.size / words.length;
    
    if (uniquenessRatio >= 0.6) return 1;
    if (uniquenessRatio >= 0.4) return 0.7;
    if (uniquenessRatio >= 0.2) return 0.4;
    return 0.2;
}

function checkForTLDR() {
    console.log(`🔍 TL;DR Detection - checking for introductory summary BEFORE first H2`);
    
    // Get both editor content and DOM content
    let editorContent = '';
    if (window.tinymce) {
        const editors = window.tinymce.editors;
        for (let editor of editors) {
            if (editor.getContent) {
                editorContent = editor.getContent();
                break;
            }
        }
    }
    
    const content = getMainContent();
    
    // Check editor content first (more accurate for admin)
    if (editorContent) {
        console.log(`📝 Checking editor content for TL;DR structure`);
        return checkTLDRInContent(editorContent, 'editor');
    }
    
    // Fallback to page content
    console.log(`📄 Checking page content for TL;DR structure`);
    return checkTLDRInContent(content, 'page');
}

function checkTLDRInContent(content, source) {
    // Find the position of the first H2
    const h2Match = content.match(/<h2[^>]*>|^## /im);
    let contentBeforeH2 = content;
    
    if (h2Match) {
        const h2Position = h2Match.index;
        contentBeforeH2 = content.substring(0, h2Position);
        console.log(`  First H2 found at position ${h2Position} in ${source}`);
        console.log(`  Content before H2: "${contentBeforeH2.substring(0, 200)}..."`);
    } else {
        console.log(`  No H2 found in ${source} - checking entire content`);
    }
    
    // Strip HTML tags for text analysis
    const textBeforeH2 = contentBeforeH2.replace(/<[^>]*>/g, ' ').trim();
    
    if (textBeforeH2.length < 50) {
        console.log(`❌ Insufficient content before first H2 (${textBeforeH2.length} chars)`);
        return false;
    }
    
    // Analyze content before first H2
    const words = textBeforeH2.split(/\s+/).filter(word => word.length > 0);
    const wordCount = words.length;
    
    console.log(`  Content before H2: ${wordCount} words`);
    console.log(`  Text preview: "${textBeforeH2.substring(0, 150)}..."`);
    
    // Simple rule: Any content of 20-150 words before first H2 = valid TL;DR
    if (wordCount >= 20 && wordCount <= 150) {
        console.log(`✅ VALID TL;DR: ${wordCount} words before first H2 - FULL SCORE`);
        console.log(`💡 Introductory content serves as summary`);
        return true;
    }
    
    if (wordCount < 20) {
        console.log(`❌ Too short for TL;DR (${wordCount} < 20 words)`);
        console.log(`💡 Need at least 20 words before first H2`);
        return false;
    }
    
    if (wordCount > 150) {
        console.log(`❌ Too long for TL;DR (${wordCount} > 150 words)`);
        console.log(`💡 TL;DR should be concise - max 150 words before first H2`);
        return false;
    }
    
    // Fallback
    console.log(`❌ No valid introductory content found before first H2`);
    return false;
}

// Helper function to normalize text (remove diacritics)
function normalizeText(text) {
    if (!text) return '';
    return text.normalize('NFD')
              .replace(/[\u0300-\u036f]/g, '') // Remove diacritics
              .toLowerCase()
              .trim();
}

function checkKeywordLink(mainKeyword) {
    if (!mainKeyword) {
        console.log(`❌ No keyword provided for link check`);
        return false;
    }
    
    console.log(`🔍 Checking for links containing keyword: "${mainKeyword}"`);
    
    const normalizedKeyword = normalizeText(mainKeyword);
    let foundKeywordLink = false;
    let linkDetails = [];
    
    // Check DOM links
    const domLinks = document.querySelectorAll('a');
    console.log(`  Found ${domLinks.length} DOM links`);
    
    domLinks.forEach((link, index) => {
        const linkText = normalizeText(link.textContent || link.innerText || '');
        const href = link.href || link.getAttribute('href') || 'no-href';
        
        if (linkText.includes(normalizedKeyword)) {
            foundKeywordLink = true;
            linkDetails.push(`DOM Link ${index + 1}: "${linkText}" → ${href}`);
        }
    });
    
    // Check editor content for links
    if (window.tinymce) {
        const editors = window.tinymce.editors;
        for (let editor of editors) {
            if (editor.getContent) {
                const editorContent = editor.getContent();
                const linkMatches = editorContent.match(/<a[^>]*>.*?<\/a>/gi) || [];
                
                console.log(`  Found ${linkMatches.length} editor links`);
                
                linkMatches.forEach((linkHtml, index) => {
                    // Extract text content from link
                    const tempDiv = document.createElement('div');
                    tempDiv.innerHTML = linkHtml;
                    const linkElement = tempDiv.querySelector('a');
                    
                    if (linkElement) {
                        const linkText = (linkElement.textContent || '').toLowerCase().trim();
                        const href = linkElement.getAttribute('href') || 'no-href';
                        
                        if (linkText.includes(keywordLower)) {
                            foundKeywordLink = true;
                            linkDetails.push(`Editor Link ${index + 1}: "${linkText}" → ${href}`);
                        }
                    }
                });
                break;
            }
        }
    }
    
    console.log(`  Links containing keyword "${mainKeyword}":`);
    if (linkDetails.length > 0) {
        linkDetails.forEach(detail => console.log(`    ✅ ${detail}`));
        console.log(`  🚨 KEYWORD LINK FOUND - This is BAD for SEO (Google sees as manipulative)`);
    } else {
        console.log(`    ❌ No links found containing keyword`);
        console.log(`  ✅ GOOD - No keyword links detected`);
    }
    
    return foundKeywordLink;
}

function checkRelevantLinks() {
    const hostname = window.location.hostname;
    
    // Get all links from content
    const allLinks = document.querySelectorAll('a[href]');
    
    let internalLinks = [];
    let externalLinks = [];
    let competitorLinks = [];
    
    // Classify links
    allLinks.forEach(link => {
        const href = link.getAttribute('href');
        if (!href) return;
        
        // Skip anchor links, mailto, tel, etc.
        if (href.startsWith('#') || href.startsWith('mailto:') || href.startsWith('tel:')) {
            return;
        }
        
        // Internal links
        if (href.startsWith('/') || href.includes(hostname)) {
            internalLinks.push(link);
        }
        // External links
        else if (href.startsWith('http')) {
            // Check if it's a competitor (commercial site in same niche)
            const domain = new URL(href).hostname;
            const isCommercial = /\.(ro|com|net|org|biz)$/.test(domain);
            const hasCommercialKeywords = /shop|store|buy|sell|price|magazin|cumpar|vand|pret/.test(href.toLowerCase());
            
            if (isCommercial && hasCommercialKeywords) {
                competitorLinks.push(link);
            } else {
                externalLinks.push(link);
            }
        }
    });
    
    let linkScore = 0;
    let details = [];
    
    // Internal links requirement: minimum 1 relevant internal link (1.5p out of 3p)
    if (internalLinks.length >= 1) {
        linkScore += 0.5; // 50% of total score
        details.push(`✅ Internal links: ${internalLinks.length}`);
    } else {
        details.push(`❌ No internal links found`);
    }
    
    // External links requirement: minimum 1 external link to authority source (1.5p out of 3p)
    if (externalLinks.length >= 1) {
        // Check for authority domains
        const authorityDomains = [
            'wikipedia.org', 'gov.ro', '.edu', 'pubmed.ncbi.nlm.nih.gov',
            'scholar.google.com', 'researchgate.net', 'academia.edu',
            'who.int', 'europa.eu', 'ec.europa.eu'
        ];
        
        const hasAuthorityLink = externalLinks.some(link => {
            const href = link.getAttribute('href');
            return authorityDomains.some(domain => href.includes(domain));
        });
        
        if (hasAuthorityLink) {
            linkScore += 0.5; // Full points for authority links
            details.push(`✅ External authority links: ${externalLinks.length} (including authority sources)`);
        } else {
            linkScore += 0.3; // Partial points for regular external links
            details.push(`⚠️ External links: ${externalLinks.length} (no clear authority sources)`);
        }
    } else {
        details.push(`❌ No external links found`);
    }
    
    // Penalty for competitor links
    if (competitorLinks.length > 0) {
        linkScore = Math.max(0, linkScore - 0.2);
        details.push(`⚠️ Competitor links detected: ${competitorLinks.length} (penalty applied)`);
    }
    
    const finalScore = Math.min(linkScore, 1);
    
    console.log(`  Relevant Links Analysis:`);
    details.forEach(detail => console.log(`    ${detail}`));
    console.log(`    Final links score: ${(finalScore * 100).toFixed(1)}%`);
    
    return finalScore;
}

/**
 * Update category score display in UI
 */
function updateCategoryScoreDisplay(categoryKey, categoryScore) {
    console.log(`🎨 Updating UI for category: ${categoryScore.categoryName} (${categoryScore.totalScore}/${categoryScore.maxScore})`);
    
    // Reset data-updated attributes to allow fresh matching
    document.querySelectorAll('[data-updated]').forEach(el => el.removeAttribute('data-updated'));
    
    // Update individual criteria scores
    Object.entries(categoryScore.criteriaScores).forEach(([criterionKey, criterionScore]) => {
        console.log(`  🔍 Looking for criterion: "${criterionScore.name}" with maxScore: ${criterionScore.maxScore}`);
        
        let criterionElement = null;
        
        // Method 1: Find by exact criterion name match
        const allCriterionLabels = document.querySelectorAll('.criterion-label');
        for (let label of allCriterionLabels) {
            const labelText = label.textContent.trim();
            if (labelText === criterionScore.name) {
                const scoreElement = label.parentElement?.querySelector('.criterion-score');
                if (scoreElement && scoreElement.getAttribute('data-score') == criterionScore.maxScore) {
                    criterionElement = scoreElement;
                    console.log(`  ✅ Found exact match for "${criterionScore.name}"`);
                    break;
            }
            }
        }
        

        
        // Method 2: Find by partial name match and score
        if (!criterionElement) {
        const scoreElements = document.querySelectorAll(`[data-score="${criterionScore.maxScore}"]`);
        for (let element of scoreElements) {
            const label = element.parentElement?.querySelector('.criterion-label');
            if (label) {
                const labelText = label.textContent.toLowerCase();
                    const criterionNameLower = criterionScore.name.toLowerCase();
                    
                    // Check for key words from the criterion name
                    const keyWords = criterionNameLower.split(' ').filter(word => word.length > 3);
                    const matchingWords = keyWords.filter(word => labelText.includes(word));
                    
                    if (matchingWords.length >= Math.min(2, keyWords.length)) {
                    criterionElement = element;
                        console.log(`  ✅ Found partial match for "${criterionScore.name}" (${matchingWords.length}/${keyWords.length} words)`);
                    break;
                    }
                }
            }
        }
        
        // Method 3: Fallback by category section and position
        if (!criterionElement) {
            // Find the category section
                const allH4 = document.querySelectorAll('h4');
            let categorySection = null;
            
                for (let h4 of allH4) {
                const h4Text = h4.textContent.toLowerCase();
                if ((categoryKey === 'headings' && (h4Text.includes('headings') || h4Text.includes('h1–h3'))) ||
                    (categoryKey === 'content' && h4Text.includes('content')) ||
                    (categoryKey === 'images' && h4Text.includes('images')) ||
                    (categoryKey === 'metaTitle' && h4Text.includes('page title')) ||
                    (categoryKey === 'metaDescription' && h4Text.includes('meta description')) ||
                    (categoryKey === 'url' && h4Text.includes('url')) ||
                    (categoryKey === 'internalLinks' && h4Text.includes('internal links')) ||
                    (categoryKey === 'externalLinks' && h4Text.includes('external links')) ||
                    (categoryKey === 'backlinks' && h4Text.includes('backlinks')) ||
                    (categoryKey === 'performance' && h4Text.includes('speed')) ||
                    (categoryKey === 'mobileFriendly' && h4Text.includes('mobile')) ||
                    (categoryKey === 'technicalSeo' && h4Text.includes('technical'))) {
                    categorySection = h4.parentElement;
                    break;
                }
            }
            
            if (categorySection) {
                const scoreElements = categorySection.querySelectorAll(`[data-score="${criterionScore.maxScore}"]`);
                if (scoreElements.length > 0) {
                    // Try to match by position or find the first unmatched element
                    for (let element of scoreElements) {
                        if (!element.hasAttribute('data-updated')) {
                            criterionElement = element;
                            element.setAttribute('data-updated', 'true');
                            console.log(`  🎯 Found by category section for "${criterionScore.name}"`);
                        break;
                        }
                    }
                }
            }
        }
        
        if (criterionElement) {

            
            // Verifică dacă criteriul este în dezvoltare
            if (criterionScore.inDevelopment) {
                // Afișare specială pentru criterii în dezvoltare
                criterionElement.textContent = criterionScore.developmentText;
                
                // Stil greyed out pentru dezvoltare
                criterionElement.style.backgroundColor = '#f8f9fa';
                criterionElement.style.color = '#6c757d';
                criterionElement.style.fontStyle = 'italic';
                criterionElement.style.fontWeight = 'normal';
                criterionElement.style.opacity = '0.7';
                
                // Adaugă și un indicator vizual pentru criteriul întreg
                const parentRow = criterionElement.closest('.criterion-row, .scoring-row, tr');
                if (parentRow) {
                    parentRow.style.opacity = '0.6';
                    parentRow.title = 'This functionality is in development';
                }
                
                console.log(`  🚧 Updated "${criterionScore.name}": ${criterionScore.developmentText} (in development)`);
            } else {
                // Afișare normală pentru criterii active
                const newScore = `${criterionScore.score}/${criterionScore.maxScore}p`;
                criterionElement.textContent = newScore;
                
                // Add color coding
                const percentage = (criterionScore.score / criterionScore.maxScore) * 100;
                if (percentage >= 80) {
                    criterionElement.style.backgroundColor = '#d4edda';
                    criterionElement.style.color = '#155724';
                    criterionElement.style.fontWeight = 'bold';
                } else if (percentage >= 60) {
                    criterionElement.style.backgroundColor = '#fff3cd';
                    criterionElement.style.color = '#856404';
                    criterionElement.style.fontWeight = 'normal';
                } else {
                    criterionElement.style.backgroundColor = '#f8d7da';
                    criterionElement.style.color = '#721c24';
                    criterionElement.style.fontWeight = 'normal';
                }
                
                console.log(`  ✅ Updated "${criterionScore.name}": ${newScore}`);
                
                // Confirmation for Lazy loading criteria
                if (criterionScore.name.includes('Lazy loading active')) {
                    console.log(`✅ ${criterionScore.name} updated successfully!`);
                }
            }
        } else {
            console.warn(`  ⚠️ Could not find UI element for "${criterionScore.name}" (maxScore: ${criterionScore.maxScore})`);
            
            // Debug: log all available elements with this maxScore
            const allWithScore = document.querySelectorAll(`[data-score="${criterionScore.maxScore}"]`);
            console.log(`  🔍 Found ${allWithScore.length} elements with data-score="${criterionScore.maxScore}"`);
            allWithScore.forEach((el, i) => {
                const label = el.parentElement?.querySelector('.criterion-label');
                console.log(`    ${i}: "${label ? label.textContent : 'NO LABEL'}" -> "${el.textContent}"`);
            });
        }
    });
}

/**
 * Update total score displays
 */
function updateTotalScoreDisplay(totalScore, percentageScore) {
    console.log(`📊 Updating total score displays: ${totalScore}/100 (${percentageScore}%)`);
    
    const scoreOutOf10 = (totalScore / 10).toFixed(1);
    const grade = getScoreGrade(percentageScore);
    
    // Update all score display elements (avoid duplication)
    const scoreElements = new Set();
    
    // Collect all unique score elements
    document.querySelectorAll('.score-value, .score-text, .score-display').forEach(el => scoreElements.add(el));
    
    // Update score elements
    scoreElements.forEach(element => {
        if (element.textContent && element.textContent.includes('Calculating...')) {
            element.textContent = scoreOutOf10;
        } else if (element.classList.contains('score-value') || element.classList.contains('score-text') || element.classList.contains('score-display')) {
            element.textContent = scoreOutOf10;
        }
    });
    
    // Update grade display
    const gradeElements = document.querySelectorAll('.score-grade');
    gradeElements.forEach(element => {
        element.textContent = grade;
        element.className = `score-grade grade-${grade.toLowerCase().replace('+', 'plus').replace('-', 'minus')}`;
    });
    
    // Update progress bars
    const progressBars = document.querySelectorAll('.progress-bar');
    progressBars.forEach(bar => {
        bar.style.width = percentageScore + '%';
        bar.style.backgroundColor = getScoreColor(percentageScore);
    });
    
    // Update progress bars in score box
    const scoreProgressBars = document.querySelectorAll('.progress-bar-container .progress-bar');
    scoreProgressBars.forEach(bar => {
        bar.style.width = percentageScore + '%';
    });
    
    console.log(`✅ Updated score display: ${scoreOutOf10}/10 (${grade})`);
}

/**
 * Generate comprehensive SEO conclusions
 */
function generateComprehensiveConclusions(categoryScores, totalScore, percentageScore) {
    console.log(`📋 Generating comprehensive SEO conclusions...`);
    
    const recommendations = [];
    
    // Analyze each category for recommendations
    Object.values(categoryScores).forEach(category => {
        const categoryPercentage = (category.totalScore / category.maxScore) * 100;
        
        if (categoryPercentage < 70) {
            recommendations.push({
                category: category.categoryName,
                score: categoryPercentage,
                priority: categoryPercentage < 50 ? 'high' : 'medium',
                message: `Improvements needed for ${category.categoryName}`
            });
        }
    });
    
    // Sort by priority and score
    recommendations.sort((a, b) => {
        if (a.priority === 'high' && b.priority !== 'high') return -1;
        if (b.priority === 'high' && a.priority !== 'high') return 1;
        return a.score - b.score;
    });
    
    console.log(`📝 Generated ${recommendations.length} recommendations:`, recommendations);
    
    return {
        totalScore,
        percentageScore,
        grade: getScoreGrade(percentageScore),
        description: getScoreDescription(percentageScore),
        recommendations: recommendations.slice(0, 5) // Top 5 recommendations
    };
}

/**
 * Get score grade
 */
function getScoreGrade(score) {
    if (score >= 90) return 'A+';
    if (score >= 85) return 'A';
    if (score >= 80) return 'A-';
    if (score >= 75) return 'B+';
    if (score >= 70) return 'B';
    if (score >= 65) return 'B-';
    if (score >= 60) return 'C+';
    if (score >= 55) return 'C';
    if (score >= 50) return 'C-';
    if (score >= 40) return 'D';
    return 'F';
}

/**
 * Get score text based on percentage
 */
function getScoreText(score) {
    if (score >= 90) return 'Perfect';
    if (score >= 80) return 'Excellent';
    if (score >= 70) return 'Good';
    if (score >= 60) return 'Fair';
    if (score >= 50) return 'Needs Work';
    return 'Poor';
}

/**
 * Add new API call for comprehensive analysis
 */
async function callBacklinksApi(url) {
    try {
        console.log('🔗 Calling Backlinks API for:', url);
        
        const response = await fetch(`${AYSA_API_CONFIG.baseUrl}${AYSA_API_CONFIG.endpoints.backlinks}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify({ url: url })
        });

        if (!response.ok) {
            throw new Error(`Backlinks API HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        console.log('🔗 Backlinks API Success:', data);
        
        return {
            success: true,
            data: data,
            error: null
        };
    } catch (error) {
        console.error('❌ Backlinks API Error:', error);
        return {
            success: false,
            data: null,
            error: error.message
        };
    }
}

/**
 * Comprehensive API calls disabled - using DOM-based analysis only
 */
async function callComprehensiveSeoApi(url) {
    console.log('🚫 Comprehensive API calls disabled - using DOM-based analysis only');
    return null;
}

// =======================
// DEBUG FUNCTIONS
// =======================





/**
 * ChatGPT Integration Functions for SEO Scoring
 */

/**
 * Call ChatGPT for LSI terms analysis
 */
async function callChatGPTLsiAnalysis(primaryKeyword, content) {
    const apiUrl = buildAysaApiUrl('api/chatgpt/analyze-lsi-terms');
    
    // Use clean content extraction function if content parameter is null/empty
    let cleanContent = content;
    if (!cleanContent || cleanContent.trim().length < 100) {
        cleanContent = getCleanContentForChatGPT();
    }
    
    // Limit content for API
    cleanContent = cleanContent.substring(0, 4000).trim();
    
    const requestData = {
        primaryKeyword: primaryKeyword,
        content: cleanContent,
        language: getLanguageOptimizeValue() || 'english'
    };
    
    console.log('🤖 Calling ChatGPT LSI Analysis API...', { 
        keyword: primaryKeyword, 
        originalLength: content ? content.length : 0,
        cleanLength: cleanContent.length,
        preview: cleanContent.substring(0, 150) + '...',
        requestData: requestData
    });
    
    const response = await fetch(apiUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Origin': window.location.origin
        },
        body: JSON.stringify(requestData),
        mode: 'cors'
    });

    if (!response.ok) {
        const errorText = await response.text();
        console.error(`❌ ChatGPT LSI API failed: ${response.status} ${response.statusText}`, errorText);
        throw new Error(`ChatGPT LSI API failed: ${response.status} ${response.statusText}`);
    }

    const result = await response.json();
    console.log('✅ ChatGPT LSI Analysis result:', result);

    // Handle the response structure correctly
    return {
        lsiScore: result.lsiScore || result.LsiScore || 0.5,
        foundLsiTerms: result.foundLsiTerms || result.FoundLsiTerms || [],
        missingSuggestions: result.missingSuggestions || result.MissingSuggestions || []
    };
}

/**
 * Call ChatGPT for content uniqueness analysis
 */
async function callChatGPTUniquenessAnalysis(content) {
    const apiUrl = buildAysaApiUrl('api/chatgpt/analyze-content-uniqueness');
    
    // Use clean content extraction function if content parameter is null/empty
    let cleanContent = content;
    if (!cleanContent || cleanContent.trim().length < 100) {
        cleanContent = getCleanContentForChatGPT();
    }
    
    // Limit content for API
    cleanContent = cleanContent.substring(0, 4000).trim();
    
    const requestData = {
        content: cleanContent,
        checkGenericPhrases: true,
        language: getLanguageOptimizeValue() || 'english'
    };
    
    console.log('🤖 Calling ChatGPT Uniqueness Analysis API...', { 
        originalLength: content ? content.length : 0,
        cleanLength: cleanContent.length,
        preview: cleanContent.substring(0, 150) + '...',
        requestData: requestData
    });
    
    const response = await fetch(apiUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Origin': window.location.origin
        },
        body: JSON.stringify(requestData),
        mode: 'cors'
    });

    if (!response.ok) {
        const errorText = await response.text();
        console.error(`❌ ChatGPT Uniqueness API failed: ${response.status} ${response.statusText}`, errorText);
        throw new Error(`ChatGPT Uniqueness API failed: ${response.status} ${response.statusText}`);
    }

    const result = await response.json();
    console.log('✅ ChatGPT Uniqueness Analysis result:', result);

    return {
        uniquenessScore: result.uniquenessScore || result.UniquenessScore || 0.5,
        issues: result.issues || result.Issues || [],
        vocabularyDiversity: result.vocabularyDiversity || result.VocabularyDiversity || 0.6,
        recommendations: result.recommendations || result.Recommendations || []
    };
}

/**
 * Call ChatGPT for links relevance analysis
 */
async function callChatGPTLinksAnalysis(primaryKeyword, content, internalLinks, externalLinks) {
    const apiUrl = buildAysaApiUrl('api/chatgpt/analyze-links-relevance');
    
    // Use clean content extraction function if content parameter is null/empty
    let cleanContent = content;
    if (!cleanContent || cleanContent.trim().length < 100) {
        cleanContent = getCleanContentForChatGPT();
    }
    
    // Limit content for API (leave room for links data)
    cleanContent = cleanContent.substring(0, 3000).trim();
    
    const requestData = {
        content: cleanContent,
        primaryKeyword: primaryKeyword,
        internalLinks: internalLinks.slice(0, 10), // Limit to first 10 links
        externalLinks: externalLinks.slice(0, 10)
    };
    
    console.log('🤖 Calling ChatGPT Links Analysis API...', { 
        keyword: primaryKeyword, 
        originalLength: content ? content.length : 0,
        cleanLength: cleanContent.length,
        preview: cleanContent.substring(0, 150) + '...',
        internalLinksCount: internalLinks.length,
        externalLinksCount: externalLinks.length,
        requestData: requestData
    });
    
    const response = await fetch(apiUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Origin': window.location.origin
        },
        body: JSON.stringify(requestData),
        mode: 'cors'
    });

    if (!response.ok) {
        const errorText = await response.text();
        console.error(`❌ ChatGPT Links API failed: ${response.status} ${response.statusText}`, errorText);
        throw new Error(`ChatGPT Links API failed: ${response.status} ${response.statusText}`);
    }

    const result = await response.json();
    console.log('✅ ChatGPT Links Analysis result:', result);

    return {
        internalRelevanceScore: result.internalRelevanceScore || result.InternalRelevanceScore || 0.5,
        externalRelevanceScore: result.externalRelevanceScore || result.ExternalRelevanceScore || 0.5,
        anchorQualityScore: result.anchorQualityScore || result.AnchorQualityScore || 0.5,
        suggestions: result.suggestions || result.Suggestions || []
    };
}

/**
 * Extract links from content for analysis
 */
function extractLinksFromContent(linkType) {
    const links = [];
    const currentDomain = window.location.hostname;
    
    // Get content from relevant sources only (not entire DOM)
    const contentSources = [];
    
    // 1. Try to get links from TinyMCE editors (product description, content)
    if (window.tinymce) {
        const editors = window.tinymce.editors;
        for (let editor of editors) {
            if (editor.getContent) {
                const editorContent = editor.getContent(); // HTML format to preserve links
                if (editorContent && editorContent.length > 50) {
                    contentSources.push(editorContent);
                }
            }
        }
    }
    
    // 2. Try to get from WordPress classic editor
    const classicEditor = document.getElementById('content');
    if (classicEditor && classicEditor.value) {
        contentSources.push(classicEditor.value);
    }
    
    // 3. Try to get WooCommerce product short description
    const shortDesc = document.getElementById('excerpt');
    if (shortDesc && shortDesc.value) {
        contentSources.push(shortDesc.value);
    }
    
    // 4. Try to get from category description
    const categoryDescription = document.getElementById('description');
    if (categoryDescription && categoryDescription.value) {
        contentSources.push(categoryDescription.value);
    }
    
    // 5. If no content sources found, try limited DOM selectors
    if (contentSources.length === 0) {
        const adminContentSelectors = [
            '#wp-content-editor-container',
            '#wp-excerpt-editor-container',
            '.woocommerce-product-data .inside'
        ];
        
        for (let selector of adminContentSelectors) {
            const element = document.querySelector(selector);
            if (element) {
                contentSources.push(element.innerHTML || element.textContent || '');
            }
        }
    }
    
    // Process each content source to extract links
    contentSources.forEach(source => {
        if (!source) return;
        
        // Create temporary element to parse HTML
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = source;
        
        const linkElements = tempDiv.querySelectorAll('a[href]');
        
        linkElements.forEach(link => {
            const href = link.getAttribute('href');
            const anchor = link.textContent.trim();
            
            if (!href || !anchor || anchor.length < 2) return;
            
            try {
                const url = new URL(href, window.location.origin);
                const isInternal = url.hostname === currentDomain || href.startsWith('/') || href.startsWith('#');
                
                if (linkType === 'internal' && isInternal) {
                    links.push({ url: href, anchor: anchor });
                } else if (linkType === 'external' && !isInternal) {
                    links.push({ url: href, anchor: anchor });
                }
            } catch (e) {
                // Try to handle relative URLs
                if (href.startsWith('/') || href.startsWith('#')) {
                    if (linkType === 'internal') {
                        links.push({ url: href, anchor: anchor });
                    }
                } else {
                    console.warn('Invalid URL found:', href);
                }
            }
        });
    });
    
    // Remove duplicates based on URL
    const uniqueLinks = links.filter((link, index, arr) => 
        arr.findIndex(l => l.url === link.url) === index
    );
    
    console.log(`📎 Found ${uniqueLinks.length} ${linkType} links from content sources:`, 
               uniqueLinks.map(l => `${l.anchor} -> ${l.url}`).slice(0, 3));
    return uniqueLinks;
}

/**
 * Get language value for API calls
 * Reusing existing function or fallback
 */
function getLanguageOptimizeValue() {
    // Try to get from existing AYSA functions
    if (typeof window.getLanguageOptimizeValue === 'function') {
        return window.getLanguageOptimizeValue();
    }
    
    // Fallback to HTML lang attribute or browser language
    const htmlLang = document.documentElement.lang;
    if (htmlLang) return htmlLang.substring(0, 2);
    
    const browserLang = navigator.language || navigator.userLanguage;
    return browserLang ? browserLang.substring(0, 2) : 'en';
}

// ================================
// DEBUG FUNCTIONS for ChatGPT Content Extraction
// ================================

/**
 * Debug function to test content extraction
 */
function debugChatGPTContentExtraction() {
    console.log('🔍 DEBUG: Testing ChatGPT Content Extraction...');
    
    const cleanContent = getCleanContentForChatGPT();
    console.log('📝 Clean Content Result:', {
        length: cleanContent.length,
        preview: cleanContent.substring(0, 300) + '...',
        fullContent: cleanContent
    });
    
    const internalLinks = extractLinksFromContent('internal');
    const externalLinks = extractLinksFromContent('external');
    
    console.log('🔗 Links Extraction Result:', {
        internal: internalLinks,
        external: externalLinks
    });
    
    return {
        content: cleanContent,
        internalLinks,
        externalLinks
    };
}

/**
 * Debug function to test ChatGPT API calls
 */
async function debugChatGPTAPICalls() {
    console.log('🔍 DEBUG: Testing ChatGPT API Calls...');
    
    const testKeyword = 'buchet floral';
    const testContent = `Alege să surprinzi pe cineva drag cu un buchet floral impresionant, disponibil într-un magazin online demonstrativ. Fiecare floare este atent selecționată pentru a crea un test care nu doar că impresionează prin frumusețea sa vizuală, dar și prin prospețimea și durabilitatea remarcabilă.

Ce Înseamnă Calitatea Buchetelor Florale Noastre?

În magazinul demonstrativ, calitatea este o prioritate. Fiecare aranjament este compus din flori crescute sub atentă supraveghere, asigurându-se că fiecare petală și fiecare frunză reflectă standardele noastre înalte. Alegerea unui buchet floral este o alegere pentru eleganță, prospețime și rafinament.

Personalizarea Buchetului Floral

Poți alege să personalizezi buchet floral în funcție de ocazie sau preferințele personale. Adaugă un mesaj personalizat sau alege dintr-o varietate de ambalaje speciale pentru a transforma un simplu dar într-o amintire de neuitat.`;
    
    console.log('📝 Test Content Length:', testContent.length);
    console.log('📝 Test Keyword:', testKeyword);
    console.log('🌐 API Base URL:', buildAysaApiUrl('api/chatgpt/'));
    
    try {
        console.log('\n🤖 Testing LSI Analysis...');
        const lsiResult = await callChatGPTLsiAnalysis(testKeyword, testContent);
        console.log('✅ LSI Result:', lsiResult);
        console.log('   - Score:', lsiResult.lsiScore);
        console.log('   - Found Terms:', lsiResult.foundLsiTerms.length);
        console.log('   - Suggestions:', lsiResult.missingSuggestions.length);
        
        console.log('\n🤖 Testing Uniqueness Analysis...');
        const uniquenessResult = await callChatGPTUniquenessAnalysis(testContent);
        console.log('✅ Uniqueness Result:', uniquenessResult);
        console.log('   - Uniqueness Score:', uniquenessResult.uniquenessScore);
        console.log('   - Vocabulary Diversity:', uniquenessResult.vocabularyDiversity);
        console.log('   - Issues:', uniquenessResult.issues.length);
        
        const testInternalLinks = [
            { url: '/buchete-nunta', anchor: 'buchete pentru nuntă' },
            { url: '/flori-proaspete', anchor: 'flori proaspete' }
        ];
        const testExternalLinks = [
            { url: 'https://example.com', anchor: 'informații suplimentare' }
        ];
        
        console.log('\n🤖 Testing Links Analysis...');
        const linksResult = await callChatGPTLinksAnalysis(testKeyword, testContent, testInternalLinks, testExternalLinks);
        console.log('✅ Links Result:', linksResult);
        console.log('   - Internal Score:', linksResult.internalRelevanceScore);
        console.log('   - External Score:', linksResult.externalRelevanceScore);
        console.log('   - Anchor Score:', linksResult.anchorQualityScore);
        
        console.log('\n🎯 SUMMARY:');
        console.log('   LSI Score:', (lsiResult.lsiScore * 100).toFixed(1) + '%');
        console.log('   Uniqueness Score:', (uniquenessResult.uniquenessScore * 100).toFixed(1) + '%');
        console.log('   Average Links Score:', ((linksResult.internalRelevanceScore + linksResult.externalRelevanceScore + linksResult.anchorQualityScore) / 3 * 100).toFixed(1) + '%');
        
        return {
            lsi: lsiResult,
            uniqueness: uniquenessResult,
            links: linksResult
        };
    } catch (error) {
        console.error('❌ ChatGPT API Test Failed:', error);
        console.error('Error details:', {
            name: error.name,
            message: error.message,
            stack: error.stack
        });
        return { error: error.message };
    }
}

// ================================
// NEW API FUNCTIONS for Advanced SEO Analysis
// ================================

/**
 * Call Performance Analysis API
 */
async function callPerformanceAnalysisAPI(url) {
    const apiUrl = buildAysaApiUrl('api/aysa-plugin/analyze-performance');
    
    const requestData = {
        url: url
    };
    
    console.log('🚀 Calling Performance Analysis API...', { url });
    
    try {
        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'Origin': window.location.origin
            },
            body: JSON.stringify(requestData),
            mode: 'cors'
        });

        if (!response.ok) {
            const errorText = await response.text();
            console.error(`❌ Performance API failed: ${response.status} ${response.statusText}`, errorText);
            throw new Error(`Performance API failed: ${response.status} ${response.statusText}`);
        }

        const result = await response.json();
        console.log('✅ Performance Analysis result:', result);
        return result;
    } catch (error) {
        console.error('❌ Performance Analysis failed:', error);
        throw error;
    }
}

/**
 * Call Mobile-Friendly Analysis API
 */
async function callMobileFriendlyAnalysisAPI(url) {
    const apiUrl = buildAysaApiUrl('api/aysa-plugin/analyze-mobile-friendly');
    
    const requestData = {
        url: url
    };
    
    console.log('📱 Calling Mobile-Friendly Analysis API...', { url });
    
    try {
        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'Origin': window.location.origin
            },
            body: JSON.stringify(requestData),
            mode: 'cors'
        });

        if (!response.ok) {
            const errorText = await response.text();
            console.error(`❌ Mobile-Friendly API failed: ${response.status} ${response.statusText}`, errorText);
            throw new Error(`Mobile-Friendly API failed: ${response.status} ${response.statusText}`);
        }

        const result = await response.json();
        console.log('✅ Mobile-Friendly Analysis result:', result);
        return result;
    } catch (error) {
        console.error('❌ Mobile-Friendly Analysis failed:', error);
        throw error;
    }
}

/**
 * Call Backlinks Analysis API
 */
async function callBacklinksAnalysisAPI(url) {
    const apiUrl = buildAysaApiUrl('api/aysa-plugin/analyze-backlinks');
    
    const requestData = {
        url: url
    };
    
    console.log('🔗 Calling Backlinks Analysis API...', { url });
    
    try {
        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'Origin': window.location.origin
            },
            body: JSON.stringify(requestData),
            mode: 'cors'
        });

        if (!response.ok) {
            const errorText = await response.text();
            console.error(`❌ Backlinks API failed: ${response.status} ${response.statusText}`, errorText);
            throw new Error(`Backlinks API failed: ${response.status} ${response.statusText}`);
        }

        const result = await response.json();
        console.log('✅ Backlinks Analysis result:', result);
        return result;
    } catch (error) {
        console.error('❌ Backlinks Analysis failed:', error);
        throw error;
    }
}

/**
 * Call Technical SEO Analysis API
 */
async function callTechnicalSeoAnalysisAPI(url) {
    const apiUrl = buildAysaApiUrl('api/seo/technical');
    
    const requestData = {
        url: url
    };
    
    console.log('🔧 Calling Technical SEO Analysis API...', { url });
    
    try {
        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'Origin': window.location.origin
            },
            body: JSON.stringify(requestData),
            mode: 'cors'
        });

        if (!response.ok) {
            const errorText = await response.text();
            console.error(`❌ Technical SEO API failed: ${response.status} ${response.statusText}`, errorText);
            throw new Error(`Technical SEO API failed: ${response.status} ${response.statusText}`);
        }

        const result = await response.json();
        console.log('✅ Technical SEO Analysis result:', result);
        return result;
    } catch (error) {
        console.error('❌ Technical SEO Analysis failed:', error);
        throw error;
    }
}

/**
 * Call Links Functionality Analysis API
 */
async function callLinksFunctionalityAnalysisAPI(links) {
    const apiUrl = buildAysaApiUrl('api/aysa-plugin/analyze-links-functionality');
    
    const requestData = {
        links: links
    };
    
    console.log('🔍 Calling Links Functionality Analysis API...', { linksCount: links.length });
    
    try {
        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'Origin': window.location.origin
            },
            body: JSON.stringify(requestData),
            mode: 'cors'
        });

        if (!response.ok) {
            const errorText = await response.text();
            console.error(`❌ Links Functionality API failed: ${response.status} ${response.statusText}`, errorText);
            throw new Error(`Links Functionality API failed: ${response.status} ${response.statusText}`);
        }

        const result = await response.json();
        console.log('✅ Links Functionality Analysis result:', result);
        return result;
    } catch (error) {
        console.error('❌ Links Functionality Analysis failed:', error);
        throw error;
    }
}

// Make debug functions available globally
window.debugChatGPTContentExtraction = debugChatGPTContentExtraction;
window.debugChatGPTAPICalls = debugChatGPTAPICalls;

// ================================
// Debug and test functions removed for production
// ================================
 
 
 
