/**
 * VMO Media Integration Specialist - Frontend Interface
 * Handles the media integration modal and AI agent communication
 */

(function($) {
    'use strict';

    // Media Integration System
    window.vmoMediaIntegration = {
        currentMedia: null,
        isProcessing: false,
        modal: null,
        
        // Initialize the media integration system
        init: function() {
            this.createIntegrationModal();
            this.bindEvents();
            this.loadSuggestions();
            console.log('VMO Media Integration Agent initialized');
        },
        
        // Create the integration modal HTML
        createIntegrationModal: function() {
            const modalHTML = `
                <div id="vmo-media-integration-modal" class="vmo-modal" style="display: none;">
                    <div class="vmo-modal-overlay"></div>
                    <div class="vmo-modal-content vmo-media-integration-content">
                        <div class="vmo-modal-header">
                            <h3>🎨 Media Integration Specialist</h3>
                            <button class="vmo-modal-close">&times;</button>
                        </div>
                        
                        <div class="vmo-modal-body">
                            <!-- Media Preview -->
                            <div class="vmo-media-preview">
                                <div class="vmo-media-preview-container">
                                    <div id="vmo-preview-placeholder">
                                        Select media to preview integration options
                                    </div>
                                </div>
                                <div class="vmo-media-info">
                                    <span id="vmo-media-type">No media selected</span>
                                    <span id="vmo-media-url">—</span>
                                </div>
                            </div>
                            
                            <!-- Integration Prompt -->
                            <div class="vmo-integration-prompt">
                                <label for="vmo-integration-input">Describe how you want to integrate this media:</label>
                                <textarea 
                                    id="vmo-integration-input" 
                                    placeholder="Example: Place this image as a floating element with a subtle shadow over the hero section, positioned in the top-right corner with a gentle fade-in animation..."
                                    rows="4"
                                ></textarea>
                                <div class="vmo-prompt-suggestions">
                                    <span class="vmo-suggestions-label">Quick suggestions:</span>
                                    <div id="vmo-suggestion-tags"></div>
                                </div>
                            </div>
                            
                            <!-- Advanced Options -->
                            <div class="vmo-advanced-options">
                                <button type="button" class="vmo-toggle-advanced">
                                    Advanced Options <span class="vmo-toggle-icon">▼</span>
                                </button>
                                <div class="vmo-advanced-panel" style="display: none;">
                                    <div class="vmo-option-group">
                                        <label>Device Priority:</label>
                                        <select id="vmo-device-priority">
                                            <option value="mobile-first">Mobile First</option>
                                            <option value="desktop-first">Desktop First</option>
                                            <option value="tablet-optimized">Tablet Optimized</option>
                                        </select>
                                    </div>
                                    <div class="vmo-option-group">
                                        <label>Animation Style:</label>
                                        <select id="vmo-animation-style">
                                            <option value="subtle">Subtle</option>
                                            <option value="dynamic">Dynamic</option>
                                            <option value="none">No Animation</option>
                                        </select>
                                    </div>
                                    <div class="vmo-option-group">
                                        <label>Integration Context:</label>
                                        <textarea id="vmo-project-context" placeholder="Describe your project style, target audience, or specific design requirements..." rows="2"></textarea>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Cost Display -->
                            <div class="vmo-cost-display">
                                <div class="vmo-cost-info">
                                    <span class="vmo-cost-label">Integration Cost:</span>
                                    <span class="vmo-cost-amount">$0.50</span>
                                </div>
                                <div class="vmo-balance-info">
                                    <span id="vmo-current-balance">Balance: Loading...</span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="vmo-modal-footer">
                            <button type="button" class="vmo-btn-secondary" id="vmo-cancel-integration">Cancel</button>
                            <button type="button" class="vmo-btn-primary" id="vmo-execute-integration" disabled>
                                <span class="vmo-btn-text">🚀 Integrate Media</span>
                                <span class="vmo-btn-loading" style="display: none;">
                                    <span class="vmo-spinner"></span> Processing...
                                </span>
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            $('body').append(modalHTML);
            this.modal = $('#vmo-media-integration-modal');
        },
        
        // Bind event handlers
        bindEvents: function() {
            const self = this;
            
            // Modal controls
            $(document).on('click', '.vmo-modal-close, #vmo-cancel-integration', function() {
                self.closeModal();
            });
            
            // Click outside modal to close
            $(document).on('click', '.vmo-modal-overlay', function() {
                self.closeModal();
            });
            
            // Integration prompt input
            $('#vmo-integration-input').on('input', function() {
                self.validateInput();
            });
            
            // Execute integration
            $('#vmo-execute-integration').on('click', function() {
                self.executeIntegration();
            });
            
            // Toggle advanced options
            $('.vmo-toggle-advanced').on('click', function() {
                const panel = $('.vmo-advanced-panel');
                const icon = $('.vmo-toggle-icon');
                
                panel.slideToggle();
                icon.text(panel.is(':visible') ? '▲' : '▼');
            });
            
            // Suggestion tags
            $(document).on('click', '.vmo-suggestion-tag', function() {
                const suggestion = $(this).text();
                const currentText = $('#vmo-integration-input').val();
                const newText = currentText ? currentText + ' ' + suggestion : suggestion;
                $('#vmo-integration-input').val(newText).trigger('input');
            });
            
            // WordPress media library integration
            $(document).on('click', '.vmo-media-integrate-btn', function() {
                const mediaData = $(this).data();
                self.openModalWithMedia(mediaData);
            });
        },
        
        // Open modal with specific media
        openModalWithMedia: function(mediaData) {
            this.currentMedia = mediaData;
            this.updateMediaPreview();
            this.loadTokenBalance();
            this.loadSuggestionsForType(mediaData.type);
            this.modal.fadeIn(300);
        },
        
        // Update media preview in modal
        updateMediaPreview: function() {
            if (!this.currentMedia) return;
            
            const preview = $('#vmo-preview-placeholder');
            const mediaType = this.currentMedia.type;
            const mediaUrl = this.currentMedia.url;
            
            let previewHTML = '';
            
            switch (mediaType) {
                case 'image':
                    previewHTML = `<img src="${mediaUrl}" alt="Media Preview" style="max-width: 100%; height: auto; border-radius: 8px;">`;
                    break;
                case 'video':
                    previewHTML = `<video src="${mediaUrl}" controls style="max-width: 100%; height: auto; border-radius: 8px;">`;
                    break;
                default:
                    previewHTML = `<div class="vmo-media-placeholder">📄 ${mediaType.toUpperCase()} file</div>`;
            }
            
            preview.html(previewHTML);
            $('#vmo-media-type').text(mediaType.toUpperCase());
            $('#vmo-media-url').text(mediaUrl);
        },
        
        // Load integration suggestions
        loadSuggestions: function() {
            // Default suggestions will be loaded when media type is selected
        },
        
        // Load suggestions for specific media type
        loadSuggestionsForType: function(mediaType) {
            const suggestions = this.getSuggestionsForType(mediaType);
            const container = $('#vmo-suggestion-tags');
            
            container.empty();
            suggestions.forEach(function(suggestion) {
                const tag = $(`<button type="button" class="vmo-suggestion-tag">${suggestion}</button>`);
                container.append(tag);
            });
        },
        
        // Get suggestions based on media type
        getSuggestionsForType: function(mediaType) {
            const suggestions = {
                image: [
                    'floating with shadow',
                    'circular mask',
                    'background with overlay',
                    'grid layout',
                    'polaroid frame',
                    'fade-in animation',
                    'hover zoom effect'
                ],
                video: [
                    'background autoplay',
                    'modal popup',
                    'floating player',
                    'custom controls',
                    'hero section',
                    'thumbnail preview'
                ],
                svg: [
                    'scroll animation',
                    'background pattern',
                    'interactive hover',
                    'logo animation',
                    'decorative accent'
                ]
            };
            
            return suggestions[mediaType] || ['creative placement', 'responsive design', 'smooth animation'];
        },
        
        // Load current token balance
        loadTokenBalance: function() {
            $.post(vmo_ajax.ajaxurl, {
                action: 'vmo_get_token_balance',
                security: vmo_ajax.nonce
            }).done(function(response) {
                if (response.success) {
                    $('#vmo-current-balance').text(`Balance: ${response.data.balance}`);
                }
            });
        },
        
        // Validate input and enable/disable button
        validateInput: function() {
            const prompt = $('#vmo-integration-input').val().trim();
            const button = $('#vmo-execute-integration');
            
            if (prompt.length > 10 && this.currentMedia) {
                button.prop('disabled', false);
            } else {
                button.prop('disabled', true);
            }
        },
        
        // Execute the media integration
        executeIntegration: function() {
            if (this.isProcessing || !this.currentMedia) return;
            
            this.isProcessing = true;
            this.showProcessingState();
            
            const integrationData = {
                action: 'vmo_integrate_media',
                security: vmo_ajax.nonce,
                media_url: this.currentMedia.url,
                media_type: this.currentMedia.type,
                integration_prompt: $('#vmo-integration-input').val(),
                project_context: $('#vmo-project-context').val(),
                current_html: this.getCurrentProjectHTML(),
                device_priority: $('#vmo-device-priority').val(),
                animation_style: $('#vmo-animation-style').val()
            };
            
            $.post(vmo_ajax.ajaxurl, integrationData)
                .done(this.handleIntegrationSuccess.bind(this))
                .fail(this.handleIntegrationError.bind(this))
                .always(this.hideProcessingState.bind(this));
        },
        
        // Handle successful integration
        handleIntegrationSuccess: function(response) {
            this.isProcessing = false;
            
            if (response.success) {
                const integration = response.data.integration;
                
                // Apply the integration to the current project
                this.applyIntegration(integration);
                
                // Show success message
                this.showToast('Media integrated successfully! ✨', 'success');
                
                // Update token balance
                this.loadTokenBalance();
                
                // Close modal
                this.closeModal();
                
                console.log('Media Integration Success:', integration);
            } else {
                this.showToast(response.data.message || 'Integration failed', 'error');
            }
        },
        
        // Handle integration error
        handleIntegrationError: function(xhr, status, error) {
            this.isProcessing = false;
            console.error('Media Integration Error:', error);
            this.showToast('Integration request failed. Please try again.', 'error');
        },
        
        // Apply integration to current project
        applyIntegration: function(integration) {
            // Add the CSS to the current project
            if (integration.css) {
                this.addCSSToProject(integration.css);
            }
            
            // Add/update HTML in the current project
            if (integration.html) {
                this.addHTMLToProject(integration.html);
            }
            
            // Trigger project update
            if (typeof window.renderBlocks === 'function') {
                window.renderBlocks();
            }
            
            // Show integration details
            this.showIntegrationDetails(integration);
        },
        
        // Add CSS to current project
        addCSSToProject: function(css) {
            // Check if there's a custom CSS area in the project
            let styleElement = $('#vmo-dynamic-styles');
            
            if (styleElement.length === 0) {
                styleElement = $('<style id="vmo-dynamic-styles"></style>');
                $('head').append(styleElement);
            }
            
            // Append new CSS
            const currentCSS = styleElement.text();
            styleElement.text(currentCSS + '\n\n/* Media Integration Styles */\n' + css);
        },
        
        // Add HTML to current project
        addHTMLToProject: function(html) {
            // Find the current active section or canvas
            const activeSection = $('.vmo-section.active, .vmo-canvas').first();
            
            if (activeSection.length) {
                // Create a wrapper for the integrated media
                const wrapper = $('<div class="vmo-media-integration"></div>').html(html);
                activeSection.append(wrapper);
                
                // Add edit controls if they exist
                if (typeof window.addEditControls === 'function') {
                    window.addEditControls(wrapper);
                }
            }
        },
        
        // Get current project HTML for context
        getCurrentProjectHTML: function() {
            const canvas = $('.vmo-canvas, .vmo-preview-area').first();
            return canvas.length ? canvas.html() : '';
        },
        
        // Show integration details
        showIntegrationDetails: function(integration) {
            if (integration.description || integration.creative_elements) {
                let details = '';
                
                if (integration.description) {
                    details += `<strong>Integration:</strong> ${integration.description}<br>`;
                }
                
                if (integration.creative_elements && integration.creative_elements.length > 0) {
                    details += `<strong>Creative Elements:</strong> ${integration.creative_elements.join(', ')}`;
                }
                
                this.showToast(details, 'info', 5000);
            }
        },
        
        // Show processing state
        showProcessingState: function() {
            $('#vmo-execute-integration').prop('disabled', true);
            $('.vmo-btn-text').hide();
            $('.vmo-btn-loading').show();
        },
        
        // Hide processing state
        hideProcessingState: function() {
            $('#vmo-execute-integration').prop('disabled', false);
            $('.vmo-btn-text').show();
            $('.vmo-btn-loading').hide();
        },
        
        // Close modal
        closeModal: function() {
            this.modal.fadeOut(300);
            this.resetModal();
        },
        
        // Reset modal to initial state
        resetModal: function() {
            $('#vmo-integration-input').val('');
            $('#vmo-project-context').val('');
            $('#vmo-preview-placeholder').html('Select media to preview integration options');
            $('#vmo-media-type').text('No media selected');
            $('#vmo-media-url').text('—');
            $('#vmo-suggestion-tags').empty();
            $('.vmo-advanced-panel').hide();
            $('.vmo-toggle-icon').text('▼');
            this.currentMedia = null;
            this.isProcessing = false;
        },
        
        // Show toast notification
        showToast: function(message, type = 'info', duration = 3000) {
            if (typeof window.showToast === 'function') {
                window.showToast(message, type, duration);
            } else {
                console.log(`Toast (${type}):`, message);
            }
        }
    };

    // Integration with WordPress Media Library
    if (typeof wp !== 'undefined' && wp.media) {
        // Extend media modal to include integration button
        const originalMediaModal = wp.media.view.Modal;
        wp.media.view.Modal = originalMediaModal.extend({
            events: function() {
                return _.extend({}, originalMediaModal.prototype.events, {
                    'click .vmo-integrate-media': 'integrateMedia'
                });
            },
            
            integrateMedia: function(e) {
                e.preventDefault();
                const selection = this.controller.state().get('selection');
                const model = selection.first();
                
                if (model) {
                    const mediaData = {
                        id: model.get('id'),
                        url: model.get('url'),
                        type: model.get('type'),
                        filename: model.get('filename'),
                        title: model.get('title')
                    };
                    
                    window.vmoMediaIntegration.openModalWithMedia(mediaData);
                    this.controller.modal.close();
                }
            }
        });
        
        // Add integration button to media modal
        wp.media.view.Button.extend({
            initialize: function() {
                if (this.model && this.model.get('id') === 'vmo-integrate') {
                    this.$el.addClass('button-primary vmo-integrate-media');
                    this.$el.text('🎨 AI Integrate');
                }
            }
        });
    }

    // Initialize when DOM is ready
    $(document).ready(function() {
        window.vmoMediaIntegration.init();
    });

})(jQuery);
