/**
 * SEO Health Check Widget
 * Real-time SEO Health monitoring with actionable recommendations
 */

class SEOHealthCheckWidget {
    constructor() {
        this.checks = [];
        this.score = 0;
    }

    /**
     * Render health check widget
     */
    render(containerId) {
        const container = document.getElementById(containerId);
        if (!container) return;

        this.container = container;
        this.updateHealthStatus();
    }

    /**
     * Update health status
     */
    updateHealthStatus() {
        const metrics = this.getHealthMetrics();
        
        let html = `
            <div class="health-check-widget" style="
                background: #fff;
                border-radius: 8px;
                padding: 20px;
                box-shadow: 0 2px 10px rgba(0,0,0,0.08);
                margin: 20px 0;
            ">
                <div class="health-header" style="
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    margin-bottom: 20px;
                    border-bottom: 2px solid #e9ecef;
                    padding-bottom: 15px;
                ">
                    <h3 style="margin: 0; color: #2c3e50;">SEO Health Check</h3>
                    <div class="health-score-badge" style="
                        width: 80px;
                        height: 80px;
                        border-radius: 50%;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        font-size: 28px;
                        font-weight: 700;
                        color: #fff;
                        background: ${this.getScoreColor(metrics.overall_score)};
                    ">
                        ${Math.round(metrics.overall_score)}
                    </div>
                </div>
                
                <div class="health-metrics" style="margin-bottom: 20px;">
                    ${this.renderMetrics(metrics)}
                </div>
                
                <div class="health-recommendations" style="
                    background: #f8f9fa;
                    border-radius: 6px;
                    padding: 15px;
                    margin-bottom: 15px;
                ">
                    <h4 style="margin: 0 0 15px 0; color: #2c3e50;">To-Do Items</h4>
                    ${this.renderRecommendations(metrics)}
                </div>
                
                <button class="btn btn-primary" onclick="location.href='?action=meta-tags'" style="
                    width: 100%;
                    padding: 12px;
                    background: #df7caa;
                    color: #fff;
                    border: none;
                    border-radius: 6px;
                    cursor: pointer;
                    font-weight: 600;
                ">
                    Improve SEO
                </button>
            </div>
        `;

        this.container.innerHTML = html;
    }

    /**
     * Get health metrics
     */
    getHealthMetrics() {
        return {
            overall_score: 75,
            meta_title: { score: 90, status: 'good' },
            meta_description: { score: 75, status: 'fair' },
            h1_tag: { score: 100, status: 'good' },
            keywords: { score: 60, status: 'needs_work' },
            readability: { score: 80, status: 'good' },
            images_alt: { score: 50, status: 'needs_work' },
            internal_links: { score: 85, status: 'good' },
            schema_markup: { score: 70, status: 'fair' }
        };
    }

    /**
     * Render metrics
     */
    renderMetrics(metrics) {
        const metricEntries = Object.entries(metrics).filter(([key]) => key !== 'overall_score');
        
        return metricEntries.map(([key, data]) => {
            const label = this.formatLabel(key);
            const statusColor = this.getStatusColor(data.status);
            const statusIcon = this.getStatusIcon(data.status);
            
            return `
                <div style="
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    padding: 10px 0;
                    border-bottom: 1px solid #e9ecef;
                ">
                    <span style="color: #555;">${label}</span>
                    <span style="
                        display: flex;
                        align-items: center;
                        gap: 10px;
                    ">
                        <span style="
                            background: ${statusColor};
                            color: white;
                            padding: 4px 10px;
                            border-radius: 4px;
                            font-size: 12px;
                            font-weight: 600;
                        ">${data.score}%</span>
                        <span>${statusIcon}</span>
                    </span>
                </div>
            `;
        }).join('');
    }

    /**
     * Render recommendations
     */
    renderRecommendations(metrics) {
        const recommendations = [];

        if (metrics.meta_title.score < 80) {
            recommendations.push({
                priority: 'high',
                text: 'Optimize meta title (30-60 characters)'
            });
        }

        if (metrics.meta_description.score < 80) {
            recommendations.push({
                priority: 'high',
                text: 'Improve meta description (120-160 characters)'
            });
        }

        if (metrics.h1_tag.score < 100) {
            recommendations.push({
                priority: 'critical',
                text: 'Ensure exactly one H1 tag per page'
            });
        }

        if (metrics.keywords.score < 70) {
            recommendations.push({
                priority: 'high',
                text: 'Optimize focus keyword usage'
            });
        }

        if (metrics.readability.score < 70) {
            recommendations.push({
                priority: 'medium',
                text: 'Improve content readability'
            });
        }

        if (metrics.images_alt.score < 80) {
            recommendations.push({
                priority: 'medium',
                text: 'Add alt text to all images'
            });
        }

        if (metrics.schema_markup.score < 80) {
            recommendations.push({
                priority: 'low',
                text: 'Add schema markup to pages'
            });
        }

        return recommendations.length > 0 
            ? recommendations.map(rec => `
                <div style="
                    padding: 10px;
                    margin-bottom: 10px;
                    background: white;
                    border-left: 4px solid ${this.getPriorityColor(rec.priority)};
                    border-radius: 4px;
                    font-size: 14px;
                ">
                    <strong>[${rec.priority.toUpperCase()}]</strong> ${rec.text}
                </div>
            `).join('')
            : '<div style="color: #28a745; text-align: center;">All checks passed! 🎉</div>';
    }

    /**
     * Format label
     */
    formatLabel(key) {
        const labels = {
            'meta_title': 'Meta Title',
            'meta_description': 'Meta Description',
            'h1_tag': 'H1 Tag',
            'keywords': 'Keywords',
            'readability': 'Readability',
            'images_alt': 'Image Alt Text',
            'internal_links': 'Internal Links',
            'schema_markup': 'Schema Markup'
        };
        return labels[key] || key;
    }

    /**
     * Get status icon
     */
    getStatusIcon(status) {
        const icons = {
            'good': '🟢',
            'fair': '🟡',
            'needs_work': '🔴'
        };
        return icons[status] || '⚪';
    }

    /**
     * Get status color
     */
    getStatusColor(status) {
        const colors = {
            'good': '#28a745',
            'fair': '#ffc107',
            'needs_work': '#dc3545'
        };
        return colors[status] || '#6c757d';
    }

    /**
     * Get score color
     */
    getScoreColor(score) {
        if (score >= 80) return '#28a745';
        if (score >= 60) return '#ffc107';
        return '#dc3545';
    }

    /**
     * Get priority color
     */
    getPriorityColor(priority) {
        const colors = {
            'critical': '#dc3545',
            'high': '#fd7e14',
            'medium': '#ffc107',
            'low': '#17a2b8'
        };
        return colors[priority] || '#6c757d';
    }
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', () => {
    const widget = new SEOHealthCheckWidget();
    const container = document.getElementById('seo-health-widget');
    
    if (container) {
        widget.render('seo-health-widget');
    }
});
