/**
 * VMO Template Integration v1.0.0
 * Integrates template system with existing preset interface
 */

(function($) {
    'use strict';
    
    console.log('🔗 VMO Template Integration Loading...');
    
    // Initialize template integration when document is ready
    $(document).ready(function() {
        console.log('🔗 Initializing template integration');
        
        // Handle template category item clicks
        $(document).on('click', '.vmo-template-category-item', function(e) {
            e.preventDefault();
            const category = $(this).data('category');
            console.log('🎨 Template category clicked:', category);
            openTemplateModal(category);
        });
        
        // Handle "Browse All Templates" button
        $(document).on('click', '#vmo-browse-all-templates', function(e) {
            e.preventDefault();
            console.log('🎨 Browse all templates clicked');
            openTemplateModal('all');
        });
        
        // Handle template modal close
        $(document).on('click', '#vmo-close-template-modal', function(e) {
            e.preventDefault();
            closeTemplateModal();
        });
        
        // Close modal when clicking outside
        $(document).on('click', '#vmo-template-modal', function(e) {
            if (e.target === this) {
                closeTemplateModal();
            }
        });
        
        // Handle template category buttons in modal
        $(document).on('click', '.vmo-template-category-btn', function(e) {
            e.preventDefault();
            const category = $(this).data('category');
            
            // Update active state
            $('.vmo-template-category-btn').removeClass('active');
            $(this).addClass('active');
            
            // Show templates for category
            if (category === 'all') {
                showAllTemplates();
            } else {
                showTemplatesForCategory(category);
            }
        });
        
        console.log('🔗 Template integration initialized');
    });
    
    // Open template modal with specific category
    function openTemplateModal(category = 'all') {
        console.log('🎨 Opening template modal for category:', category);
        
        // Check if VMOTemplates is available
        if (typeof VMOTemplates === 'undefined') {
            console.error('🎨 VMOTemplates not found');
            alert('Template system is not loaded. Please refresh the page.');
            return;
        }
        
        // Create a container for templates if it doesn't exist
        let templatesContainer = document.getElementById('vmo-templates-container');
        if (!templatesContainer) {
            // Create the template container and modal
            const modalHTML = `
                <div id="vmo-template-modal" class="vmo-template-modal" style="display: none;">
                    <div class="vmo-template-modal-content">
                        <div class="vmo-template-modal-header">
                            <h3>Choose a Template</h3>
                            <button class="vmo-template-close" onclick="closeTemplateModal()">&times;</button>
                        </div>
                        <div class="vmo-template-modal-body">
                            <div id="vmo-templates-container"></div>
                        </div>
                    </div>
                </div>
            `;
            document.body.insertAdjacentHTML('beforeend', modalHTML);
            templatesContainer = document.getElementById('vmo-templates-container');
        }
        
        // Show modal
        const modal = document.getElementById('vmo-template-modal');
        if (modal) {
            modal.style.display = 'flex';
        }
        
        // Load templates using VMOTemplates
        try {
            if (category === 'all') {
                // Show all templates
                VMOTemplates.openSelector('vmo-templates-container');
            } else {
                // Filter templates by category and display ONLY that category
                const templates = VMOTemplates.getTemplatesByCategory(category);
                console.log('🎨 Loading templates for category:', category, 'Found:', templates.length);
                
                if (templates.length === 0) {
                    templatesContainer.innerHTML = `
                        <div style="text-align: center; padding: 40px; color: #666;">
                            <h3>No ${category} templates available yet</h3>
                            <p>More templates coming soon!</p>
                        </div>
                    `;
                    return;
                }
                
                let html = '<div class="vmo-templates-grid">';
                templates.forEach(function(template) {
                    html += createTemplateCardHTML(template);
                });
                html += '</div>';
                
                templatesContainer.innerHTML = html;
                
                // Add grid animations
                VMOTemplates.addGridAnimations();
            }
        } catch (error) {
            console.error('🎨 Error loading templates:', error);
            templatesContainer.innerHTML = '<div class="error">Error loading templates. Please try again.</div>';
        }
    }
    
    // Helper function to create template card HTML
    function createTemplateCardHTML(template) {
        const featuresHtml = template.features.map(function(feature) {
            return '<span class="vmo-template-feature">' + feature + '</span>';
        }).join('');

        const statusBadge = template.ready ? 
            '<div class="vmo-template-status ready">✅ Ready</div>' : 
            '<div class="vmo-template-status coming">🚧 Coming Soon</div>';

        return `
            <div class="vmo-template-card ${template.ready ? 'ready' : 'coming-soon'}" data-template-id="${template.id}">
                <div class="vmo-template-image">
                    <img src="${template.preview}" alt="${template.name}" onerror="this.src='data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzAwIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMzAwIiBoZWlnaHQ9IjIwMCIgZmlsbD0iI2Y4ZjlmYSIvPjx0ZXh0IHg9IjUwJSIgeT0iNTAlIiBmb250LWZhbWlseT0ic2Fucy1zZXJpZiIgZm9udC1zaXplPSIxNCIgZmlsbD0iIzk5YTNhZiIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZHk9Ii4zZW0iPk5vIEltYWdlPC90ZXh0Pjwvc3ZnPg=='">
                    ${statusBadge}
                    ${template.ready ? `
                        <div class="vmo-template-overlay">
                            <button class="vmo-template-preview-btn" onclick="VMOTemplates.previewTemplate('${template.id}')">
                                👁️ Preview Template
                            </button>
                        </div>
                    ` : ''}
                </div>
                <div class="vmo-template-content">
                    <h3 class="vmo-template-title">${template.name}</h3>
                    <p class="vmo-template-description">${template.description}</p>
                    <div class="vmo-template-features">
                        ${featuresHtml}
                    </div>
                    <div class="vmo-template-actions">
                        ${template.ready ? `
                            <button class="vmo-template-btn vmo-template-btn-primary" onclick="VMOTemplates.useTemplate('${template.id}')">
                                🚀 Use Template
                            </button>
                            <button class="vmo-template-btn vmo-template-btn-secondary" onclick="VMOTemplates.previewTemplate('${template.id}')">
                                👁️ Preview
                            </button>
                        ` : `
                            <button class="vmo-template-btn vmo-template-btn-disabled" disabled>
                                ⏳ Coming Soon
                            </button>
                        `}
                    </div>
                </div>
            </div>
        `;
    }
    
    // Close template modal
    function closeTemplateModal() {
        console.log('🎨 Closing template modal');
        const modal = document.getElementById('vmo-template-modal');
        if (modal) {
            modal.style.display = 'none';
        }
    }
    
    // Show all templates
    function showAllTemplates() {
        console.log('🎨 Showing all templates');
        const templatesContainer = document.getElementById('vmo-templates-container');
        if (!templatesContainer) return;
        
        if (typeof VMOTemplates !== 'undefined') {
            const allTemplates = VMOTemplates.getAllTemplates();
            displayTemplateGrid(allTemplates, templatesContainer);
        }
    }
    
    // Show templates for specific category
    function showTemplatesForCategory(category) {
        console.log('🎨 Showing templates for category:', category);
        const templatesContainer = document.getElementById('vmo-templates-container');
        if (!templatesContainer) return;
        
        if (typeof VMOTemplates !== 'undefined') {
            const categoryTemplates = VMOTemplates.getTemplatesByCategory(category);
            displayTemplateGrid(categoryTemplates, templatesContainer, category);
        }
    }
    
    // Display template grid
    function displayTemplateGrid(templates, container, category = 'all') {
        if (!templates || templates.length === 0) {
            container.innerHTML = `
                <div class="vmo-no-templates">
                    <h3>No ${category === 'all' ? '' : category} templates available yet</h3>
                    <p>More templates coming soon!</p>
                </div>
            `;
            return;
        }
        
        let html = '<div class="vmo-templates-grid">';
        
        templates.forEach(template => {
            const statusBadge = template.ready ? 
                '<div class="vmo-template-status ready">✅ Ready</div>' : 
                '<div class="vmo-template-status coming">🚧 Coming Soon</div>';
            
            const featuresHtml = template.features.map(feature => 
                `<span class="vmo-template-feature">${feature}</span>`
            ).join('');
            
            html += `
                <div class="vmo-template-card ${template.ready ? 'ready' : 'coming-soon'}" data-template-id="${template.id}">
                    <div class="vmo-template-image">
                        <img src="${template.preview}" alt="${template.name}" 
                             onerror="this.src='data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzAwIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMzAwIiBoZWlnaHQ9IjIwMCIgZmlsbD0iI2Y4ZjlmYSIvPjx0ZXh0IHg9IjUwJSIgeT0iNTAlIiBmb250LWZhbWlseT0ic2Fucy1zZXJpZiIgZm9udC1zaXplPSIxNCIgZmlsbD0iIzk5YTNhZiIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZHk9Ii4zZW0iPk5vIEltYWdlPC90ZXh0Pjwvc3ZnPg=='">
                        ${statusBadge}
                        ${template.ready ? `
                            <div class="vmo-template-overlay">
                                <button class="vmo-template-preview-btn" onclick="VMOTemplates.previewTemplate('${template.id}')">
                                    👁️ Preview Template
                                </button>
                            </div>
                        ` : ''}
                    </div>
                    <div class="vmo-template-info">
                        <h4>${template.name}</h4>
                        <p>${template.description}</p>
                        <div class="vmo-template-features">
                            ${featuresHtml}
                        </div>
                        ${template.ready ? `
                            <div class="vmo-template-actions">
                                <button class="vmo-template-btn vmo-template-btn-primary" onclick="VMOTemplates.useTemplate('${template.id}')">
                                    ✨ Use Template
                                </button>
                                <button class="vmo-template-btn vmo-template-btn-secondary" onclick="VMOTemplates.previewTemplate('${template.id}')">
                                    👁️ Preview
                                </button>
                            </div>
                        ` : `
                            <div class="vmo-template-actions">
                                <button class="vmo-template-btn vmo-template-btn-disabled" disabled>
                                    🚧 Coming Soon
                                </button>
                            </div>
                        `}
                    </div>
                </div>
            `;
        });
        
        html += '</div>';
        container.innerHTML = html;
        
        // Add animation to template cards
        setTimeout(() => {
            const cards = container.querySelectorAll('.vmo-template-card');
            cards.forEach((card, index) => {
                card.style.opacity = '0';
                card.style.transform = 'translateY(20px)';
                setTimeout(() => {
                    card.style.transition = 'all 0.3s ease';
                    card.style.opacity = '1';
                    card.style.transform = 'translateY(0)';
                }, index * 100);
            });
        }, 50);
    }
    
    // Make functions global
    window.openTemplateModal = openTemplateModal;
    window.closeTemplateModal = closeTemplateModal;
    window.vmoOpenTemplateModal = openTemplateModal;
    window.vmoCloseTemplateModal = closeTemplateModal;
    window.vmoShowAllTemplates = showAllTemplates;
    window.vmoShowTemplatesForCategory = showTemplatesForCategory;
    window.showAllTemplates = showAllTemplates;
    window.showTemplatesForCategory = showTemplatesForCategory;
    
    console.log('🔗 VMO Template Integration Loaded');
    
})(typeof jQuery !== 'undefined' ? jQuery : function() { console.warn('jQuery not available'); });
