jQuery(document).ready(function($) {

    function getParam(key) {
        var paramsStr = window.location.search.substr(1, window.location.search.length),
            paramsArr = paramsStr.split("&"),
            items     = [];

        for (var i = 0; i < paramsArr.length; i++) {
            items[paramsArr[i].split("=")[0]] = paramsArr[i].split("=")[1];
        }

        if (key != "" && key != undefined) {
            // return single
            if (items[key] != undefined) {
                return items[key];
            } else {
                return null;
            }
        } else {
            // return all (array)
            return items;
        }
    };

    if (getParam('post')){
        // Fetch data via AJAX
        $.ajax({
            url: formipay_admin.ajax_url, // WordPress AJAX URL
            method: 'GET',
            data: {
                action: 'fetch_formipay_settings',
                post_id: formipay_admin.form_id, // Assuming you have post ID available globally,
                _wpnonce: formipay_admin.nonce
            },
            success: function(response) {
                var source = $("#preview-template").html();
                var template = Handlebars.compile(source);
                var context = {
                    fields: response.data.fields
                };
                var html = template(context);
                $("#preview-wrapper").html(html);
            }
        });
    }

    // Fetch data via AJAX
    $.ajax({
        url: formipay_admin.ajax_url, // WordPress AJAX URL
        method: 'GET',
        data: {
            action: 'fetch_formipay_fields',
        },
        success: function(response) {
            var source = $("#add-field-form-template").html();
            var template = Handlebars.compile(source);
            var context = {
                fields: response.data.fields
            };
            var html = template(context);
            $("#add_field_form").html(html);
            $('#add_field_form .field select.form-select').trigger('change');
        }
    });

    // Handlebars helper for comparing equality
    Handlebars.registerHelper('ifEquals', function(arg1, arg2, options) {
        return (arg1 == arg2) ? options.fn(this) : options.inverse(this);
    });

    // Handlebars helper for checking inequality
    Handlebars.registerHelper('ifNotEquals', function(arg1, arg2, options) {
        return (arg1 != arg2) ? options.fn(this) : options.inverse(this);
    });

    // Handlebars helper for checking if a value is in a list
    Handlebars.registerHelper('ifIn', function(value, list, options) {
        return (list.split(' ').indexOf(value) > -1) ? options.fn(this) : options.inverse(this);
    });

    // Handlebars helper for checking if a value is in a list
    Handlebars.registerHelper('ifNotIn', function(value, list, options) {
        return (list.split(' ').indexOf(value) > -1) ? options.inverse(this) : options.fn(this);
    });

    // Handlebars helper for JSON stringify
    Handlebars.registerHelper('json', function(context) {
        return JSON.stringify(context);
    });

    // Handlebars helper to concatenate custom classes
    Handlebars.registerHelper('custom_class', function(custom_class) {
        return (custom_class && Array.isArray(custom_class)) ? ' '+custom_class.join(' ') : '';
    });

     // Handlebars helper to handle conditional classes and display properties
     Handlebars.registerHelper('conditional_class', function(conditional) {
        return (conditional && conditional.length > 0) ? ' has-conditional' : '';
    });

    // Handlebars helper to return label class
    Handlebars.registerHelper('labelClass', function(fieldType) {
        return 'label-' + fieldType;
    });

    // Handlebars helper to return name attribute for checkbox and radio inputs
    Handlebars.registerHelper('name', function(fieldType, fieldId, index) {
        return (fieldType == 'radio') ? fieldId : fieldId + '-' + index;
    });

    Handlebars.registerHelper('display', function(conditional) {
        var display = '';
        if (conditional) {
            display = ' style="display:none"';
            if (Array.isArray(conditional)) {
                conditional.forEach(function(cond) {
                    display += ' data-if-' + cond.key + "='" + JSON.stringify(cond.value) + "'";
                });
            }
        }
        return display;
    });

    // Handlebars helper to format option text
    Handlebars.registerHelper('formatOption', function(option) {
        return option.charAt(0).toUpperCase() + option.slice(1).replace('_', ' ');
    });

    // Handlebars helper for toggle display property
    Handlebars.registerHelper('toggleDisplay', function(toggle) {
        return (toggle == 'yes') ? ' style="display:none;"' : '';
    });

    // Handlebars helper for set grid column for checkbox and radio
    Handlebars.registerHelper('layoutColumn', function(layout) {
        return (layout !== '') ? layout : 1;
    });

    // Handlebars helper for set the first option as selected
    Handlebars.registerHelper('selectedTheFirstOption', function(index) {
        return (index == 0) ? ' selected' : '';
    });

    // Handlebars helper for set the first option as selected
    Handlebars.registerHelper('countryListOptions', function() {
        var country_json = formipay_admin.preset.country_list;
        // Check if country_json is a string (indicating it might need to be parsed)
        if (typeof country_json === 'string') {
            try {
                country_json = JSON.parse(country_json); // Parse the JSON string into an object
            } catch (e) {
                console.error('Error parsing JSON:', e); // Log any parsing errors
                country_json = []; // Fallback to an empty array
            }
        }

        // Validate the data type
        if (!Array.isArray(country_json)) {
            console.error('Expected an array but got:', country_json);
            country_json = []; // Fallback to an empty array if not an array
        }

        var options_html = ``; // Initialize options_html variable

        // Loop through each country object
        $.each(country_json, function(index, country) {
            // Assuming each country object has 'id' for the value and 'name' for the display text
            options_html += `<option value="${country.name}">${country.name}</option>`;
        });

        return options_html;
    });

});
