/**
 * VMO Media Integration Specialist - Backend Integration
 * Handles AI-powered media integration without frontend modal
 */

window.VMOMediaIntegration = (function($) {
    'use strict';
    
    let isProcessing = false;
    let progressInterval = null;
    
    return {
        /**
         * Process media integration with AI agent
         * Called by existing VMO media handling system
         */
        processIntegration: function(mediaData, integrationPrompt, callback) {
            if (!mediaData || !integrationPrompt) {
                if (callback) callback({success: false, message: 'Missing required parameters'});
                return;
            }
            
            if (isProcessing) {
                this.showToast('🤖 Media integration already in progress...', 'info');
                return;
            }
            
            isProcessing = true;
            
            // Show loading state with progress meter
            this.showProgressToast();
            
            // Make AJAX request to Media Integration Agent
            $.ajax({
                url: vmo_ajax.ajaxurl || vmoAjax.ajax_url,
                type: 'POST',
                data: {
                    action: 'vmo_integrate_media',
                    security: vmo_ajax.nonce || vmoAjax.nonce,
                    media_url: mediaData.url,
                    media_type: mediaData.type,
                    integration_prompt: integrationPrompt,
                    current_html: this.getCurrentProjectHTML(),
                    project_context: this.getProjectContext()
                },
                success: function(response) {
                    this.hideProgressToast();
                    isProcessing = false;
                    
                    if (response.success) {
                        // Integration successful - apply to current project
                        this.applyIntegrationToProject(response.data);
                        this.showToast('🎨 Media integrated successfully! AI has placed your media with creative precision.', 'success');
                        if (callback) callback(response);
                    } else {
                        this.showToast('❌ ' + (response.data?.message || 'Integration failed'), 'error');
                        if (callback) callback(response);
                    }
                }.bind(this),
                error: function(xhr, status, error) {
                    this.hideProgressToast();
                    isProcessing = false;
                    this.showToast('❌ Request failed: ' + error, 'error');
                    if (callback) callback({success: false, message: 'Request failed'});
                }.bind(this)
            });
        },
        
        /**
         * Show progress toast with sci-fi meter
         */
        showProgressToast: function() {
            const progressHtml = `
                <div class="vmo-integration-progress">
                    <div class="vmo-integration-title">🤖 AI Media Integration Specialist</div>
                    <div class="vmo-integration-status">Analyzing project context and generating creative placement...</div>
                    <div class="vmo-progress-meter">
                        <div class="vmo-progress-bar">
                            <div class="vmo-progress-fill"></div>
                            <div class="vmo-progress-glow"></div>
                        </div>
                        <div class="vmo-progress-particles">
                            <span class="vmo-particle"></span>
                            <span class="vmo-particle"></span>
                            <span class="vmo-particle"></span>
                            <span class="vmo-particle"></span>
                        </div>
                    </div>
                    <div class="vmo-integration-details">
                        <span class="vmo-detail-item">🧠 Context Analysis</span>
                        <span class="vmo-detail-item">🎨 Creative Generation</span>
                        <span class="vmo-detail-item">📱 Responsive Optimization</span>
                    </div>
                </div>
            `;
            
            // Use existing VMO toast system with custom content
            if (typeof window.showToast === 'function') {
                window.showToast(progressHtml, 'info', true, true);
                
                // Add custom CSS for the progress meter
                this.injectProgressStyles();
                
                // Start progress animation
                this.startProgressAnimation();
            }
        },
        
        /**
         * Hide progress toast
         */
        hideProgressToast: function() {
            this.stopProgressAnimation();
            if (typeof window.hideToast === 'function') {
                window.hideToast(true);
            }
        },
        
        /**
         * Inject sci-fi progress meter styles
         */
        injectProgressStyles: function() {
            if ($('#vmo-integration-progress-styles').length) return;
            
            const styles = `
                <style id="vmo-integration-progress-styles">
                .vmo-integration-progress {
                    text-align: center;
                    padding: 10px;
                }
                
                .vmo-integration-title {
                    font-size: 1.1em;
                    color: #00ffff;
                    margin-bottom: 8px;
                    text-shadow: 0 0 10px #00ffff80;
                }
                
                .vmo-integration-status {
                    font-size: 0.9em;
                    color: #88ffff;
                    margin-bottom: 15px;
                    opacity: 0.9;
                }
                
                .vmo-progress-meter {
                    position: relative;
                    margin: 15px 0;
                }
                
                .vmo-progress-bar {
                    position: relative;
                    width: 100%;
                    height: 8px;
                    background: rgba(0, 255, 255, 0.1);
                    border-radius: 4px;
                    border: 1px solid rgba(0, 255, 255, 0.3);
                    overflow: hidden;
                }
                
                .vmo-progress-fill {
                    height: 100%;
                    width: 0%;
                    background: linear-gradient(90deg, 
                        #00ffff 0%, 
                        #0080ff 25%, 
                        #00ffff 50%, 
                        #0080ff 75%, 
                        #00ffff 100%);
                    background-size: 200% 100%;
                    border-radius: 4px;
                    animation: vmo-progress-flow 2s ease-in-out infinite;
                    box-shadow: 0 0 15px rgba(0, 255, 255, 0.6);
                }
                
                .vmo-progress-glow {
                    position: absolute;
                    top: -2px;
                    left: -2px;
                    right: -2px;
                    bottom: -2px;
                    background: rgba(0, 255, 255, 0.1);
                    border-radius: 6px;
                    animation: vmo-progress-pulse 1.5s ease-in-out infinite alternate;
                }
                
                .vmo-progress-particles {
                    position: absolute;
                    top: -10px;
                    left: 0;
                    right: 0;
                    height: 20px;
                    pointer-events: none;
                }
                
                .vmo-particle {
                    position: absolute;
                    width: 3px;
                    height: 3px;
                    background: #00ffff;
                    border-radius: 50%;
                    box-shadow: 0 0 8px #00ffff;
                    animation: vmo-particle-float 3s linear infinite;
                }
                
                .vmo-particle:nth-child(1) { left: 10%; animation-delay: 0s; }
                .vmo-particle:nth-child(2) { left: 30%; animation-delay: 0.7s; }
                .vmo-particle:nth-child(3) { left: 60%; animation-delay: 1.4s; }
                .vmo-particle:nth-child(4) { left: 85%; animation-delay: 2.1s; }
                
                .vmo-integration-details {
                    display: flex;
                    justify-content: space-between;
                    margin-top: 12px;
                    font-size: 0.75em;
                }
                
                .vmo-detail-item {
                    color: #88ffff;
                    opacity: 0.7;
                    animation: vmo-detail-glow 2s ease-in-out infinite alternate;
                }
                
                .vmo-detail-item:nth-child(2) { animation-delay: 0.5s; }
                .vmo-detail-item:nth-child(3) { animation-delay: 1s; }
                
                @keyframes vmo-progress-flow {
                    0% { background-position: 0% 0%; }
                    100% { background-position: 200% 0%; }
                }
                
                @keyframes vmo-progress-pulse {
                    0% { opacity: 0.1; }
                    100% { opacity: 0.3; }
                }
                
                @keyframes vmo-particle-float {
                    0% { transform: translateY(20px) translateX(-10px); opacity: 0; }
                    10% { opacity: 1; }
                    90% { opacity: 1; }
                    100% { transform: translateY(-20px) translateX(10px); opacity: 0; }
                }
                
                @keyframes vmo-detail-glow {
                    0% { opacity: 0.5; text-shadow: 0 0 5px rgba(0, 255, 255, 0.3); }
                    100% { opacity: 0.9; text-shadow: 0 0 15px rgba(0, 255, 255, 0.7); }
                }
                </style>
            `;
            
            $('head').append(styles);
        },
        
        /**
         * Start progress animation
         */
        startProgressAnimation: function() {
            let progress = 0;
            const statusMessages = [
                'Analyzing current project structure...',
                'Understanding business context...',
                'Consulting AI Media Integration Specialist...',
                'Generating creative placement strategies...',
                'Optimizing for responsive design...',
                'Finalizing integration code...'
            ];
            
            let messageIndex = 0;
            
            progressInterval = setInterval(() => {
                progress += Math.random() * 15 + 5; // Progress 5-20% each step
                if (progress > 95) progress = 95; // Never reach 100% until complete
                
                $('.vmo-progress-fill').css('width', progress + '%');
                
                // Update status message occasionally
                if (Math.random() < 0.3 && messageIndex < statusMessages.length - 1) {
                    messageIndex++;
                    $('.vmo-integration-status').text(statusMessages[messageIndex]);
                }
            }, 800);
        },
        
        /**
         * Stop progress animation
         */
        stopProgressAnimation: function() {
            if (progressInterval) {
                clearInterval(progressInterval);
                progressInterval = null;
            }
            
            // Complete the progress bar
            $('.vmo-progress-fill').css('width', '100%');
        },
        
        /**
         * Show toast message using VMO system
         */
        showToast: function(message, type = 'info') {
            if (typeof window.showToast === 'function') {
                window.showToast(message, type);
            } else {
                console.log(`VMO Media Integration (${type}):`, message);
            }
        },
        /**
         * Get current project HTML for context
         */
        getCurrentProjectHTML: function() {
            // Check if VMO state management exists
            if (window.vmoState && typeof window.vmoState.getCurrentHTML === 'function') {
                return window.vmoState.getCurrentHTML();
            }
            
            // Fallback - get from main content area
            const contentArea = document.querySelector('#vmo-content-area, .vmo-preview-area, #vmo-main-preview');
            return contentArea ? contentArea.innerHTML : '';
        },
        
        /**
         * Get current project context
         */
        getProjectContext: function() {
            const context = {};
            
            // Get project data from VMO state if available
            if (window.vmoState && typeof window.vmoState.getProjectData === 'function') {
                const projectData = window.vmoState.getProjectData();
                context.business_type = projectData.businessType;
                context.template = projectData.template;
                context.colors = projectData.colors;
            }
            
            // Get current template if available
            if (window.vmoTemplates && typeof window.vmoTemplates.getCurrentTemplate === 'function') {
                context.current_template = window.vmoTemplates.getCurrentTemplate();
            }
            
            return JSON.stringify(context);
        },
        
        /**
         * Apply integration results to current project
         */
        applyIntegrationToProject: function(integrationData) {
            try {
                if (integrationData.html && integrationData.css) {
                    // Apply through VMO render system if available
                    if (window.vmoRender && typeof window.vmoRender.applyCustomHTML === 'function') {
                        window.vmoRender.applyCustomHTML(integrationData.html, integrationData.css);
                    }
                    
                    // Update project state
                    if (window.vmoState && typeof window.vmoState.updateContent === 'function') {
                        window.vmoState.updateContent({
                            type: 'media_integration',
                            html: integrationData.html,
                            css: integrationData.css,
                            description: integrationData.description
                        });
                    }
                }
            } catch (error) {
                console.error('VMO Media Integration Error:', error);
                this.showToast('❌ Failed to apply integration to project', 'error');
            }
        },
        
        /**
         * Integration with existing VMO media handling
         */
        init: function() {
            // Hook into existing media upload events if available
            $(document).on('vmo:media:uploaded', function(event, mediaData) {
                // Media was uploaded - check if integration prompt exists
                if (mediaData.integrationPrompt) {
                    VMOMediaIntegration.processIntegration(
                        mediaData, 
                        mediaData.integrationPrompt,
                        function(result) {
                            $(document).trigger('vmo:media:integrated', [result, mediaData]);
                        }
                    );
                }
            });
            
            // Hook into VMO prompts system for media integration commands
            $(document).on('vmo:prompt:media_integration', function(event, promptData) {
                if (promptData.mediaUrl && promptData.prompt) {
                    VMOMediaIntegration.processIntegration(
                        {url: promptData.mediaUrl, type: promptData.mediaType},
                        promptData.prompt,
                        function(result) {
                            $(document).trigger('vmo:integration:complete', [result]);
                        }
                    );
                }
            });
        }
    };
    
})(jQuery);

// Initialize when DOM is ready
jQuery(document).ready(function() {
    VMOMediaIntegration.init();
});
