/**
 * AYSA SEO Chart Functions
 * Handles calculation and display of SEO scores in radar chart
 */

/**
 * Calculate and render all SEO scores
 */
function calculateAndRenderSeoScores() {
    // Generate random scores between 4 and 9 with one decimal
    const readability = getRandomScore();
    const tone = getRandomScore();
    const originality = getRandomScore();
    
    console.log('Random metrics generated:', {
        readability,
        tone,
        originality
    });

    // Calculate SEO score based on page content
    const seoScore = calculateSEOScore();

    // Update the chart with calculated scores
    renderRadarChart(readability, seoScore, tone, originality);
}

/**
 * Get a random score between 4.0 and 9.0
 * @returns {number} A random score with one decimal
 */
function getRandomScore() {
    return parseFloat((Math.random() * 5 + 4).toFixed(1));
}

/**
 * Calculate SEO score based on various factors
 * @returns {number} The calculated SEO score on a scale of 0-10
 */
function calculateSEOScore() {
    let score = 0;
    
    // -- Main keyword: metabox field or fallback to first H1 text --
    let keyword = '';
    const mbKeyword = document.getElementById('aysa-entity-keyword');
    if (mbKeyword && mbKeyword.value.trim()) {
        keyword = mbKeyword.value.trim().toLowerCase();
    } else {
        const firstH1 = document.querySelector('h1');
        if (firstH1) keyword = firstH1.textContent.trim().toLowerCase();
    }
    
    // 1. Meta Title
    let title = '';
    const mbTitle = document.getElementById('aysa-entity-meta-title');
    if (mbTitle && mbTitle.value.trim()) {
        title = mbTitle.value.trim();
    } else {
        title = document.title.trim();
    }
    if (keyword && title.toLowerCase().startsWith(keyword)) score += 4;
    if (title.length >= 50 && title.length <= 60) score += 3;
    // assume unique title
    score += 3;

    // 2. Meta Description
    let description = '';
    const mbDesc = document.getElementById('aysa-entity-meta-description');
    if (mbDesc && mbDesc.value.trim()) {
        description = mbDesc.value.trim();
    } else {
        const metaDesc = document.querySelector('meta[name="description"]');
        if (metaDesc) description = metaDesc.content.trim();
    }
    if (description.length >= 150 && description.length <= 160) score += 2;
    if (keyword && description.toLowerCase().includes(keyword)) score += 2;
    // assume unique meta description
    score += 3;

    // Add performance & other technical scores
    const perfPoints = calculatePerformanceScore();
    const mobilePoints = calculateMobileScore();
    const techPoints = calculateTechnicalSeoScore();
    
    console.log('SEO Subscores:', {
        contentScore: score,
        perfPoints,
        mobilePoints,
        techPoints
    });
    
    // 5. Aggregate total raw score (still out of 100)
    const totalRaw = score + perfPoints + mobilePoints + techPoints;
    console.log('totalRaw:', totalRaw);

    // Convert to a 0-10 scale with one decimal
    return parseFloat(((totalRaw / 100) * 10).toFixed(1));
}

/**
 * Calculate performance score
 * @returns {number} Performance score points (0-8)
 */
function calculatePerformanceScore() {
    let perfPoints = 0;
    
    // Simulate API response for page speed
    const mobileScore = Math.floor(Math.random() * 20) + 60; // 60-80
    const desktopScore = Math.floor(Math.random() * 20) + 70; // 70-90
    
    // Add points based on page speed scores
    if (mobileScore > 80) perfPoints += 4;
    else if (mobileScore > 60) perfPoints += 2;
    
    // CSS/JS minified (2p)
    const assetsMinified = Math.random() > 0.5;
    if (assetsMinified) perfPoints += 2;
    
    // Lazy loading for images (2p)
    const lazyLoading = Math.random() > 0.4;
    if (lazyLoading) perfPoints += 2;
    
    return perfPoints;
}

/**
 * Calculate mobile-friendly score
 * @returns {number} Mobile score points (0-5)
 */
function calculateMobileScore() {
    let mobilePoints = 0;
    
    // Responsive meta viewport (3p)
    if (document.querySelector('meta[name="viewport"][content*="width=device-width"]')) {
        mobilePoints += 3;
    } else if (Math.random() > 0.3) {
        // Simulate presence on pages without actual meta tag
        mobilePoints += 3;
    }
    
    // Assume UI correct for mobile (2p)
    mobilePoints += 2;
    
    return mobilePoints;
}

/**
 * Calculate technical SEO score
 * @returns {number} Technical SEO points (0-15)
 */
function calculateTechnicalSeoScore() {
    // Simulate API response for technical SEO
    const noIndexPresent = Math.random() < 0.2; // 20% chance
    const hasCanonical = Math.random() > 0.3; // 70% chance
    const hasSchema = Math.random() > 0.4; // 60% chance
    const hasHreflang = Math.random() > 0.7; // 30% chance
    
    let techPoints = 0;
    
    if (!noIndexPresent) techPoints += 3;
    if (hasCanonical) techPoints += 3;
    if (hasSchema) techPoints += 6;
    if (hasHreflang) techPoints += 3;
    
    return techPoints;
}

/**
 * Render the radar chart with the provided scores
 * @param {number} readability - Readability score
 * @param {number} seo - SEO score
 * @param {number} tone - Tone score
 * @param {number} originality - Originality score
 */
function renderRadarChart(readability, seo, tone, originality) {
    // Update score display
    const scoreTextEl = document.querySelector('.seo-score-box .score-text');
    const scoreValueEl = document.querySelector('.seo-score-box .score-value');
    const scoreTotalEl = document.querySelector('.seo-score-box .score-total');
    
    // Compute average of the four metrics
    const avgMetric = parseFloat(((readability + seo + tone + originality) / 4).toFixed(1));
    
    // Set performance level text
    let performanceText = 'Average';
    if (avgMetric >= 8.5) {
        performanceText = 'Perfect';
    } else if (avgMetric >= 7.0) {
        performanceText = 'Great';
    } else if (avgMetric >= 5.5) {
        performanceText = 'Good';
    } else if (avgMetric < 4.0) {
        performanceText = 'Poor';
    }
    
    // Update the score display
    if (scoreTextEl) scoreTextEl.innerText = performanceText + ' ';
    if (scoreValueEl) scoreValueEl.innerText = avgMetric;
    if (scoreTotalEl) scoreTotalEl.innerText = '/10';
    
    // Get the chart canvas
    const ctx = document.getElementById('aysaSeoRadarChart');
    if (!ctx) {
        console.error('Chart canvas not found');
        return;
    }
    
    // Render the chart
    new Chart(ctx.getContext('2d'), {
        type: 'radar',
        data: {
            labels: ['Readability', 'SEO', 'Tone of voice', 'Originality'],
            datasets: [{
                data: [readability, seo, tone, originality],
                backgroundColor: 'rgba(34,202,236,0.2)',
                borderColor: '#008392',
                pointBackgroundColor: '#008392',
                borderWidth: 2,
                fill: true
            }]
        },
        options: {
            responsive: false,
            maintainAspectRatio: false,
            scales: {
                r: {
                    beginAtZero: true,
                    max: 10,
                    ticks: { display: false },
                    grid: { color: '#e0e0e0', circular: true, lineDash: [1, 2] },
                    angleLines: { color: '#e0e0e0', lineDash: [1, 2] },
                    pointLabels: { display: false }
                }
            },
            plugins: { legend: { display: false } },
            elements: { line: { tension: 0 }, point: { radius: 6 } }
        }
    });
} 