jQuery(document).ready(function($) {
    
    // Load static categories only
    buildCategoryMenu([]);
    
    // Load templates
    loadTemplatesByType('templates');
    
    // Tab switching (for future use when more tabs are added)
    $('.tab-btn').on('click', function() {
        var type = $(this).data('type');
        $('.tab-btn').removeClass('active');
        $(this).addClass('active');
        loadTemplatesByType(type);
    });
    
    // Dismiss AI notice
    $('.dismiss-notice').on('click', function() {
        $('.turbo-ai-notice').slideUp();
    });
    
    // Search functionality
    $('#template-search').on('input', function() {
        var searchTerm = $(this).val().toLowerCase();
        filterTemplates(searchTerm);
    });
    
    // Sort functionality
    $('#template-sort').on('change', function() {
        var sortBy = $(this).val();
        var activeType = $('.tab-btn.active').data('type') || 'templates';
        loadTemplatesByType(activeType, sortBy);
    });
    
    // Category filtering (using event delegation for dynamically added items)
    $(document).on('click', '.menu-item > a', function(e) {
        e.preventDefault();
        
        var $menuItem = $(this).parent();
        var category = $menuItem.data('category');
        
        $('.menu-item').removeClass('active');
        $menuItem.addClass('active');
        
        filterByCategory(category);
    });
    
    // Subcategory filtering (using event delegation)
    $(document).on('click', '.submenu-item > a', function(e) {
        e.preventDefault();
        
        var $submenuItem = $(this).parent();
        var category = $submenuItem.data('category');
        
        $('.menu-item, .submenu-item').removeClass('active');
        $submenuItem.addClass('active');
        
        filterByCategory(category);
    });
    
    // Universal import handler
    $(document).on('click', '.import-btn, .import-pack-btn, .import-block-btn', function() {
        var $btn = $(this);
        var itemId = $btn.data('template-id') || $btn.data('pack-id') || $btn.data('block-id');
        var $card = $btn.closest('.template-card, .template-pack-card, .template-block-card');
        var itemName = $card.find('h3').text();
        var itemImage = $card.find('img').attr('src');
        
        // Determine type based on button class
        var type = 'template';
        if ($btn.hasClass('import-pack-btn')) type = 'pack';
        if ($btn.hasClass('import-block-btn')) type = 'block';
        
        showImportWizard(itemId, itemName, itemImage, type);
    });
    
    // Wizard navigation
    $('#continue-step-2').on('click', function() {
        showWizardStep(2);
    });
    
    $('#continue-step-3').on('click', function() {
        showWizardStep(3);
    });
    
    $('#submit-build').on('click', function() {
        if ($('#understand-terms').is(':checked')) {
            showWizardStep(4);
            startImport();
        }
    });
    
    // Advanced options toggle
    $('.toggle-advanced').on('click', function() {
        $('.advanced-content').slideToggle();
    });
    
    // Form validation
    $('#understand-terms').on('change', function() {
        $('#submit-build').prop('disabled', !$(this).is(':checked'));
    });
    
    // Feature selection
    $('.feature-item input').on('change', function() {
        updatePluginList();
        updateFeatureStyles();
    });
    
    // Color scheme selection
    $('.color-option input').on('change', function() {
        var selectedColor = $(this).val();
        
        $('.color-option').removeClass('active');
        $(this).closest('.color-option').addClass('active');
        
        // Apply color change to preview
        applyColorChange(selectedColor);
    });
    
    // Font weight tab selection
    $(document).on('click', '.weight-tab', function() {
        $('.weight-tab').removeClass('active');
        $(this).addClass('active');
        
        // Apply font weight change while preserving colors
        applyFontChange();
    });
    
    // Store current customizations
    var currentCustomizations = {
        colors: 'default',
        fonts: 'default'
    };
    
    /**
     * Apply color change to preview
     */
    function applyColorChange(colorScheme) {
        // Update stored color customization
        currentCustomizations.colors = colorScheme;
        
        // Apply color changes to preview template
        applyPreviewCustomizations();
    }
    
    /**
     * Apply font change while preserving colors
     */
    function applyFontChange() {
        var selectedWeight = $('.weight-tab.active').data('weight') || '400';
        
        // Update stored font customization (colors remain unchanged)
        currentCustomizations.fontWeight = selectedWeight;
        
        // Apply font changes to preview template without affecting colors
        applyPreviewCustomizations();
    }
    
    /**
     * Apply customizations to preview template
     */
    function applyPreviewCustomizations() {
        // Send message to preview iframe if it exists
        var previewFrame = document.getElementById('template-preview-frame');
        if (previewFrame && previewFrame.contentWindow) {
            previewFrame.contentWindow.postMessage({
                type: 'applyCustomizations',
                data: currentCustomizations
            }, '*');
        }
        
        // Log current customizations for debugging
        console.log('Applied customizations:', currentCustomizations);
    }
    

    
    // Modal close
    $('.turbo-modal-close, .turbo-modal').on('click', function(e) {
        if (e.target === this) {
            $('.turbo-modal').hide();
        }
    });
    
    // Prevent modal content clicks from closing modal
    $('.turbo-modal-content').on('click', function(e) {
        e.stopPropagation();
    });
    
    /**
     * Load categories from API
     */
    function loadCategories() {
        $.ajax({
            url: turboAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'turbo_get_categories',
                nonce: turboAdmin.nonce
            },
            success: function(response) {
                if (response.success && response.data && response.data.length > 0) {
                    buildCategoryMenu(response.data);
                }
                // Don't replace static menu if API returns empty data
            }
        });
    }
    
    /**
     * Build category menu from API data or fallback to static structure
     */
    function buildCategoryMenu(categories) {
        var $menu = $('#category-menu');
        
        // Static fallback menu structure
        var staticCategories = [
            {
                name: 'Business',
                slug: 'business',
                subcategories: [
                    { name: 'Landing Page', slug: 'landing-page' },
                    { name: 'Portfolio', slug: 'portfolio' },
                    { name: 'Blog', slug: 'blog' },
                    { name: 'E-commerce', slug: 'e-commerce' },
                    { name: 'Agency', slug: 'agency' },
                    { name: 'Creative', slug: 'creative' },
                    { name: 'Education', slug: 'education' },
                    { name: 'Corporate', slug: 'corporate' },
                    { name: 'Consulting', slug: 'consulting' },
                    { name: 'Finance', slug: 'finance' },
                    { name: 'Marketing', slug: 'marketing' },
                    { name: 'Startup', slug: 'startup' },
                    { name: 'Software Company', slug: 'software-company' },
                    { name: 'IT Solutions', slug: 'it-solutions' },
                    { name: 'Real Estate', slug: 'real-estate' },
                    { name: 'Architecture', slug: 'architecture' },
                    { name: 'Construction', slug: 'construction' }
                ]
            },
            {
                name: 'Local Business',
                slug: 'local-business',
                subcategories: [
                    { name: 'Restaurant', slug: 'restaurant' },
                    { name: 'Cafe', slug: 'cafe' },
                    { name: 'Salon', slug: 'salon' },
                    { name: 'Dental Clinic', slug: 'dental-clinic' },
                    { name: 'Gym / Fitness Center', slug: 'gym-fitness' },
                    { name: 'Spa & Wellness', slug: 'spa-wellness' },
                    { name: 'Cleaning Services', slug: 'cleaning-services' },
                    { name: 'Plumbing / Repair', slug: 'plumbing-repair' },
                    { name: 'Pet Care', slug: 'pet-care' },
                    { name: 'Travel Agency', slug: 'travel-agency' }
                ]
            },
            {
                name: 'Professional',
                slug: 'professional',
                subcategories: [
                    { name: 'Doctor / Medical', slug: 'doctor-medical' },
                    { name: 'Lawyer', slug: 'lawyer' },
                    { name: 'Accountant', slug: 'accountant' },
                    { name: 'Coach / Mentor', slug: 'coach-mentor' },
                    { name: 'Therapist', slug: 'therapist' },
                    { name: 'Teacher / Tutor', slug: 'teacher-tutor' },
                    { name: 'Designer', slug: 'designer' },
                    { name: 'Developer', slug: 'developer' }
                ]
            },
            {
                name: 'Personal',
                slug: 'personal',
                subcategories: [
                    { name: 'Freelancer', slug: 'freelancer' },
                    { name: 'Photographer', slug: 'photographer' },
                    { name: 'Artist', slug: 'artist' },
                    { name: 'Writer', slug: 'writer' },
                    { name: 'Speaker', slug: 'speaker' },
                    { name: 'Resume / CV', slug: 'resume-cv' },
                    { name: 'Personal Site', slug: 'personal-site' },
                    { name: 'Influencer Page', slug: 'influencer-page' },
                    { name: 'Bio / Link Page', slug: 'bio-link-page' },
                    { name: 'Single Page Resume', slug: 'single-page-resume' },
                    { name: 'Author / Blogger', slug: 'author-blogger' }
                ]
            },
            {
                name: 'Community',
                slug: 'community',
                subcategories: [
                    { name: 'Non-Profit', slug: 'non-profit' },
                    { name: 'Charity', slug: 'charity' },
                    { name: 'Church / Religious', slug: 'church-religious' },
                    { name: 'School / College', slug: 'school-college' },
                    { name: 'Event / Meetup', slug: 'event-meetup' },
                    { name: 'Online Course', slug: 'online-course' },
                    { name: 'Organization', slug: 'organization' },
                    { name: 'Club / Society', slug: 'club-society' }
                ]
            },
            {
                name: 'E-commerce',
                slug: 'ecommerce',
                subcategories: [
                    { name: 'Clothing Store', slug: 'clothing-store' },
                    { name: 'Furniture Shop', slug: 'furniture-shop' },
                    { name: 'Electronics', slug: 'electronics' },
                    { name: 'Jewelry', slug: 'jewelry' },
                    { name: 'Grocery / Organic Shop', slug: 'grocery-organic' },
                    { name: 'Books / Stationery', slug: 'books-stationery' },
                    { name: 'Gift Store', slug: 'gift-store' },
                    { name: 'Beauty Products', slug: 'beauty-products' }
                ]
            },
            {
                name: 'Lifestyle',
                slug: 'lifestyle',
                subcategories: [
                    { name: 'Travel', slug: 'travel' },
                    { name: 'Food', slug: 'food' },
                    { name: 'Fitness', slug: 'fitness' },
                    { name: 'Technology', slug: 'technology' },
                    { name: 'Fashion', slug: 'fashion' },
                    { name: 'Photography', slug: 'photography' },
                    { name: 'Parenting', slug: 'parenting' },
                    { name: 'Business Tips', slug: 'business-tips' }
                ]
            }
        ];
        
        // Use API categories if available, otherwise use static fallback
        var menuCategories = (categories && categories.length > 0) ? categories : staticCategories;
        
        // Clear existing categories except "All"
        var $allItem = $('#category-menu .menu-item').first();
        $('#category-menu').empty().append($allItem);
        
        // Add categories after the "All" item
        menuCategories.forEach(function(category) {
            var hasSubcategories = category.subcategories && category.subcategories.length > 0;
            var menuClass = hasSubcategories ? 'menu-item has-submenu' : 'menu-item';
            
            var $menuItem = $('<li class="' + menuClass + '" data-category="' + category.slug + '">');
            $menuItem.append('<a href="#">' + category.name + '</a>');
            
            if (hasSubcategories) {
                var $submenu = $('<ul class="submenu">');
                category.subcategories.forEach(function(sub) {
                    $submenu.append('<li class="submenu-item" data-category="' + sub.slug + '"><a href="#">' + sub.name + '</a></li>');
                });
                $menuItem.append($submenu);
            }
            
            $menu.append($menuItem);
        });
    }
    
    /**
     * Load templates by type
     */
    function loadTemplatesByType(type, sortBy) {
        $('#templates-loading').show();
        $('#template-grid').hide();
        $('#no-templates').hide();
        
        var actionMap = {
            'templates': 'turbo_templates_list',
            'packs': 'turbo_template_packs_list', 
            'blocks': 'turbo_template_blocks_list',
            'sections': 'turbo_template_blocks_list'
        };
        
        sortBy = sortBy || $('#template-sort').val() || 'newest';
        
        $.ajax({
            url: turboAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: actionMap[type],
                sort_by: sortBy,
                nonce: turboAdmin.nonce
            },
            success: function(response) {
                $('#templates-loading').hide();
                
                if (response.success && response.data.html) {
                    $('#template-grid').html(response.data.html).show();
                    // Apply current search filter if any
                    var searchTerm = $('#template-search').val();
                    if (searchTerm) {
                        filterTemplates(searchTerm.toLowerCase());
                    }
                } else {
                    $('#no-templates').show();
                }
            },
            error: function() {
                $('#templates-loading').hide();
                $('#no-templates').show();
            }
        });
    }
    
    /**
     * Sort templates
     */
    function sortTemplates(sortBy) {
        var $cards = $('.template-card, .template-pack-card, .template-block-card');
        var $container = $('#template-grid');
        
        var sortedCards = $cards.sort(function(a, b) {
            var $a = $(a), $b = $(b);
            
            switch(sortBy) {
                case 'popular':
                    var aDownloads = parseInt($a.find('.template-downloads').text().replace(/[^0-9]/g, '')) || 0;
                    var bDownloads = parseInt($b.find('.template-downloads').text().replace(/[^0-9]/g, '')) || 0;
                    return bDownloads - aDownloads;
                    
                case 'name':
                    var aName = $a.find('h3').text().toLowerCase();
                    var bName = $b.find('h3').text().toLowerCase();
                    return aName.localeCompare(bName);
                    
                case 'trending':
                case 'newest':
                default:
                    return 0; // Keep original order for now
            }
        });
        
        $container.html(sortedCards);
    }
    
    /**
     * Filter templates by search term
     */
    function filterTemplates(searchTerm) {
        $('.template-card, .template-pack-card, .template-block-card').each(function() {
            var $card = $(this);
            var title = $card.find('h3').text().toLowerCase();
            var description = $card.find('.pack-description, .template-meta, .block-meta').text().toLowerCase();
            
            if (title.includes(searchTerm) || description.includes(searchTerm)) {
                $card.show();
            } else {
                $card.hide();
            }
        });
        
        checkNoResults();
    }
    
    /**
     * Filter templates by category
     */
    function filterByCategory(category) {
        if (!category) {
            $('.template-card, .template-pack-card, .template-block-card').show();
        } else {
            $('.template-card, .template-pack-card, .template-block-card').each(function() {
                var $card = $(this);
                var cardCategory = $card.data('category');
                
                if (cardCategory === category) {
                    $card.show();
                } else {
                    $card.hide();
                }
            });
        }
        
        checkNoResults();
    }
    
    /**
     * Check if no results and show message
     */
    function checkNoResults() {
        var visibleCards = $('.template-card:visible, .template-pack-card:visible, .template-block-card:visible').length;
        
        if (visibleCards === 0) {
            $('#no-templates').show();
            $('#template-grid').hide();
        } else {
            $('#no-templates').hide();
            $('#template-grid').show();
        }
    }
    
    /**
     * Show import wizard
     */
    function showImportWizard(itemId, templateName, templateImage, type) {
        // Set template info
        $('#selected-template-name').text(templateName);
        $('#selected-template-preview').attr('src', templateImage);
        
        // Store item ID and type for later use
        $('#import-modal').data('item-id', itemId);
        $('#import-modal').data('import-type', type || 'template');
        
        // Reset wizard
        showWizardStep(1);
        updatePluginList();
        updateFeatureStyles();
        
        // Show modal
        $('#import-modal').show();
    }
    
    /**
     * Show wizard step
     */
    function showWizardStep(step) {
        $('.wizard-step').removeClass('active');
        $('#wizard-step-' + step).addClass('active');
    }
    
    /**
     * Update plugin list based on selected features
     */
    function updatePluginList() {
        var plugins = [
            '<li><strong>Elementor</strong> <span class="required">*</span></li>',
            '<li><strong>Turbo Addons</strong> <span class="required">*</span></li>'
        ];
        
        $('.feature-item input:checked').each(function() {
            var feature = $(this).val();
            
            switch(feature) {
                case 'contact_form':
                    plugins.push('<li><strong>Contact Form 7</strong></li>');
                    break;
                case 'ecommerce':
                    plugins.push('<li><strong>WooCommerce</strong></li>');
                    break;
                case 'seo':
                    plugins.push('<li><strong>Yoast SEO</strong></li>');
                    break;
                case 'bookings':
                    plugins.push('<li><strong>Booking Calendar</strong></li>');
                    break;
                case 'email':
                    plugins.push('<li><strong>WP Mail SMTP</strong></li>');
                    break;
            }
        });
        
        $('#selected-plugins').html(plugins.join(''));
    }
    
    /**
     * Update feature item styles
     */
    function updateFeatureStyles() {
        $('.feature-item').each(function() {
            var $item = $(this);
            var $checkbox = $item.find('input');
            var $content = $item.find('.feature-content');
            
            if ($checkbox.is(':checked')) {
                $item.css('border-color', '#667eea');
                $content.css('opacity', '1');
            } else {
                $item.css('border-color', '#eee');
                $content.css('opacity', '0.7');
            }
        });
    }
    
    /**
     * Start import process
     */
    function startImport() {
        var packId = $('#import-modal').data('pack-id');
        var selectedFeatures = [];
        var colorScheme = $('input[name="color_scheme"]:checked').val();
        
        $('.feature-item input:checked').each(function() {
            selectedFeatures.push($(this).val());
        });
        
        // Start actual import process
        var itemId = $('#import-modal').data('item-id');
        performActualImport(itemId, selectedFeatures, colorScheme);
    }
    
    /**
     * Perform actual import process
     */
    function performActualImport(itemId, selectedFeatures, colorScheme, fontScheme) {
        var startTime = Date.now();
        var importType = $('#import-modal').data('import-type') || 'template';
        
        updateCurrentStep(1, 'Preparing import');
        updateLogItem('plugins', 'active');
        updateCurrentAction('Getting template requirements...');
        updateProgress(5);
        
        // Determine action based on import type
        var actionMap = {
            'template': 'turbo_template_import',
            'pack': 'turbo_import_template_pack', 
            'block': 'turbo_template_block_import'
        };
        var dataKeyMap = {
            'template': 'template_id',
            'pack': 'pack_id',
            'block': 'block_id'
        };
        
        var action = actionMap[importType] || 'turbo_template_import';
        var dataKey = dataKeyMap[importType] || 'template_id';
        
        var requestData = {
            action: action,
            features: selectedFeatures,
            color_scheme: colorScheme,
            font_scheme: fontScheme || 'default',
            nonce: turboAdmin.nonce
        };
        requestData[dataKey] = itemId;
        
        // Start actual import via AJAX
        $.ajax({
            url: turboAdmin.ajaxUrl,
            type: 'POST',
            data: requestData,
            success: function(response) {
                if (response.success) {
                    updateProgress(100);
                    updateLogItem('plugins', 'completed');
                    updateLogItem('content', 'completed');
                    updateLogItem('customizer', 'completed');
                    updateLogItem('complete', 'active');
                    updateCurrentAction('Website setup complete!');
                    
                    // Calculate build time
                    var buildTime = Math.round((Date.now() - startTime) / 1000);
                    $('#build-time').text(buildTime);
                    
                    // Setup Twitter share
                    var tweetText = encodeURIComponent('I just built my website with Starter Templates by @TurboWP in minutes. Can\'t believe how easy it is! 😍');
                    $('#tweet-btn').attr('href', 'https://twitter.com/intent/tweet?text=' + tweetText);
                    
                    showWizardStep(5);
                    
                    // Set proper redirect URL
                    var siteUrl = response.data.homepage_url || response.data.preview_url || window.location.origin;
                    $('#view-site-btn').attr('href', siteUrl);
                    
                    // Auto-redirect after 3 seconds
                    setTimeout(function() {
                        window.location.href = siteUrl;
                    }, 3000);
                } else {
                    updateCurrentAction('Import failed: ' + (response.data || 'Unknown error'));
                }
            },
            error: function() {
                updateCurrentAction('Import failed: Network error');
            }
        });
    }
    

    
    /**
     * Legacy simulation function (kept for fallback)
     */
    function simulateDetailedProgress() {
        var progress = 0;
        var step = 1;
        var startTime = Date.now();
        
        var plugins = [
            'Elementor',
            'Contact Form 7', 
            'WooCommerce',
            'Yoast SEO',
            'Ultimate Addons for Elementor Lite'
        ];
        
        var pluginIndex = 0;
        
        // Step 1: Install plugins (0-60%)
        updateCurrentStep(1, 'Installing plugins');
        updateLogItem('plugins', 'active');
        
        var pluginInterval = setInterval(function() {
            if (pluginIndex < plugins.length) {
                updateCurrentAction('Installing ' + plugins[pluginIndex] + ' plugin.');
                progress += 12;
                updateProgress(progress);
                pluginIndex++;
            } else {
                clearInterval(pluginInterval);
                updateLogItem('plugins', 'completed');
                
                // Step 2: Import content (60-85%)
                setTimeout(function() {
                    updateCurrentStep(2, 'Importing pages, menus, posts, etc');
                    updateLogItem('content', 'active');
                    
                    var contentSteps = [
                        'Importing pages and posts',
                        'Setting up navigation menus', 
                        'Importing media files',
                        'Configuring widgets'
                    ];
                    
                    var contentIndex = 0;
                    var contentInterval = setInterval(function() {
                        if (contentIndex < contentSteps.length) {
                            updateCurrentAction(contentSteps[contentIndex] + '.');
                            progress += 6;
                            updateProgress(progress);
                            contentIndex++;
                        } else {
                            clearInterval(contentInterval);
                            updateLogItem('content', 'completed');
                            
                            // Step 3: Apply settings (85-100%)
                            setTimeout(function() {
                                updateCurrentStep(3, 'Applying customizer settings');
                                updateLogItem('customizer', 'active');
                                updateCurrentAction('Applying theme customizations.');
                                
                                var settingsInterval = setInterval(function() {
                                    progress += 3;
                                    updateProgress(Math.min(progress, 100));
                                    
                                    if (progress >= 100) {
                                        clearInterval(settingsInterval);
                                        updateLogItem('customizer', 'completed');
                                        updateLogItem('complete', 'active');
                                        updateCurrentAction('Website setup complete!');
                                        
                                        setTimeout(function() {
                                            // Calculate build time
                                            var buildTime = Math.round((Date.now() - startTime) / 1000);
                                            $('#build-time').text(buildTime);
                                            
                                            // Setup Twitter share
                                            var tweetText = encodeURIComponent('I just built my website with Starter Templates by @TurboWP in minutes. Can\'t believe how easy it is! 😍');
                                            $('#tweet-btn').attr('href', 'https://twitter.com/intent/tweet?text=' + tweetText);
                                            
                                            showWizardStep(5);
                                            $('#view-site-btn').attr('href', window.location.origin);
                                            
                                            // Auto-redirect to homepage
                                            setTimeout(function() {
                                                window.location.href = window.location.origin;
                                            }, 3000);
                                        }, 1000);
                                    }
                                }, 200);
                            }, 1000);
                        }
                    }, 1500);
                }, 1000);
            }
        }, 2000);
    }
    
    /**
     * Update current step display
     */
    function updateCurrentStep(stepNum, description) {
        $('.current-step').html('<span class="step-number">' + stepNum + '.</span> <span class="step-description">' + description + '</span>');
    }
    
    /**
     * Update current action message
     */
    function updateCurrentAction(message) {
        $('#current-action').text(message);
    }
    
    /**
     * Update progress percentage
     */
    function updateProgress(percentage) {
        $('.progress-percentage').text(Math.round(percentage) + '%');
    }
    
    /**
     * Update log item status
     */
    function updateLogItem(itemId, status) {
        var $item = $('#log-' + itemId);
        $item.removeClass('active completed').addClass(status);
        
        if (status === 'completed') {
            $item.find('.log-icon').text('✓');
        } else if (status === 'active') {
            $item.find('.log-icon').text('•');
        }
    }
    

    

    
});
