jQuery(document).ready(function() {
    // Call wizCheckConfig with a small delay to ensure DOM is ready
    setTimeout(wizCheckConfig, 100);
    
    // Set up tab navigation
    jQuery('body').on('click', '.wizard-tab li a', function(e) {
        e.preventDefault();
        idWizardScreen(jQuery(this).attr('href'));
    });

    // Set up payment platform selection
    jQuery('body').on('click', '.payment-platform input', function(e) {
        let val = jQuery(this).val();
        if(val == 'wc') {
            if(jQuery(this).attr('notice') == 'true' && 
               !confirm(wp.i18n.__('IgnitionDeck Enterprise requires the IgnitionDeck Commerce platform. Using WooCommerce will make Enterprise functionality unavailable.', 'ignitiondeck'))) {
                jQuery('.payment-platform input[value="idc"]').prop('checked', true);
                return;
            }
        }
        wizard_action('save_payment');
    });

    // Set up modal event handlers
    jQuery('.wiz-notice-close').on('click', wizClosePopup);
    jQuery(document).on('click.wizardmodal', function(event) {
        if (!jQuery(event.target).closest('.wiz-notice-box').length && 
            !jQuery(event.target).closest('.ign-tools_delete_sampleproject').length) {
            wizClosePopup();
        }
    });

    // Initialize to the correct tab based on hash or default to install
    idWizardScreen(window.location.hash || '#wiz-install');

    // Initialize tippy tooltips
    jQuery(document).trigger('idfInitializeTippy');
});
function idWizardScreen(id='#wiz-install') {
    // Update tab navigation
    jQuery('.wizard-tab li').removeClass('active')
        .find('a[href="'+id+'"]').parent().addClass('active');

    // Show target content
    jQuery('.wizard-tabs .wizard-tab-content').removeClass('active');
    jQuery(id).addClass('active');

    if(id=='#wiz-install') {
        checkInstallConditions();
    }
}

function checkInstallConditions() {
    jQuery('#wiz-install li').each(function() {
        if(jQuery(this).data('status')!='active') {
            jQuery('.wiz-button.install').prop('disabled',false);
            jQuery('.wiz-button.continue').prop('disabled',true);
        }
    })
}

function wizard_action(action,ele=null) {
    switch(action) {
        case 'plugin_install':
            var plugins = [];
            jQuery('.wiz-button.install').prop('disabled',true);
            var i=0;
            jQuery('ul#wiz-install li').each(function() {
                if( jQuery(this).data('status') !== 'active' ) {
                    plugins.push(i);
                }
                i++;
            });
            i=0;
            plugin_install(i, plugins);
            break;
        case 'verify_license':
            jQuery(ele).html('Validating<em></em>');
            var data = {
                action: 'idf_wizard_verify_license',
                license: jQuery(ele).parent().find('.wiz-control-inline').val(),
                _wpnonce: idfWizardParams.nonce,
            };

            // First AJAX request
            jQuery.post(idfWizardParams.ajaxUrl, data, function(response) {
                var content = jQuery(response).filter("#license-details");
                var filtered = content.contents();
                jQuery('#license-details').html(filtered);

                var content = jQuery(response).filter("#configure-details");
                var filtered = content.contents();
                // jQuery('#configure-details').html(filtered);
                // jQuery(ele).html('Activated');
                jQuery('#wiz-upgrade .button-group .wiz-button').removeClass('hidden');

                // Second AJAX request after the first one
                jQuery.ajax({
                    url: idfWizardParams.ajaxUrl,
                    type: 'post',
                    data: {
                        action: 'idf_wizard_validate_themes_access',
                    },
                    success: function (response) {
                        if (response.success) {
                            // Update HTML on success
                            jQuery('#wiz-themes').html(response.data);
                        } else {
                            // Show an error message if there's an issue with the request or action
                            jQuery('#wiz-themes').html('<p>No themes available.</p>');
                        }
                    },
                    error: function () {
                        // Show an error message if there's an issue with the AJAX request
                        jQuery('#wiz-themes').html('<p>Error loading themes.</p>');
                    },
                }).done(function() {
                    jQuery(document).trigger('idfInitializeTippy');
                });
            });

            break;
        case 'save_payment':
            jQuery(ele).html('Saving<em></em>');
            var paymentVal = jQuery('.payment-platform input:checked').val();
            var licenseText = jQuery('#license-details').data('license');
            if (paymentVal === 'wc' && licenseText === 'enterprise') {
                if (confirm(wp.i18n.__('You are about to activate WooCommerce as the e-commerce platform with the Enterprise Edition. This action will disable all IgnitionDeck frontend dashboard functionality. All ecommerce actions, including user accounts, will be handled by WooCommerce.\n\nAre you sure you want to proceed?', 'ignitiondeck'))) {
                    savePayment(ele, paymentVal);
                } else {
                    jQuery('.payment-platform input[value="idc"]').prop('checked', true);
                }
            } else {
                savePayment(ele, paymentVal);
            }
            break;
        case 'theme_install':
            if(jQuery(ele).hasClass('locked')) {
                window.open(jQuery(ele).data('url'), '_blank').focus();
            } else {
                jQuery(ele).html('Installing<em></em>');
                var data = {
                    action: 'idf_wizard_install_themes',
                    url: jQuery(ele).data('url'),
                    slug: jQuery(ele).data('slug'),
                    _wpnonce: idfWizardParams.nonce,
                };
                jQuery.post( idfWizardParams.ajaxUrl, data, function(response) {
                    jQuery(ele).html(response);
                    alert('Theme is installed. Visit Appearance > Themes to activate.');
                });
            }
            break;
        default:
            break;
    }
}

function savePayment(ele, paymentVal) {
    var data = {
        action: 'idf_wizard_save_payment',
        payment: paymentVal,
        _wpnonce: idfWizardParams.nonce,
    };
    jQuery.post(idfWizardParams.ajaxUrl, data, function(response) {
        var content = jQuery(response).filter("#license-details");
        var filtered = content.contents();
        jQuery('#license-details').html(filtered);

        var content = jQuery(response).filter("#configure-details");
        var filtered = content.contents();
        jQuery('#configure-details').html(filtered);
        // Check if the payment platform is WooCommerce
        if (data.payment === 'wc') {
            // Check if an element with class "ign-dashboard-receipt-settings" exists
            if (jQuery('.ign-dashboard-receipt-settings').length > 0) {
                // Hide the receipt settings
                jQuery('.ign-dashboard-receipt-settings').hide();
            } else {
                // Show the receipt settings
                jQuery('.ign-dashboard-receipt-settings').show();
            }
        }
    }).done(function() {
        jQuery(document).trigger('idfInitializeTippy');
    });
}

function wizard_call(data) {
    jQuery.post( idfWizardParams.ajaxUrl, data, function(response) {
        if( data.action=='idf_wizard_install_plugins' ) {
            jQuery('.wizard-tabs .active ul').html( response );
        }
        jQuery('.wizard-tab-content').removeClass('wiz-loader');
    });
}

function plugin_install(i, plugins) {
    if( i >= jQuery('#wiz-install li').length ) {
        jQuery('#wiz-loader').fadeIn();
        let pageUrl = window.location.href;
        jQuery.get( pageUrl, {}, function(response) {
            var content = jQuery(response).filter("#wpwrap");
            var filtered = content.contents();
            jQuery('#wpwrap').html(filtered);

            jQuery('.wiz-button.install').html('Installed and Activated');
            jQuery('.wiz-install-button.continue').prop('disabled',false);
            // Use idWizardScreen directly instead of checkHash
            if (window.location.hash !== '') {
                idWizardScreen(window.location.hash);
            } else {
                idWizardScreen('#wiz-install');
            }
            jQuery('#wiz-loader').fadeOut();
        });
    } else {
        var ele = jQuery('#wiz-install li:eq('+i+')');
        if(ele.data('status') == 'not') {
            ele.find('span').html('Installing<em></em>');
            var data = {
                action: 'idf_wizard_install_plugins',
                name: ele.data('name'),
                slug: ele.data('slug'),
                url: ele.data('url'),
                _wpnonce: idfWizardParams.nonce,
            };
            jQuery.post( idfWizardParams.ajaxUrl, data, function(response) {
                ele.find('span').html('Activating<em></em>');
                // Add a delay before activation to ensure database is ready
                setTimeout(function() {
                    var data = {
                        action: 'idf_wizard_activate_plugins',
                        _wpnonce: idfWizardParams.nonce,
                        name: ele.data('name'),
                        slug: ele.data('slug'),
                        url: ele.data('url'),
                    };
                    jQuery.post( idfWizardParams.ajaxUrl, data, function(response) {
                        if (response.success === false) {
                            // If activation failed, retry after a delay
                            setTimeout(function() {
                                ele.find('span').html('Retrying activation<em></em>');
                                plugin_install(i, plugins);
                            }, 1000);
                        } else {
                            ele.find('span').html('Installed and Activated');
                            i++;
                            plugin_install(i, plugins);
                        }
                    }).fail(function() {
                        // If AJAX call failed, retry after a delay
                        setTimeout(function() {
                            ele.find('span').html('Retrying activation<em></em>');
                            plugin_install(i, plugins);
                        }, 1000);
                    });
                }, 1000);
            });
        } else if(ele.data('status') == 'installed') {
            ele.find('span').html('Activating<em></em>');
            // Add a delay before activation to ensure database is ready
            setTimeout(function() {
                var data = {
                    action: 'idf_wizard_activate_plugins',
                    _wpnonce: idfWizardParams.nonce,
                    name: ele.data('name'),
                    slug: ele.data('slug'),
                    url: ele.data('url'),
                };
                jQuery.post( idfWizardParams.ajaxUrl, data, function(response) {
                    if (response.success === false) {
                        // If activation failed, retry after a delay
                        setTimeout(function() {
                            ele.find('span').html('Retrying activation<em></em>');
                            plugin_install(i, plugins);
                        }, 1000);
                    } else {
                        ele.find('span').html('Installed and Activated');
                        i++;
                        plugin_install(i, plugins);
                    }
                }).fail(function() {
                    // If AJAX call failed, retry after a delay
                    setTimeout(function() {
                        ele.find('span').html('Retrying activation<em></em>');
                        plugin_install(i, plugins);
                    }, 1000);
                });
            }, 1000);
        } else {
            i++;
            plugin_install(i, plugins);
        }
    }
}
// Use a self-executing function to create a private scope for variables
(function() {
    let dotCount = 0;
    let elipsis = '';
    setInterval(function () {
        dotCount++;
        if(dotCount>3) dotCount = 1;
        elipsis = '';
        for(let i=0; i<dotCount; i++) {
            elipsis += '.';
        }
        jQuery('.wizard-tabs em, #wiz-loader em').each(function() {
            jQuery(this).html(elipsis);
        });
    }, 500);
})();

function wizCheckConfig() {
    var data = {
        action: 'idf_wizard_check_config',
    };
    
    // Add a small delay to ensure DOM is fully loaded
    setTimeout(function() {
        jQuery.post( idfWizardParams.ajaxUrl, data, function(response) {
            try {
                var r = JSON.parse(response);
                
                // Reset all checkboxes first to ensure clean state
                jQuery('.ign-tools li .check').removeClass('checked');
                
                // Process configuration items
                processConfigItems(r, jQuery('ol.ign-tools').first(), 0, 7); // Required items
                processConfigItems(r, jQuery('ol.ign-tools').eq(1), 7); // Optional items
                
                // Force a repaint to ensure visual update
                forceRepaint();
            } catch(e) {
                console.error('Error parsing wizCheckConfig response:', e);
            }
        });
    }, 100); // Small delay to ensure DOM is ready
}

function processConfigItems(configData, listElement, startIndex, endIndex) {
    var configKeys = Object.keys(configData);
    var i;
    
    // Handle required items (with endIndex)
    if (endIndex) {
        for (i = startIndex; i < endIndex; i++) {
            if (i < configKeys.length && configData[configKeys[i]]) {
                listElement.find('li:eq(' + (i - startIndex) + ') .check').addClass('checked');
            }
        }
    } 
    // Handle optional items (no endIndex)
    else {
        for (i = startIndex; i < configKeys.length; i++) {
            if (configData[configKeys[i]]) {
                listElement.find('li:eq(' + (i - startIndex) + ') .check').addClass('checked');
            }
        }
    }
}

function forceRepaint() {
    setTimeout(function() {
        jQuery('.ign-tools li .check.checked').css('opacity', '0.99');
        setTimeout(function() {
            jQuery('.ign-tools li .check.checked').css('opacity', '');
        }, 50);
    }, 50);
}

function wizCreateMyDashboard(ele) {
    jQuery(ele).addClass('loading');
    var data = {
        action: 'idf_wizard_create_dashboard',
    };
    jQuery.post( idfWizardParams.ajaxUrl, data, function(response) {
        var r = jQuery.parseJSON(response);
        jQuery(ele).removeClass('loading');
        jQuery(ele).parent().find('.check').addClass('checked');
        showWizPopup(r.result.heading, r.result.content);
    });
}

function wizCreateCheckoutPage(ele) {
    jQuery(ele).addClass('loading');
    var data = {
        action: 'idf_wizard_create_checkout',
    };
    jQuery.post( idfWizardParams.ajaxUrl, data, function(response) {
        var r = jQuery.parseJSON(response);
        jQuery(ele).removeClass('loading');
        jQuery(ele).parent().find('.check').addClass('checked');
        showWizPopup(r.result.heading, r.result.content);
    });
}

function wizSetTimezone(ele) {
    jQuery(ele).addClass('loading');
    var data = {
        action: 'idf_wizard_get_timezone_html',
    };
    jQuery.post( idfWizardParams.ajaxUrl, data, function(response) {
        var r = jQuery.parseJSON(response);
        jQuery(ele).removeClass('loading');
        showWizPopup(r.result.heading, r.result.content);
    });
}

function wizSaveTimezone(ele) {
    jQuery(ele).addClass('loading');
    var data = {
        action: 'idf_wizard_save_timezone',
        wiz_timezone: jQuery('#wiz-notice #timezone_string option:selected').val(),
        _wpnonce: idfWizardParams.nonce,
    };
    jQuery.post( idfWizardParams.ajaxUrl, data, function(response) {
        var r = jQuery.parseJSON(response);
        jQuery(ele).removeClass('loading');
        //jQuery('.ign-tools li:eq(2) .check').addClass('checked');
        jQuery('.button[onclick="wizSetTimezone(this);"]').parent().find('.check').addClass('checked');
        showWizPopup(r.result.heading, r.result.content);
    });
}

function wizSetPermalink(ele) {
    jQuery(ele).addClass('loading');
    var data = {
        action: 'idf_wizard_set_permalink',
    };
    jQuery.post( idfWizardParams.ajaxUrl, data, function(response) {
        var r = jQuery.parseJSON(response);
        jQuery(ele).removeClass('loading');
        jQuery(ele).parent().find('.check').addClass('checked');
        showWizPopup(r.result.heading, r.result.content);
    });
}

function wizReceiptSettings(ele) {
    jQuery(ele).addClass('loading');
    var data = {
        action: 'idf_wizard_get_receipt_html',
    };
    jQuery.post( idfWizardParams.ajaxUrl, data, function(response) {
        var r = jQuery.parseJSON(response);
        jQuery(ele).removeClass('loading');
        showWizPopup(r.result.heading, r.result.content);
    });
}

function saveReceiptSettings(ele) {
    jQuery(ele).addClass('loading');
    var coName = jQuery('#wiz-notice #co-name');
    var coEmail = jQuery('#wiz-notice #co-email');

    // Reset error messages
    coName.next('.ign-receipt-settings-error-message').hide();
    coEmail.next('.ign-receipt-settings-error-message').hide();

    var coNameValue = coName.val().trim();
    var coEmailValue = coEmail.val().trim();

    if (coNameValue === '') {
        coName.next('.ign-receipt-settings-error-message').show();
    }

    if (coEmailValue === '') {
        coEmail.next('.ign-receipt-settings-error-message').show();
    }

    if (coNameValue === '' || coEmailValue === '') {
        jQuery(ele).removeClass('loading');
        return; // Don't proceed if there are empty fields
    }

    var data = {
        action: 'idf_wizard_save_receipt_settings',
        co_name: coNameValue,
        co_email: coEmailValue,
        _wpnonce: idfWizardParams.nonce,
    };

    jQuery.post(idfWizardParams.ajaxUrl, data, function(response) {
        var r = jQuery.parseJSON(response);
        jQuery(ele).removeClass('loading');
        //jQuery('.ign-tools li:eq(4) .check').addClass('checked');
        jQuery('.button[onclick="wizReceiptSettings(this);"]').parent().find('.check').addClass('checked');
        showWizPopup(r.result.heading, r.result.content);
    });
}

function wizPaymentGateway(ele) {
    jQuery(ele).addClass('loading');
    var data = {
        action: 'idf_wizard_payment_gateway'
    };
    jQuery.post( idfWizardParams.ajaxUrl, data, function(response) {
        var r = jQuery.parseJSON(response);
        jQuery(ele).removeClass('loading');
        jQuery(ele).parent().find('.check').addClass('checked');
        //showWizPopup(r.result.heading, r.result.content);
    });
}

function wizCurrencyPreference(ele) {
    jQuery(ele).addClass('loading');
    var data = {
        action: 'idf_wizard_get_currency_html',
    };
    jQuery.post( idfWizardParams.ajaxUrl, data, function(response) {
        var r = jQuery.parseJSON(response);
        jQuery(ele).removeClass('loading');
        showWizPopup(r.result.heading, r.result.content);
    });
}

function saveGlobalCurrency(ele) {
    jQuery(ele).addClass('loading');
    var data = {
        action: 'idf_wizard_save_global_currency',
        global_currency: jQuery('#wiz-notice #global-currency').val(),
        _wpnonce: idfWizardParams.nonce,
    };
    jQuery.post( idfWizardParams.ajaxUrl, data, function(response) {
        var r = jQuery.parseJSON(response);
        jQuery(ele).removeClass('loading');
        //jQuery('.ign-tools li:eq(6) .check').addClass('checked');
        jQuery('.button[onclick="wizCurrencyPreference(this);"]').parent().find('.check').addClass('checked');
        showWizPopup(r.result.heading, r.result.content);
    });
}

function wizCreatePrivacyPolicy(ele) {
    jQuery(ele).addClass('loading');
    var data = {
        action: 'idf_wizard_create_privacy_policy',
    };
    jQuery.post( idfWizardParams.ajaxUrl, data, function(response) {
        var r = jQuery.parseJSON(response);
        jQuery(ele).removeClass('loading');
        jQuery(ele).parent().find('.check').addClass('checked');
        showWizPopup(r.result.heading, r.result.content);
    });
}

function wizTermsofUse(ele) {
    jQuery(ele).addClass('loading');
    var data = {
        action: 'idf_wizard_create_terms_of_use',
    };
    jQuery.post( idfWizardParams.ajaxUrl, data, function(response) {
        var r = jQuery.parseJSON(response);
        jQuery(ele).removeClass('loading');
        jQuery(ele).parent().find('.check').addClass('checked');
        showWizPopup(r.result.heading, r.result.content);
    });
}

function wizCreateSampleProject(ele) {
    jQuery(ele).addClass('loading');
    var data = {
        action: 'idf_wizard_create_sample_project',
    };
    jQuery.post( idfWizardParams.ajaxUrl, data, function(response) {
        var r = jQuery.parseJSON(response);
        jQuery(ele).removeClass('loading');
        jQuery(ele).parent().find('.check').addClass('checked');
        showWizPopup(r.result.heading, r.result.content);
    });
}

function wizDeleteSampleProject(ele) {
    var html = `<form method="POST" action="" class="confirmation">
			<div class="form-input">
                <p>It will delete the <b>Sample Project</b>, the products, the product→reward level connection, and any orders in IgnitionDeck » IDCF Orders and IDC » Orders permanently.</p>
			</div>
			<div class="submit">
				<input type="button" class="button button-secondary" value="Close" onclick="wizClosePopup()">
				<input type="button" class="button button-primary" value="Delete" onclick="wizConfirmDelete(this)">
			</div>
		</form>`;
    showWizPopup('Confirm', html);
}

function wizConfirmDelete(ele) {
    jQuery(ele).addClass('loading');
    var data = {
        action: 'idf_wizard_delete_sample_project',
    };
    jQuery.post( idfWizardParams.ajaxUrl, data, function(response) {
        var r = jQuery.parseJSON(response);
        jQuery(ele).removeClass('loading');
        jQuery('.button[onclick="wizCreateSampleProject(this);"]').parent().find('.check').removeClass('checked');
        showWizPopup(r.result.heading, r.result.content);
    });
}

function showWizPopup(heading = 'Notice', content='') {
    jQuery('#wiz-notice-title').html(heading);
    jQuery('#wiz-notice-content').html(content);
    jQuery('#wiz-notice').fadeIn();
    
    // Re-bind close button event to ensure it works
    jQuery('.wiz-notice-close').off('click').on('click', function() {
        wizClosePopup();
    });
    
    // Re-bind click outside handler
    jQuery(document).off('click.wizardmodal').on('click.wizardmodal', function(event) {
        if (!jQuery(event.target).closest('.wiz-notice-box').length && !jQuery(event.target).closest('.ign-tools_delete_sampleproject').length) {
            wizClosePopup();
        }
    });
}

function wizClosePopup() {
    jQuery('#wiz-notice').fadeOut();
}
