/**
 * Yoast-Style SEO UI Component
 * Real-time SEO analysis and scoring interface
 */

if (typeof YoastSEOUI === 'undefined') {
class YoastSEOUI {
    constructor(containerId, options = {}) {
        this.container = document.getElementById(containerId);
        this.options = {
            autoAnalyze: true,
            debounceDelay: 500,
            ...options
        };
        this.analysisCache = null;
        this.debounceTimer = null;
    }
    
    /**
     * Initialize the Yoast SEO UI
     */
    init() {
        if (!this.container) {
            console.error('YoastSEOUI: Container not found');
            return;
        }
        
        this.render();
        this.attachEventListeners();
    }
    
    /**
     * Render the Yoast-style SEO panel
     */
    render() {
        this.container.innerHTML = `
            <div class="yoast-seo-panel">
                <div class="yoast-seo-header">
                    <div class="yoast-seo-score" id="yoastScoreCircle">
                        <div class="score-circle">
                            <svg width="60" height="60" viewBox="0 0 60 60">
                                <circle cx="30" cy="30" r="28" fill="none" stroke="#ddd" stroke-width="4"/>
                                <circle cx="30" cy="30" r="28" fill="none" stroke="#f0ad4e" stroke-width="4" 
                                        stroke-dasharray="${2 * Math.PI * 28}" 
                                        stroke-dashoffset="${2 * Math.PI * 28}" 
                                        id="scoreCircle" transform="rotate(-90 30 30)"/>
                                <text x="30" y="35" text-anchor="middle" font-size="16" font-weight="bold" fill="#333" id="scoreText">0</text>
                            </svg>
                        </div>
                        <div class="score-label">
                            <span id="scoreStatus" class="status-badge status-bad">Bad</span>
                            <span class="score-type">SEO Score</span>
                        </div>
                    </div>
                    <div class="yoast-readability-score" id="yoastReadabilityScore">
                        <div class="readability-circle">
                            <svg width="50" height="50" viewBox="0 0 50 50">
                                <circle cx="25" cy="25" r="23" fill="none" stroke="#ddd" stroke-width="3"/>
                                <circle cx="25" cy="25" r="23" fill="none" stroke="#f0ad4e" stroke-width="3" 
                                        stroke-dasharray="${2 * Math.PI * 23}" 
                                        stroke-dashoffset="${2 * Math.PI * 23}" 
                                        id="readabilityCircle" transform="rotate(-90 25 25)"/>
                                <text x="25" y="30" text-anchor="middle" font-size="12" font-weight="bold" fill="#333" id="readabilityText">0</text>
                            </svg>
                        </div>
                        <div class="readability-label">
                            <span class="score-type">Readability</span>
                        </div>
                    </div>
                </div>
                
                <div class="yoast-seo-content">
                    <div class="yoast-section" id="focusKeywordSection">
                        <div class="yoast-section-header">
                            <span class="yoast-icon" id="focusKeywordIcon">⚠️</span>
                            <span class="yoast-title">Focus keyword</span>
                        </div>
                        <div class="yoast-section-content" id="focusKeywordContent">
                            <p class="yoast-message">Enter a focus keyword to calculate the SEO score</p>
                        </div>
                    </div>
                    
                    <div class="yoast-section" id="titleSection">
                        <div class="yoast-section-header">
                            <span class="yoast-icon" id="titleIcon">⚠️</span>
                            <span class="yoast-title">SEO title</span>
                        </div>
                        <div class="yoast-section-content" id="titleContent">
                            <p class="yoast-message">Enter an SEO title to see the analysis</p>
                        </div>
                    </div>
                    
                    <div class="yoast-section" id="metaDescriptionSection">
                        <div class="yoast-section-header">
                            <span class="yoast-icon" id="metaDescriptionIcon">⚠️</span>
                            <span class="yoast-title">Meta description</span>
                        </div>
                        <div class="yoast-section-content" id="metaDescriptionContent">
                            <p class="yoast-message">Enter a meta description to see the analysis</p>
                        </div>
                    </div>
                    
                    <div class="yoast-section" id="contentSection">
                        <div class="yoast-section-header">
                            <span class="yoast-icon" id="contentIcon">⚠️</span>
                            <span class="yoast-title">Content analysis</span>
                        </div>
                        <div class="yoast-section-content" id="contentContent">
                            <p class="yoast-message">Enter content to see the analysis</p>
                        </div>
                    </div>
                    
                    <div class="yoast-section" id="urlSection">
                        <div class="yoast-section-header">
                            <span class="yoast-icon" id="urlIcon">⚠️</span>
                            <span class="yoast-title">URL</span>
                        </div>
                        <div class="yoast-section-content" id="urlContent">
                            <p class="yoast-message">Enter a URL to see the analysis</p>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }
    
    /**
     * Attach event listeners to form fields
     */
    attachEventListeners() {
        // Find form fields and attach listeners
        const titleField = document.querySelector('input[name="title"], input[name="seo_title"]');
        const metaField = document.querySelector('textarea[name="meta_description"], textarea[name="seo_meta_description"]');
        const keywordField = document.querySelector('input[name="focus_keyword"], input[name="seo_focus_keyword"]');
        const contentField = document.querySelector('textarea[name="content"], textarea[name="description"], textarea[name="blog_content"]');
        const urlField = document.querySelector('input[name="slug"], input[name="url"]');
        
        if (titleField) {
            titleField.addEventListener('input', () => this.debounceAnalyze());
        }
        if (metaField) {
            metaField.addEventListener('input', () => this.debounceAnalyze());
        }
        if (keywordField) {
            keywordField.addEventListener('input', () => this.debounceAnalyze());
        }
        if (contentField) {
            contentField.addEventListener('input', () => this.debounceAnalyze());
        }
        if (urlField) {
            urlField.addEventListener('input', () => this.debounceAnalyze());
        }
    }
    
    /**
     * Debounce analysis to avoid too many requests
     */
    debounceAnalyze() {
        clearTimeout(this.debounceTimer);
        this.debounceTimer = setTimeout(() => {
            this.analyze();
        }, this.options.debounceDelay);
    }
    
    /**
     * Perform SEO analysis
     */
    async analyze() {
        const data = this.getFormData();
        
        if (!data.content && !data.title) {
            return; // Don't analyze if no content
        }
        
        try {
            const response = await fetch('admin_seo_manager.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'analyze_yoast_seo',
                    ...data
                })
            });
            
            const result = await response.json();
            
            if (result.success && result.analysis) {
                this.analysisCache = result.analysis;
                this.updateUI(result.analysis);
            }
        } catch (error) {
            console.error('Yoast SEO Analysis Error:', error);
        }
    }
    
    /**
     * Get form data
     */
    getFormData() {
        return {
            title: this.getFieldValue('title', 'seo_title'),
            meta_description: this.getFieldValue('meta_description', 'seo_meta_description'),
            focus_keyword: this.getFieldValue('focus_keyword', 'seo_focus_keyword'),
            content: this.getFieldValue('content', 'description', 'blog_content'),
            slug: this.getFieldValue('slug', 'url'),
            url: this.getFieldValue('url', 'slug')
        };
    }
    
    /**
     * Get field value by trying multiple field names
     */
    getFieldValue(...fieldNames) {
        for (const name of fieldNames) {
            const field = document.querySelector(`input[name="${name}"], textarea[name="${name}"]`);
            if (field) {
                return field.value || '';
            }
        }
        return '';
    }
    
    /**
     * Update UI with analysis results
     */
    updateUI(analysis) {
        // Update SEO Score
        this.updateScore(analysis.seo_score, 'yoastScoreCircle', 'scoreText', 'scoreStatus', 'scoreCircle');
        
        // Update Readability Score
        this.updateReadability(analysis.readability_score);
        
        // Update Focus Keyword Section
        this.updateFocusKeyword(analysis.focus_keyword_analysis);
        
        // Update Title Section
        this.updateTitle(analysis.title_analysis);
        
        // Update Meta Description Section
        this.updateMetaDescription(analysis.meta_description_analysis);
        
        // Update Content Section
        this.updateContent(analysis.content_analysis);
        
        // Update URL Section
        this.updateURL(analysis.url_analysis);
    }
    
    /**
     * Update score circle
     */
    updateScore(score, containerId, textId, statusId, circleId) {
        const container = document.getElementById(containerId);
        const scoreText = document.getElementById(textId);
        const statusBadge = document.getElementById(statusId);
        const circle = document.getElementById(circleId);
        
        if (!container || !scoreText || !statusBadge || !circle) return;
        
        scoreText.textContent = score;
        
        // Determine color based on score
        let color, status, statusText;
        if (score >= 80) {
            color = '#7ad03a'; // Green
            status = 'good';
            statusText = 'Good';
        } else if (score >= 50) {
            color = '#f0ad4e'; // Orange
            status = 'warning';
            statusText = 'OK';
        } else {
            color = '#dc3232'; // Red
            status = 'bad';
            statusText = 'Bad';
        }
        
        // Update circle
        const radius = 28;
        const circumference = 2 * Math.PI * radius;
        const offset = circumference - (score / 100) * circumference;
        circle.setAttribute('stroke-dashoffset', offset);
        circle.setAttribute('stroke', color);
        
        // Update status badge
        statusBadge.textContent = statusText;
        statusBadge.className = `status-badge status-${status}`;
    }
    
    /**
     * Update readability score
     */
    updateReadability(score) {
        const circle = document.getElementById('readabilityCircle');
        const text = document.getElementById('readabilityText');
        
        if (!circle || !text) return;
        
        text.textContent = score;
        
        const radius = 23;
        const circumference = 2 * Math.PI * radius;
        const offset = circumference - (score / 100) * circumference;
        circle.setAttribute('stroke-dashoffset', offset);
        
        // Color based on score
        let color;
        if (score >= 60) {
            color = '#7ad03a';
        } else if (score >= 40) {
            color = '#f0ad4e';
        } else {
            color = '#dc3232';
        }
        circle.setAttribute('stroke', color);
    }
    
    /**
     * Update focus keyword section
     */
    updateFocusKeyword(analysis) {
        if (!analysis) return;
        
        const section = document.getElementById('focusKeywordSection');
        const icon = document.getElementById('focusKeywordIcon');
        const content = document.getElementById('focusKeywordContent');
        
        if (!section || !icon || !content) return;
        
        const status = analysis.status || 'bad';
        icon.textContent = this.getStatusIcon(status);
        section.className = `yoast-section status-${status}`;
        
        let html = '';
        if (analysis.good && analysis.good.length > 0) {
            html += '<ul class="yoast-good">';
            analysis.good.forEach(item => {
                html += `<li>${this.escapeHtml(item)}</li>`;
            });
            html += '</ul>';
        }
        
        if (analysis.issues && analysis.issues.length > 0) {
            html += '<ul class="yoast-issues">';
            analysis.issues.forEach(item => {
                html += `<li>${this.escapeHtml(item)}</li>`;
            });
            html += '</ul>';
        }
        
        if (html) {
            content.innerHTML = html;
        }
    }
    
    /**
     * Update title section
     */
    updateTitle(analysis) {
        if (!analysis) return;
        
        const section = document.getElementById('titleSection');
        const icon = document.getElementById('titleIcon');
        const content = document.getElementById('titleContent');
        
        if (!section || !icon || !content) return;
        
        const status = analysis.status || 'bad';
        icon.textContent = this.getStatusIcon(status);
        section.className = `yoast-section status-${status}`;
        
        let html = '';
        if (analysis.good && analysis.good.length > 0) {
            html += '<ul class="yoast-good">';
            analysis.good.forEach(item => {
                html += `<li>${this.escapeHtml(item)}</li>`;
            });
            html += '</ul>';
        }
        
        if (analysis.issues && analysis.issues.length > 0) {
            html += '<ul class="yoast-issues">';
            analysis.issues.forEach(item => {
                html += `<li>${this.escapeHtml(item)}</li>`;
            });
            html += '</ul>';
        }
        
        if (html) {
            content.innerHTML = html;
        }
    }
    
    /**
     * Update meta description section
     */
    updateMetaDescription(analysis) {
        if (!analysis) return;
        
        const section = document.getElementById('metaDescriptionSection');
        const icon = document.getElementById('metaDescriptionIcon');
        const content = document.getElementById('metaDescriptionContent');
        
        if (!section || !icon || !content) return;
        
        const status = analysis.status || 'bad';
        icon.textContent = this.getStatusIcon(status);
        section.className = `yoast-section status-${status}`;
        
        let html = '';
        if (analysis.good && analysis.good.length > 0) {
            html += '<ul class="yoast-good">';
            analysis.good.forEach(item => {
                html += `<li>${this.escapeHtml(item)}</li>`;
            });
            html += '</ul>';
        }
        
        if (analysis.issues && analysis.issues.length > 0) {
            html += '<ul class="yoast-issues">';
            analysis.issues.forEach(item => {
                html += `<li>${this.escapeHtml(item)}</li>`;
            });
            html += '</ul>';
        }
        
        if (html) {
            content.innerHTML = html;
        }
    }
    
    /**
     * Update content section
     */
    updateContent(analysis) {
        if (!analysis) return;
        
        const section = document.getElementById('contentSection');
        const icon = document.getElementById('contentIcon');
        const content = document.getElementById('contentContent');
        
        if (!section || !icon || !content) return;
        
        let html = '';
        if (analysis.good && analysis.good.length > 0) {
            html += '<ul class="yoast-good">';
            analysis.good.forEach(item => {
                html += `<li>${this.escapeHtml(item)}</li>`;
            });
            html += '</ul>';
        }
        
        if (analysis.issues && analysis.issues.length > 0) {
            html += '<ul class="yoast-issues">';
            analysis.issues.forEach(item => {
                html += `<li>${this.escapeHtml(item)}</li>`;
            });
            html += '</ul>';
        }
        
        if (html) {
            content.innerHTML = html;
            icon.textContent = '✅';
            section.className = 'yoast-section status-good';
        }
    }
    
    /**
     * Update URL section
     */
    updateURL(analysis) {
        if (!analysis) return;
        
        const section = document.getElementById('urlSection');
        const icon = document.getElementById('urlIcon');
        const content = document.getElementById('urlContent');
        
        if (!section || !icon || !content) return;
        
        const status = analysis.status || 'bad';
        icon.textContent = this.getStatusIcon(status);
        section.className = `yoast-section status-${status}`;
        
        let html = '';
        if (analysis.good && analysis.good.length > 0) {
            html += '<ul class="yoast-good">';
            analysis.good.forEach(item => {
                html += `<li>${this.escapeHtml(item)}</li>`;
            });
            html += '</ul>';
        }
        
        if (analysis.issues && analysis.issues.length > 0) {
            html += '<ul class="yoast-issues">';
            analysis.issues.forEach(item => {
                html += `<li>${this.escapeHtml(item)}</li>`;
            });
            html += '</ul>';
        }
        
        if (html) {
            content.innerHTML = html;
        }
    }
    
    /**
     * Get status icon
     */
    getStatusIcon(status) {
        switch(status) {
            case 'good':
                return '✅';
            case 'warning':
                return '⚠️';
            case 'bad':
                return '❌';
            default:
                return '⚠️';
        }
    }
    
    /**
     * Escape HTML
     */
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}
} // End of class wrapper check

// Auto-initialize if container exists
document.addEventListener('DOMContentLoaded', function() {
    const yoastContainer = document.getElementById('yoast-seo-container');
    if (yoastContainer && typeof YoastSEOUI !== 'undefined') {
        if (!window.yoastSEO) {
            window.yoastSEO = new YoastSEOUI('yoast-seo-container');
            window.yoastSEO.init();
        }
    }
});
