/**
 * Google Snippet Preview
 * Real-time preview of how content appears in Google search results
 */

class GoogleSnippetPreview {
    constructor() {
        this.title = '';
        this.description = '';
        this.url = '';
        this.updatePreview();
    }

    /**
     * Initialize preview listeners
     */
    init() {
        const titleInput = document.getElementById('title');
        const descInput = document.getElementById('meta_description');
        const slugInput = document.getElementById('slug');

        if (titleInput) {
            titleInput.addEventListener('input', () => this.updatePreview());
        }

        if (descInput) {
            descInput.addEventListener('input', () => this.updatePreview());
        }

        if (slugInput) {
            slugInput.addEventListener('input', () => this.updatePreview());
        }

        // Also update on page load
        this.updatePreview();
    }

    /**
     * Update the preview
     */
    updatePreview() {
        this.title = document.getElementById('title')?.value || '';
        this.description = document.getElementById('meta_description')?.value || '';
        const slug = document.getElementById('slug')?.value || 'your-page';

        // Get base URL
        const host = window.location.hostname;
        const protocol = window.location.protocol;
        this.url = `${protocol}//${host}/${slug}`;

        this.render();
    }

    /**
     * Render the preview
     */
    render() {
        const container = document.getElementById('google-snippet-preview');
        if (!container) return;

        // Truncate title if needed (Google shows ~60 chars on desktop)
        const displayTitle = this.title.length > 60 
            ? this.title.substring(0, 57) + '...' 
            : this.title;

        // Truncate description if needed (Google shows ~160 chars)
        const displayDesc = this.description.length > 160 
            ? this.description.substring(0, 157) + '...' 
            : this.description;

        const titleStatus = this.getTitleStatus();
        const descStatus = this.getDescriptionStatus();

        let html = `
            <div class="snippet-preview" style="
                background: #fff;
                padding: 20px;
                border-radius: 8px;
                border: 1px solid #ddd;
                margin: 20px 0;
                font-family: Arial, sans-serif;
                max-width: 600px;
            ">
                <h4 style="margin: 0 0 15px 0; color: #555; font-size: 13px; text-transform: uppercase;">Google Search Preview</h4>
                
                <!-- Google Snippet -->
                <div class="snippet" style="
                    background: #f8f9fa;
                    padding: 15px;
                    border-radius: 6px;
                    font-size: 14px;
                ">
                    <!-- URL -->
                    <div class="snippet-url" style="
                        color: #006621;
                        font-size: 13px;
                        margin-bottom: 5px;
                    ">
                        ${this.escapeHtml(this.url)}
                    </div>
                    
                    <!-- Title -->
                    <div class="snippet-title" style="
                        color: #1a0dff;
                        font-size: 18px;
                        font-weight: 500;
                        margin-bottom: 5px;
                        cursor: pointer;
                        text-decoration: none;
                        line-height: 1.3;
                    ">
                        ${this.escapeHtml(displayTitle)}
                    </div>
                    
                    <!-- Description -->
                    <div class="snippet-description" style="
                        color: #545454;
                        font-size: 14px;
                        line-height: 1.5;
                    ">
                        ${this.escapeHtml(displayDesc) || '<span style="color: #999; font-style: italic;">Add a meta description</span>'}
                    </div>
                </div>
                
                <!-- Analysis -->
                <div class="snippet-analysis" style="margin-top: 20px;">
                    ${this.renderAnalysis(titleStatus, descStatus)}
                </div>
            </div>
        `;

        container.innerHTML = html;
    }

    /**
     * Render analysis section
     */
    renderAnalysis(titleStatus, descStatus) {
        let html = '<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">';

        // Title Analysis
        html += `
            <div class="analysis-item">
                <div style="font-weight: 600; margin-bottom: 5px; color: #2c3e50;">
                    Title (SEO Title)
                </div>
                <div style="font-size: 13px;">
                    <div style="margin-bottom: 5px;">
                        <span style="color: ${titleStatus.color}; font-weight: 600;">
                            ${titleStatus.icon} ${titleStatus.label}
                        </span>
                    </div>
                    <div style="color: #666;">
                        ${this.title.length}/60 characters
                    </div>
                    ${titleStatus.message ? `<div style="color: #999; font-size: 12px; margin-top: 5px;">${titleStatus.message}</div>` : ''}
                </div>
            </div>
        `;

        // Description Analysis
        html += `
            <div class="analysis-item">
                <div style="font-weight: 600; margin-bottom: 5px; color: #2c3e50;">
                    Meta Description
                </div>
                <div style="font-size: 13px;">
                    <div style="margin-bottom: 5px;">
                        <span style="color: ${descStatus.color}; font-weight: 600;">
                            ${descStatus.icon} ${descStatus.label}
                        </span>
                    </div>
                    <div style="color: #666;">
                        ${this.description.length}/160 characters
                    </div>
                    ${descStatus.message ? `<div style="color: #999; font-size: 12px; margin-top: 5px;">${descStatus.message}</div>` : ''}
                </div>
            </div>
        `;

        html += '</div>';
        return html;
    }

    /**
     * Get title status
     */
    getTitleStatus() {
        const length = this.title.length;

        if (length === 0) {
            return {
                icon: '❌',
                label: 'Missing',
                color: '#dc3545',
                message: 'Add a SEO title'
            };
        }

        if (length < 30) {
            return {
                icon: '⚠️',
                label: 'Too Short',
                color: '#ffc107',
                message: 'At least 30 characters recommended'
            };
        }

        if (length > 60) {
            return {
                icon: '⚠️',
                label: 'Too Long',
                color: '#ffc107',
                message: 'Keep it under 60 characters'
            };
        }

        return {
            icon: '✅',
            label: 'Good',
            color: '#28a745',
            message: ''
        };
    }

    /**
     * Get description status
     */
    getDescriptionStatus() {
        const length = this.description.length;

        if (length === 0) {
            return {
                icon: '❌',
                label: 'Missing',
                color: '#dc3545',
                message: 'Add a meta description'
            };
        }

        if (length < 120) {
            return {
                icon: '⚠️',
                label: 'Too Short',
                color: '#ffc107',
                message: 'At least 120 characters recommended'
            };
        }

        if (length > 160) {
            return {
                icon: '⚠️',
                label: 'Too Long',
                color: '#ffc107',
                message: 'Keep it under 160 characters'
            };
        }

        return {
            icon: '✅',
            label: 'Good',
            color: '#28a745',
            message: ''
        };
    }

    /**
     * Escape HTML
     */
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', () => {
    const preview = new GoogleSnippetPreview();
    preview.init();
});

// Export for use
if (typeof module !== 'undefined' && module.exports) {
    module.exports = GoogleSnippetPreview;
}
