/**
 * VMO AI Builder - SEO Tools & Auto-Generation
 * Automatically generates SEO meta tags, structured data, and provides testing tools
 */

(function($) {
    'use strict';

    // === SEO GENERATION FUNCTIONS ===
    
    /**
     * Automatically generate SEO meta tags for a page
     */
    window.vmoGenerateSEO = function(pageContent) {
        console.log('VMO: Generating SEO for page...');
        
        try {
            // Extract page information
            const title = extractPageTitle(pageContent);
            const description = extractPageDescription(pageContent);
            const keywords = extractKeywords(pageContent);
            const images = extractImages(pageContent);
            
            // Generate meta tags
            const seoTags = {
                title: title,
                description: description,
                keywords: keywords,
                ogTitle: title,
                ogDescription: description,
                ogImage: images[0] || '',
                ogType: 'website',
                twitterCard: 'summary_large_image',
                twitterTitle: title,
                twitterDescription: description,
                twitterImage: images[0] || '',
                canonical: window.location.href,
                robots: 'index, follow',
                viewport: 'width=device-width, initial-scale=1.0',
                charset: 'UTF-8'
            };
            
            // Generate structured data
            const structuredData = generateStructuredData(pageContent, seoTags);
            
            // Apply SEO tags to document
            applySEOToDocument(seoTags, structuredData);
            
            console.log('VMO: SEO generated successfully', seoTags);
            return seoTags;
            
        } catch (error) {
            console.error('VMO: Error generating SEO:', error);
            return null;
        }
    };
    
    /**
     * Extract page title from content
     */
    function extractPageTitle(content) {
        const $content = $(content);
        
        // Try to find the main heading
        let title = $content.find('h1').first().text().trim();
        
        // Fallback to other headings
        if (!title) {
            title = $content.find('h2, h3').first().text().trim();
        }
        
        // Fallback to existing title tag
        if (!title) {
            title = $('title').text().trim();
        }
        
        // Default fallback
        if (!title) {
            title = (document.body && document.body.dataset && document.body.dataset.businessName) || $('meta[property="og:site_name"]').attr('content') || window.location.hostname.replace(/^www\./, '') || 'Professional Website';
        }
        
        // Keep title within the range search engines typically display.
        title = title.substring(0, 60);
        
        return title;
    }
    
    /**
     * Extract meta description from content
     */
    function extractPageDescription(content) {
        const $content = $(content);
        
        // Try to find description in paragraphs
        let description = '';
        $content.find('p').each(function() {
            const text = $(this).text().trim();
            if (text.length > 100 && text.length < 300) {
                description = text;
                return false; // break
            }
        });
        
        // Fallback to first substantial paragraph
        if (!description) {
            const firstP = $content.find('p').first().text().trim();
            description = firstP.substring(0, 150);
        }
        
        // Default fallback
        if (!description) {
            const siteName = $('meta[property="og:site_name"]').attr('content') || window.location.hostname.replace(/^www\./, '');
            description = siteName ? `Learn more about ${siteName}, services, answers, and next steps.` : 'Learn more about this business, services, answers, and next steps.';
        }
        
        // Ensure proper length
        if (description.length > 155) {
            description = description.substring(0, 152) + '...';
        }
        
        return description;
    }
    
    /**
     * Extract keywords from content
     */
    function extractKeywords(content) {
        const $content = $(content);
        const text = $content.text().toLowerCase();
        
        // Common keywords based on content
        const commonWords = ['the', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by', 'is', 'are', 'was', 'were', 'be', 'been', 'have', 'has', 'had', 'will', 'would', 'could', 'should', 'may', 'might', 'can', 'must', 'shall', 'this', 'that', 'these', 'those'];
        
        // Extract words
        const words = text.match(/\b\w+\b/g) || [];
        const wordCount = {};
        
        words.forEach(word => {
            if (word.length > 3 && !commonWords.includes(word)) {
                wordCount[word] = (wordCount[word] || 0) + 1;
            }
        });
        
        // Get top keywords
        const keywords = Object.keys(wordCount)
            .sort((a, b) => wordCount[b] - wordCount[a])
            .slice(0, 10)
            .join(', ');
        
        return keywords;
    }
    
    /**
     * Extract images from content
     */
    function extractImages(content) {
        const $content = $(content);
        const images = [];
        
        $content.find('img').each(function() {
            const src = $(this).attr('src');
            if (src && !src.includes('placeholder')) {
                // Convert relative URLs to absolute
                const absoluteUrl = new URL(src, window.location.href).href;
                images.push(absoluteUrl);
            }
        });
        
        return images;
    }
    
    /**
     * Generate structured data (JSON-LD)
     */
    function generateStructuredData(content, seoTags) {
        const $content = $(content);
        
        // Basic website schema
        const structuredData = {
            "@context": "https://schema.org",
            "@type": "WebPage",
            "name": seoTags.title,
            "description": seoTags.description,
            "url": window.location.href,
            "inLanguage": "en-US",
            "isPartOf": {
                "@type": "WebSite",
                "name": $('meta[property="og:site_name"]').attr('content') || document.title || window.location.hostname.replace(/^www\./, ''),
                "url": window.location.origin
            }
        };
        
        // Add organization if business content detected
        if (content.toLowerCase().includes('about') || content.toLowerCase().includes('company')) {
            structuredData.about = {
                "@type": "Organization",
                "name": $('meta[property="og:site_name"]').attr('content') || seoTags.title,
                "description": seoTags.description
            };
        }
        
        // Add breadcrumbs if multiple sections
        const headings = $content.find('h1, h2, h3').map(function() {
            return $(this).text().trim();
        }).get();
        
        if (headings.length > 1) {
            structuredData.breadcrumb = {
                "@type": "BreadcrumbList",
                "itemListElement": headings.slice(0, 5).map((heading, index) => ({
                    "@type": "ListItem",
                    "position": index + 1,
                    "name": heading
                }))
            };
        }
        
        return structuredData;
    }
    
    /**
     * Apply SEO tags to document
     */
    function applySEOToDocument(seoTags, structuredData) {
        const head = document.head;
        
        // Remove existing meta tags
        $('meta[name="description"], meta[property^="og:"], meta[name^="twitter:"], link[rel="canonical"]').remove();
        $('#vmo-structured-data').remove();
        
        // Update title
        document.title = seoTags.title;
        
        // Basic meta tags
        addMetaTag('description', seoTags.description);
        addMetaTag('robots', seoTags.robots);
        
        // Open Graph tags
        addMetaTag('og:title', seoTags.ogTitle, 'property');
        addMetaTag('og:description', seoTags.ogDescription, 'property');
        addMetaTag('og:image', seoTags.ogImage, 'property');
        addMetaTag('og:type', seoTags.ogType, 'property');
        addMetaTag('og:url', seoTags.canonical, 'property');
        
        // Twitter Card tags
        addMetaTag('twitter:card', seoTags.twitterCard);
        addMetaTag('twitter:title', seoTags.twitterTitle);
        addMetaTag('twitter:description', seoTags.twitterDescription);
        addMetaTag('twitter:image', seoTags.twitterImage);
        
        // Canonical URL
        const canonical = document.createElement('link');
        canonical.rel = 'canonical';
        canonical.href = seoTags.canonical;
        head.appendChild(canonical);
        
        // Structured data
        const structuredScript = document.createElement('script');
        structuredScript.type = 'application/ld+json';
        structuredScript.id = 'vmo-structured-data';
        structuredScript.textContent = JSON.stringify(structuredData, null, 2);
        head.appendChild(structuredScript);
        
        console.log('VMO: SEO tags applied to document');
    }
    
    /**
     * Helper function to add meta tags
     */
    function addMetaTag(name, content, attribute = 'name') {
        if (!content) return;
        
        const meta = document.createElement('meta');
        meta.setAttribute(attribute, name);
        meta.content = content;
        document.head.appendChild(meta);
    }
    
    /**
     * Test and preview SEO
     */
    window.vmoTestSEO = function() {
        const seoData = getCurrentSEOData();
        
        // Create SEO preview modal
        const modal = createSEOPreviewModal(seoData);
        $('body').append(modal);
        
        // Show modal
        $('#vmo-seo-preview-modal').fadeIn();
        
        return seoData;
    };
    
    /**
     * Get current SEO data from document
     */
    function getCurrentSEOData() {
        return {
            title: document.title,
            description: $('meta[name="description"]').attr('content') || '',
            canonical: $('link[rel="canonical"]').attr('href') || '',
            ogTitle: $('meta[property="og:title"]').attr('content') || '',
            ogDescription: $('meta[property="og:description"]').attr('content') || '',
            ogImage: $('meta[property="og:image"]').attr('content') || '',
            structuredData: $('#vmo-structured-data').text() || ''
        };
    }
    
    /**
     * Create SEO preview modal
     */
    function createSEOPreviewModal(seoData) {
        return `
            <div id="vmo-seo-preview-modal" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.9);z-index:10001;overflow-y:auto;">
                <div style="max-width:800px;margin:2rem auto;background:#fff;border-radius:10px;color:#333;">
                    <div style="padding:2rem;border-bottom:1px solid #eee;">
                        <h2 style="margin:0;color:#333;">SEO Preview & Testing</h2>
                        <button onclick="$('#vmo-seo-preview-modal').fadeOut()" style="position:absolute;top:1rem;right:1rem;background:none;border:none;font-size:1.5rem;cursor:pointer;">×</button>
                    </div>
                    
                    <div style="padding:2rem;">
                        <!-- Google Search Preview -->
                        <h3>Google Search Preview</h3>
                        <div style="max-width:600px;margin:1rem 0;padding:1rem;border:1px solid #e1e5e9;border-radius:8px;background:#fff;">
                            <div style="color:#1a0dab;font-size:20px;line-height:1.3;margin-bottom:4px;text-decoration:underline;">${seoData.title}</div>
                            <div style="color:#006621;font-size:14px;margin-bottom:4px;">${seoData.canonical}</div>
                            <div style="color:#545454;font-size:14px;line-height:1.4;">${seoData.description}</div>
                        </div>
                        
                        <!-- Facebook Preview -->
                        <h3 style="margin-top:2rem;">Facebook Preview</h3>
                        <div style="max-width:500px;margin:1rem 0;border:1px solid #dadde1;border-radius:8px;overflow:hidden;background:#fff;">
                            ${seoData.ogImage ? `<img src="${seoData.ogImage}" style="width:100%;height:250px;object-fit:cover;" alt="Preview">` : '<div style="height:250px;background:#f0f2f5;display:flex;align-items:center;justify-content:center;color:#65676b;">No Image</div>'}
                            <div style="padding:12px;">
                                <div style="color:#385898;font-size:12px;line-height:1.2;margin-bottom:4px;text-transform:uppercase;">${window.location.hostname}</div>
                                <div style="color:#1d2129;font-size:16px;font-weight:600;line-height:1.3;margin-bottom:4px;">${seoData.ogTitle}</div>
                                <div style="color:#606770;font-size:14px;line-height:1.3;">${seoData.ogDescription}</div>
                            </div>
                        </div>
                        
                        <!-- SEO Score -->
                        <h3 style="margin-top:2rem;">SEO Analysis</h3>
                        <div id="seo-score" style="margin:1rem 0;">
                            ${generateSEOScore(seoData)}
                        </div>
                        
                        <!-- Raw Data -->
                        <details style="margin-top:2rem;">
                            <summary style="cursor:pointer;font-weight:600;">View Raw SEO Data</summary>
                            <pre style="background:#f8f9fa;padding:1rem;border-radius:4px;overflow:auto;font-size:12px;margin-top:1rem;">${JSON.stringify(seoData, null, 2)}</pre>
                        </details>
                        
                        <div style="text-align:center;margin-top:2rem;">
                            <button onclick="$('#vmo-seo-preview-modal').fadeOut()" style="background:#007cba;color:white;border:none;padding:12px 24px;border-radius:4px;cursor:pointer;">Close Preview</button>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }
    
    /**
     * Generate SEO score and recommendations
     */
    function generateSEOScore(seoData) {
        let score = 0;
        const checks = [];
        
        // Title check
        if (seoData.title && seoData.title.length >= 30 && seoData.title.length <= 60) {
            score += 20;
            checks.push({ status: 'pass', text: 'Title length is optimal (30-60 characters)' });
        } else {
            checks.push({ status: 'fail', text: 'Title should be 30-60 characters long' });
        }
        
        // Description check
        if (seoData.description && seoData.description.length >= 120 && seoData.description.length <= 155) {
            score += 20;
            checks.push({ status: 'pass', text: 'Meta description length is optimal (120-155 characters)' });
        } else {
            checks.push({ status: 'fail', text: 'Meta description should be 120-155 characters long' });
        }
        
        // Open Graph check
        if (seoData.ogTitle && seoData.ogDescription) {
            score += 25;
            checks.push({ status: 'pass', text: 'Open Graph tags are configured' });
        } else {
            checks.push({ status: 'fail', text: 'Open Graph tags missing' });
        }
        
        // Image check
        if (seoData.ogImage) {
            score += 20;
            checks.push({ status: 'pass', text: 'Social media image is set' });
        } else {
            checks.push({ status: 'warning', text: 'Consider adding a social media image' });
        }
        
        // Structured data check
        if (seoData.structuredData) {
            score += 10;
            checks.push({ status: 'pass', text: 'Structured data is present' });
        } else {
            checks.push({ status: 'warning', text: 'Consider adding structured data' });
        }
        
    const scoreColor = score >= 80 ? '#0fe1ff' : score >= 60 ? '#ffc107' : '#7c5cff';
        
        let html = `<div style="font-size:24px;font-weight:bold;color:${scoreColor};margin-bottom:1rem;">SEO Score: ${score}/100</div>`;
        
        checks.forEach(check => {
            const icon = check.status === 'pass' ? '✅' : check.status === 'warning' ? '⚠️' : '❌';
            html += `<div style="margin:8px 0;"><span style="margin-right:8px;">${icon}</span>${check.text}</div>`;
        });
        
        return html;
    }
    
    // Auto-generate SEO when page content changes
    $(document).ready(function() {
        // Auto-generate SEO for initial page
        setTimeout(() => {
            const iframe = document.getElementById('vmo-preview-iframe');
            if (iframe && iframe.contentDocument) {
                const content = iframe.contentDocument.body.innerHTML;
                window.vmoGenerateSEO(content);
            }
        }, 1000);
    });

})(jQuery);
