jQuery(function ($) {
    const wizard = {
        categories: [],
        categoryTree: [],
        features: [],
        featureValues: [],
        products: [],
        currentStep: 1,
        processing: false,
        completedSteps: []
    };

    function showStep(stepNumber) {
        $('.step').removeClass('active');
        $(`.step[data-tab="${stepNumber}"]`).addClass('active');
        
        $('.wizard-tab').removeClass('active');
        $(`.wizard-tab[data-tab="${stepNumber}"]`).addClass('active');
        
        wizard.currentStep = stepNumber;
    }

    function enableStep(stepNumber) {
        $(`.wizard-tab[data-tab="${stepNumber}"]`).removeClass('disabled');
    }

    function completeStep(stepNumber) {
        $(`.wizard-tab[data-tab="${stepNumber}"]`).addClass('completed');
        wizard.completedSteps.push(stepNumber);
        
        // Enable next step
        if (stepNumber < 5) {
            enableStep(stepNumber + 1);
        }
    }

    function skipStep(step) {
        const stepEl = $(`.step[data-step="${step}"]`);
        const stepNumber = stepEl.data('tab');
        const statusEl = stepEl.find('.step-status');
        
        statusEl.removeClass('step-pending step-success step-error');
        statusEl.addClass('step-pending').html('⏭ Skipped');
        
        // Mark as completed (skipped) and enable next step
        completeStep(stepNumber);
        
        // Check if all 5 steps are completed
        if (wizard.completedSteps.length >= 5) {
            markWizardCompleted();
        } else {
            // Auto-advance to next step
            if (stepNumber < 5) {
                setTimeout(() => {
                    showStep(stepNumber + 1);
                }, 500);
            }
        }
    }

    function loadData() {
        // Load categories
        $.ajax({
            url: ajax_object.ajax_url,
            method: 'POST',
            data: {
                action: 'taamito_get_categories'
            },
            success: function(response) {
                if (response.success) {
                    wizard.categories = response.data || [];
                    renderCategories();
                } else {
                    $('#categories-list').html('<div class="step-item"><span class="item-name">Error loading categories</span></div>');
                }
            },
            error: function() {
                $('#categories-list').html('<div class="step-item"><span class="item-name">Error loading categories</span></div>');
            }
        });

        // Load category tree
        $.ajax({
            url: ajax_object.ajax_url,
            method: 'POST',
            data: {
                action: 'taamito_get_category_tree'
            },
            success: function(response) {
                if (response.success) {
                    wizard.categoryTree = response.data || [];
                    renderCategoryTree();
                } else {
                    $('#category-tree-list').html('<div class="step-item"><span class="item-name">Error loading category tree</span></div>');
                }
            },
            error: function() {
                $('#category-tree-list').html('<div class="step-item"><span class="item-name">Error loading category tree</span></div>');
            }
        });

        // Load features
        $.ajax({
            url: ajax_object.ajax_url,
            method: 'POST',
            data: {
                action: 'taamito_get_features'
            },
            success: function(response) {
                if (response.success) {
                    wizard.features = response.data || [];
                    renderFeatures();
                } else {
                    $('#features-list').html('<div class="step-item"><span class="item-name">Error loading features</span></div>');
                }
            },
            error: function() {
                $('#features-list').html('<div class="step-item"><span class="item-name">Error loading features</span></div>');
            }
        });

        // Load feature values
        $.ajax({
            url: ajax_object.ajax_url,
            method: 'POST',
            data: {
                action: 'taamito_get_feature_values'
            },
            success: function(response) {
                if (response.success) {
                    wizard.featureValues = response.data || [];
                    renderFeatureValues();
                } else {
                    $('#feature-values-list').html('<div class="step-item"><span class="item-name">Error loading feature values</span></div>');
                }
            },
            error: function() {
                $('#feature-values-list').html('<div class="step-item"><span class="item-name">Error loading feature values</span></div>');
            }
        });

        // Load products
        $.ajax({
            url: ajax_object.ajax_url,
            method: 'POST',
            data: {
                action: 'taamito_get_products'
            },
            success: function(response) {
                if (response.success) {
                    wizard.products = response.data || [];
                    renderProducts();
                } else {
                    $('#products-list').html('<div class="step-item"><span class="item-name">Error loading products</span></div>');
                }
            },
            error: function() {
                $('#products-list').html('<div class="step-item"><span class="item-name">Error loading products</span></div>');
            }
        });
    }

    function renderCategories() {
        const container = $('#categories-list');
        container.empty();
        if (wizard.categories.length === 0) {
            container.html('<div class="step-item"><span class="item-name">No categories found</span></div>');
            return;
        }
        wizard.categories.forEach(cat => {
            const item = $(`
                <div class="step-item" data-id="${cat.id}">
                    <span class="item-name">${cat.name}</span>
                    <span class="item-status"></span>
                </div>
            `);
            container.append(item);
        });
    }

    function renderCategoryTree() {
        const container = $('#category-tree-list');
        container.empty();
        if (wizard.categoryTree.length === 0) {
            container.html('<div class="step-item"><span class="item-name">No child categories found. You can skip this step.</span></div>');
            $('.btn-skip-step[data-step="category-tree"]').focus();
            return;
        }
        wizard.categoryTree.forEach(cat => {
            const item = $(`
                <div class="step-item" data-id="${cat.id}" data-parent="${cat.parent || ''}">
                    <span class="item-name">${cat.name} ${cat.parent ? '(Parent: ' + cat.parent_name + ')' : ''}</span>
                    <span class="item-status"></span>
                </div>
            `);
            container.append(item);
        });
    }

    function renderFeatures() {
        const container = $('#features-list');
        container.empty();
        if (wizard.features.length === 0) {
            container.html('<div class="step-item"><span class="item-name">No features found</span></div>');
            return;
        }
        wizard.features.forEach(feature => {
            const item = $(`
                <div class="step-item" data-id="${feature.id}">
                    <span class="item-name">${feature.name} (Type: ${feature.type_name})</span>
                    <span class="item-status"></span>
                </div>
            `);
            container.append(item);
        });
    }

    function renderFeatureValues() {
        const container = $('#feature-values-list');
        container.empty();
        if (wizard.featureValues.length === 0) {
            container.html('<div class="step-item"><span class="item-name">No feature values found</span></div>');
            return;
        }
        wizard.featureValues.forEach(fv => {
            const item = $(`
                <div class="step-item" data-feature-id="${fv.feature_id}" data-term-id="${fv.term_id}">
                    <span class="item-name">${fv.name} (Feature: ${fv.feature_name})</span>
                    <span class="item-status"></span>
                </div>
            `);
            container.append(item);
        });
    }

    function renderProducts() {
        const container = $('#products-list');
        container.empty();
        if (wizard.products.length === 0) {
            container.html('<div class="step-item"><span class="item-name">No products found</span></div>');
            return;
        }
        wizard.products.forEach(product => {
            const item = $(`
                <div class="step-item" data-id="${product.id}">
                    <span class="item-name">${product.name}</span>
                    <span class="item-status"></span>
                </div>
            `);
            container.append(item);
        });
    }

    function updateItemStatus(item, success, message) {
        const statusEl = item.find('.item-status');
        statusEl.removeClass('status-pending status-success status-error');
        if (success) {
            statusEl.addClass('status-success').html('✓');
        } else {
            statusEl.addClass('status-error').html('✗');
            showError(message);
        }
    }

    function updateStepStatus(step, allSuccess) {
        const stepEl = $(`.step[data-step="${step}"]`);
        const statusEl = stepEl.find('.step-status');
        statusEl.removeClass('step-pending step-success step-error');
        
        const stepNumber = stepEl.data('tab');
        
        if (allSuccess) {
            statusEl.addClass('step-success').html('✓ Complete');
            completeStep(stepNumber);
            
            // Check if all 5 steps are completed
            if (wizard.completedSteps.length >= 5) {
                markWizardCompleted();
            } else {
                // Auto-advance to next step if all succeeded
                if (stepNumber < 5) {
                    setTimeout(() => {
                        showStep(stepNumber + 1);
                    }, 1000);
                }
            }
        } else {
            statusEl.addClass('step-error').html('✗ Errors');
        }
    }

    function markWizardCompleted() {
        $.ajax({
            url: ajax_object.ajax_url,
            method: 'POST',
            data: {
                action: 'taamito_wizard_mark_completed'
            },
            success: function(response) {
                if (response.success) {
                    // Show completion message
                    const completionMsg = $('<div class="wizard-completion-message" style="background: #46b450; color: #fff; padding: 20px; border-radius: 8px; text-align: center; margin: 20px 0;"><h3>✓ Wizard Completed Successfully!</h3><p>All data has been transferred to Taamito. The wizard button will be hidden from the settings page.</p></div>');
                    $('.wizard-container').prepend(completionMsg);
                    
                    // Reload the page after 3 seconds to update the button visibility
                    setTimeout(() => {
                        window.location.reload();
                    }, 3000);
                }
            }
        });
    }

    function showError(message) {
        const errorContainer = $('#wizard-errors');
        const errorEl = $(`<div class="error-message">${message}</div>`);
        errorContainer.append(errorEl);
        setTimeout(() => errorEl.fadeOut(() => errorEl.remove()), 5000);
    }

    async function syncCategory(categoryId) {
        const item = $(`.step-item[data-id="${categoryId}"]`);
        item.find('.item-status').addClass('status-pending').html('...');

        try {
            const response = await $.post(ajax_object.ajax_url, {
                action: 'taamito_wizard_sync_category',
                category_id: categoryId
            });

            if (response.success) {
                updateItemStatus(item, true);
                return true;
            } else {
                updateItemStatus(item, false, response.data?.message || 'Sync failed');
                return false;
            }
        } catch (error) {
            updateItemStatus(item, false, error.responseJSON?.data?.message || 'Network error');
            return false;
        }
    }

    async function syncCategoryTree(categoryId, parentId) {
        const item = $(`.step-item[data-id="${categoryId}"]`);
        item.find('.item-status').addClass('status-pending').html('...');

        try {
            const response = await $.post(ajax_object.ajax_url, {
                action: 'taamito_wizard_sync_category_tree',
                category_id: categoryId,
                parent_id: parentId || null
            });

            if (response.success) {
                updateItemStatus(item, true);
                return true;
            } else {
                updateItemStatus(item, false, response.data?.message || 'Sync failed');
                return false;
            }
        } catch (error) {
            updateItemStatus(item, false, error.responseJSON?.data?.message || 'Network error');
            return false;
        }
    }

    async function syncFeature(attributeId) {
        const item = $(`.step-item[data-id="${attributeId}"]`);
        item.find('.item-status').addClass('status-pending').html('...');

        try {
            const response = await $.post(ajax_object.ajax_url, {
                action: 'taamito_wizard_sync_feature',
                attribute_id: attributeId
            });

            if (response.success) {
                updateItemStatus(item, true);
                return true;
            } else {
                updateItemStatus(item, false, response.data?.message || 'Sync failed');
                return false;
            }
        } catch (error) {
            updateItemStatus(item, false, error.responseJSON?.data?.message || 'Network error');
            return false;
        }
    }

    async function syncFeatureValue(featureId, termId) {
        const item = $(`.step-item[data-feature-id="${featureId}"][data-term-id="${termId}"]`);
        item.find('.item-status').addClass('status-pending').html('...');

        try {
            const response = await $.post(ajax_object.ajax_url, {
                action: 'taamito_wizard_sync_feature_value',
                feature_id: featureId,
                term_id: termId
            });

            if (response.success) {
                updateItemStatus(item, true);
                return true;
            } else {
                updateItemStatus(item, false, response.data?.message || 'Sync failed');
                return false;
            }
        } catch (error) {
            updateItemStatus(item, false, error.responseJSON?.data?.message || 'Network error');
            return false;
        }
    }

    async function syncProduct(productId) {
        const item = $(`.step-item[data-id="${productId}"]`);
        item.find('.item-status').addClass('status-pending').html('...');

        try {
            const response = await $.post(ajax_object.ajax_url, {
                action: 'taamito_wizard_sync_product',
                product_id: productId
            });

            if (response.success) {
                updateItemStatus(item, true);
                return true;
            } else {
                updateItemStatus(item, false, response.data?.message || 'Sync failed');
                return false;
            }
        } catch (error) {
            updateItemStatus(item, false, error.responseJSON?.data?.message || 'Network error');
            return false;
        }
    }

    async function processStep(step) {
        if (wizard.processing) return;
        wizard.processing = true;
        const btn = $(`.btn-start-step[data-step="${step}"]`);
        btn.prop('disabled', true).text('Processing...');

        let allSuccess = true;

        if (step === 'categories') {
            for (const cat of wizard.categories) {
                const success = await syncCategory(cat.id);
                if (!success) allSuccess = false;
                await new Promise(resolve => setTimeout(resolve, 500));
            }
        } else if (step === 'category-tree') {
            for (const cat of wizard.categoryTree) {
                const success = await syncCategoryTree(cat.id, cat.parent);
                if (!success) allSuccess = false;
                await new Promise(resolve => setTimeout(resolve, 500));
            }
        } else if (step === 'features') {
            for (const feature of wizard.features) {
                const success = await syncFeature(feature.id);
                if (!success) allSuccess = false;
                await new Promise(resolve => setTimeout(resolve, 500));
            }
        } else if (step === 'feature-values') {
            for (const fv of wizard.featureValues) {
                const success = await syncFeatureValue(fv.feature_id, fv.term_id);
                if (!success) allSuccess = false;
                await new Promise(resolve => setTimeout(resolve, 500));
            }
        } else if (step === 'products') {
            for (const product of wizard.products) {
                const success = await syncProduct(product.id);
                if (!success) allSuccess = false;
                await new Promise(resolve => setTimeout(resolve, 1000));
            }
        }

        updateStepStatus(step, allSuccess);
        btn.prop('disabled', false).text('Start Sync');
        wizard.processing = false;
    }

    $(document).ready(function() {
        // Initialize: show only first step, disable others
        showStep(1);
        for (let i = 2; i <= 5; i++) {
            $(`.wizard-tab[data-tab="${i}"]`).addClass('disabled');
        }

        loadData();

        // Tab click handler
        $('.wizard-tab').on('click', function() {
            if ($(this).hasClass('disabled')) {
                return;
            }
            const tabNumber = $(this).data('tab');
            showStep(tabNumber);
        });

        // Start step button handler
        $('.btn-start-step').on('click', function() {
            const step = $(this).data('step');
            processStep(step);
        });

        // Skip step button handler
        $('.btn-skip-step').on('click', function() {
            const step = $(this).data('step');
            if (confirm('Are you sure you want to skip this step?')) {
                skipStep(step);
            }
        });
    });
});

