jQuery(function($){

    let wpcftoLoaded = false;

    var checkWpcftoLoaded = setInterval(() => {
        const container = $('.wpcfto-tab');
        if(container.length > 0){
            wpcftoLoaded = true;
            $(document).trigger('wpcftoLoaded');
            clearInterval(checkWpcftoLoaded);
        }
    }, 250);

    $(document).on('wpcftoLoaded', function(){
        update_option_to_data_mapping('initial');
    });

    function all_active_payments() {

        var items = $('.payment_gateways #active .list-group-item');
        var active_payments = [];

        if(items.length > 0){
            $.each(items, function(i, item){
                var gateway = $(item).attr('id');
                if(gateway.indexOf(':::') !== -1){
                    gateway = gateway.split(':::')[0];
                    gateway = gateway.replace('_', '-');
                }
                // $('[data-submenu=payments_'+gateway+']').show();
                active_payments.push(gateway);
            });
        }

        return active_payments;

    }

    function hide_inactive_payment_submenu() {
        
        var div = $('[data-section=payments]').siblings('.wpcfto-submenus').find('[data-submenu]:not([data-submenu=payments_general])');
        var active_payments = all_active_payments();

        if(div.length > 0) {
            $.each(div, function(x, y){
                var gateway = $(y).attr('data-submenu').replace('payments_', '');
                if(jQuery.inArray(gateway, active_payments) !== -1){
                    $(y).slideDown();
                }else{
                    $(y).slideUp();
                }
            });
        }
    }

    setTimeout(() => {
        hide_inactive_payment_submenu();
    }, 1000);
    

    $(document).on('mouseleave', '.payment_gateways .list-group', function(){

        hide_inactive_payment_submenu();

    });

    $(document).on('click', '.formipay-editor-nav .nav-link', function(){
        $('.formipay-editor-nav').find('.nav-link').removeClass('active');
        $(this).addClass('active');
        $('.formipay-editor-tab-content.nav-content-section').addClass('d-none');
        var tab_content = $(this).data('tab-content');
        $('.formipay-editor-tab-content'+tab_content).removeClass('d-none');
    });

    $('.formipay-editor-nav .nav-item:first-child > .nav-link').trigger('click');
    
    $(document).on('click', '#is_required', function(){
        if($(this).is(':checked')) {
            $(this).val('yes');
        }else{
            $(this).val('no');
        }
    });

    $(document).on('blur change', '#add_field_form .field select.form-select', function(){
        var array = ['divider', 'page_break'];
        if( $.inArray( $(this).val(), array ) !== -1 ) {
            $('#add_field_form .field:not(.main-field)').slideUp();
        }else{
            $('#add_field_form .field:not(.main-field):not(.has-conditional)').slideDown();
        }
    });

    function formipay_sortable(){
        $('#preview-wrapper').sortable({
            opacity: 0.75,
            items: '> .preview-field',
            handle: 'span.grab',
            change: function(event, ui) {
                ui.placeholder.css({
                    visibility: 'visible', 
                    border : '2px dashed #8c8f94',
                    borderRadius: '10px'
                });
            },
            stop: function(event, ui){
                update_option_to_data_mapping('update');
            }
        });
        $('.repeater-child-wrapper').sortable({
            opacity: 0.75,
            items: '> .repeater-child-input',
            handle: 'span.grab',
            change: function(event, ui) {
                ui.placeholder.css({
                    visibility: 'visible', 
                    border : '2px dashed #cccccc',
                    borderRadius: '5px'
                });
            }
        });
    }

    formipay_sortable();

    $(document).on('change blur', '#add_field_form [name=label]', function(){
        $('#add_field_form [name=field_id]').val($(this).val().toLowerCase().replace(' ', '_'));
    });

    $(document).on('click', '.add-option', function(e){
        e.preventDefault();
        var content = $(this).closest('.repeater-child-input').html();
        $(this).closest('.repeater-child-wrapper').append(`
            <div class="repeater-child-input d-flex justify-content-start align-items-start gap-2 my-2">`+content+`
            </div>`);
        $('.repeater-child-input:last-child').find('input').val('');
        $('.repeater-child-input:last-child').find('.add-thumbnail').removeClass('text-info').addClass('text-white');
    });

    $(document).on('click', '.delete-option', function(e){
        e.preventDefault();
        $(this).closest('.repeater-child-input').remove();
    });

    $(document).on('click', 'input.option-field-toggle', function(){
        var target = $(this).attr('data-child-field');
        if($(this).is(':checked')){
            $('.child-field-'+target).show();
        }else{
            $('.child-field-'+target).hide();
        }
    });

    $(document).on('change', '#add_field_form .formipay-builder-field:not(.formipay-builder-option-field, [type=checkbox], [type=checkbox])', function(){
        var value = $(this).val();
        var name = $(this).attr('name');
        var the_dependent = $('#add_field_form [data-if-'+name+']');
        if('' !== value && the_dependent.length > 0){
            // var all_dependents = $('.has-conditional');
            $.each(the_dependent, function(x, y){
                var decoded_value = JSON.parse($(y).attr('data-if-'+name));
                if($.inArray(value, decoded_value) !== -1){
                    $(y).slideDown();
                }else{
                    $(y).slideUp();
                }
            });
        }
    });

    $(document).on('click', '.add-field', function(e){
        e.preventDefault();

        var option_image_toggle = 'no';
        if($('#repeater-child-0_thumbnail').is(':checked')){
            option_image_toggle = 'yes';
        }
        var option_value_toggle = 'no';
        if($('#repeater-child-2_value').is(':checked')){
            option_value_toggle = 'yes';
        }
        var option_amount_toggle = 'no';
        if($('#repeater-child-3_amount').is(':checked')){
            option_amount_toggle = 'yes';
        }
        
        var setup = {
            'label'         : $('#add_field_form [name=label]').val(),
            'field_id'      : $('#add_field_form [name=field_id]').val(),
            'field_type'    : $('#add_field_form [name=field_type]').val(),
            'options_type'  : $('#add_field_form [name=options_type]').val(),
            'placeholder'   : $('#add_field_form [name=placeholder]').val(),
            'default_value' : $('#add_field_form [name=default_value]').val(),
            'description'   : $('#add_field_form [name=description]').val(),
            'is_required'   : $('#add_field_form [name=is_required]').val(),
            'show_toggle'   : {
                'image' : option_image_toggle,
                'value' : option_value_toggle,
                'amount': option_amount_toggle 
            },
            'layout'        : $('#option_grid_columns').val()
        };

        var options = [];
        var calculable_field = ['select', 'radio', 'checkbox'];
        if($.inArray(setup.field_type, calculable_field) !== -1){
            var single_option = $('.repeater-child-input');
            if(single_option.length > 0){
                $.each(single_option, function(a, b){
                    var check_qty;
                    if($(b).find('.repeater-child-input-qty').is(':checked')){
                        check_qty = 'yes';
                    }else{
                        check_qty = 'no';
                    }
                    var option = {
                        'image_id': $(b).find('.field-image-id').val(),
                        'image_url': $(b).find('.field-image-url').val(),
                        'label': $(b).find('.repeater-child-input-label').find('input').val(),
                        'value': $(b).find('.repeater-child-input-value').find('input').val(),
                        'amount': $(b).find('.repeater-child-input-amount').find('input').val(),
                        'weight': $(b).find('.repeater-child-input-weight').find('input').val(),
                        'qty': check_qty
                    }
                    options.push(option);
                });
            }
        }

        setup.field_options = options;

        // console.log(setup);

        var setup_string = JSON.stringify(setup);
        var not_input = ['select', 'checkbox', 'radio'];
        var is_required = '';
        var asterisk = '';
        if(setup.is_required == 'yes'){
            is_required = '';
            asterisk = ' <span style="color:red;">(*)</span>';
        }
        var hidden = '';
        if(setup.field_type == 'hidden'){
            hidden = ' style="opacity: .75;"'
        }
        if(!setup.calc_value){
            setup.calc_value = 0;
        }

        var preview_content = '';
        if($.inArray(setup.field_type, not_input) == -1){
            if($.inArray(setup.field_type, ['divider', 'page_break']) !== -1){
                preview_content = `
                <div class="formipay-field w-100"`+hidden+`>
                    <div class="d-flex justify-content-between field-controls">
                        <label for="`+setup.field_id+`" class="label-`+setup.field_type+`">`+setup.label+`</label>
                        <div class="field-icons d-flex gap-2 align-items-center the_buttons">
                            <button class="btn btn-sm edit-preview-field">
                                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24">
                                    <path fill="#000" d="M5 19h1.425L16.2 9.225L14.775 7.8L5 17.575zm-2 2v-4.25L16.2 3.575q.3-.275.663-.425t.762-.15t.775.15t.65.45L20.425 5q.3.275.438.65T21 6.4q0 .4-.137.763t-.438.662L7.25 21zM19 6.4L17.6 5zm-3.525 2.125l-.7-.725L16.2 9.225z" />
                                </svg>
                            </button>
                            <button class="btn btn-sm delete-preview-field">
                                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24">
                                    <path fill="#000" d="M7 21q-.825 0-1.412-.587T5 19V6H4V4h5V3h6v1h5v2h-1v13q0 .825-.587 1.413T17 21zm2-4h2V8H9zm4 0h2V8h-2z" />
                                </svg>
                            </button>
                        </div>
                    </div>
                    <input type="hidden" name="`+setup.field_id+`_config" class="formipay-field-setup" value='`+setup_string+`'>
                    <span class="divider-line"></span>
                    <p class="formipay-inline-desc">`+setup.description+`</p>
                </div>`;
            }else if(setup.field_type == 'country_list') {
                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 = `<option>-- ${setup.placeholder}</option>`;

                // 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>`;
                });

                preview_content = `
                <div class="formipay-field w-100"`+hidden+`>
                    <div class="d-flex justify-content-between field-controls">
                        <label for="`+setup.field_id+`">`+setup.label+asterisk+`</label>
                        <div class="field-icons d-flex gap-2 align-items-center the_buttons">
                            <button class="btn btn-sm edit-preview-field">
                                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24">
                                    <path fill="#000" d="M5 19h1.425L16.2 9.225L14.775 7.8L5 17.575zm-2 2v-4.25L16.2 3.575q.3-.275.663-.425t.762-.15t.775.15t.65.45L20.425 5q.3.275.438.65T21 6.4q0 .4-.137.763t-.438.662L7.25 21zM19 6.4L17.6 5zm-3.525 2.125l-.7-.725L16.2 9.225z" />
                                </svg>
                            </button>
                            <button class="btn btn-sm delete-preview-field">
                                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24">
                                    <path fill="#000" d="M7 21q-.825 0-1.412-.587T5 19V6H4V4h5V3h6v1h5v2h-1v13q0 .825-.587 1.413T17 21zm2-4h2V8H9zm4 0h2V8h-2z" />
                                </svg>
                            </button>
                        </div>
                    </div>
                    <input type="hidden" name="`+setup.field_id+`_config" class="formipay-field-setup" value='`+setup_string+`'>
                    <select id="`+setup.field_id+`" class="formipay-input formipay-form-field" `+is_required+`>
                        `+options_html+`
                    </select>
                    <p class="formipay-inline-desc">`+setup.description+`</p>
                </div>`;
            }else if(setup.field_type !== 'textarea'){
                preview_content = `
                <div class="formipay-field w-100"`+hidden+`>
                    <div class="d-flex justify-content-between field-controls">
                        <label for="`+setup.field_id+`">`+setup.label+asterisk+`</label>
                        <div class="field-icons d-flex gap-2 align-items-center the_buttons">
                            <button class="btn btn-sm edit-preview-field">
                                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24">
                                    <path fill="#000" d="M5 19h1.425L16.2 9.225L14.775 7.8L5 17.575zm-2 2v-4.25L16.2 3.575q.3-.275.663-.425t.762-.15t.775.15t.65.45L20.425 5q.3.275.438.65T21 6.4q0 .4-.137.763t-.438.662L7.25 21zM19 6.4L17.6 5zm-3.525 2.125l-.7-.725L16.2 9.225z" />
                                </svg>
                            </button>
                            <button class="btn btn-sm delete-preview-field">
                                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24">
                                    <path fill="#000" d="M7 21q-.825 0-1.412-.587T5 19V6H4V4h5V3h6v1h5v2h-1v13q0 .825-.587 1.413T17 21zm2-4h2V8H9zm4 0h2V8h-2z" />
                                </svg>
                            </button>
                        </div>
                    </div>
                    <input type="hidden" name="`+setup.field_id+`_config" class="formipay-field-setup" value='`+setup_string+`'>
                    <input type="`+setup.field_type+`" id="`+setup.field_id+`" class="formipay-input formipay-form-field" placeholder="`+setup.placeholder+`" data-calc-value="`+setup.calc_value+`" `+is_required+` />
                    <p class="formipay-inline-desc">`+setup.description+`</p>
                </div>`;
            }else{
                preview_content = `
                <div class="formipay-field w-100"`+hidden+`>
                    <div class="d-flex justify-content-between field-controls">
                        <label for="`+setup.field_id+`">`+setup.label+asterisk+`</label>
                        <div class="field-icons d-flex gap-2 align-items-center the_buttons">
                            <button class="btn btn-sm edit-preview-field">
                                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24">
                                    <path fill="#000" d="M5 19h1.425L16.2 9.225L14.775 7.8L5 17.575zm-2 2v-4.25L16.2 3.575q.3-.275.663-.425t.762-.15t.775.15t.65.45L20.425 5q.3.275.438.65T21 6.4q0 .4-.137.763t-.438.662L7.25 21zM19 6.4L17.6 5zm-3.525 2.125l-.7-.725L16.2 9.225z" />
                                </svg>
                            </button>
                            <button class="btn btn-sm delete-preview-field">
                                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24">
                                    <path fill="#000" d="M7 21q-.825 0-1.412-.587T5 19V6H4V4h5V3h6v1h5v2h-1v13q0 .825-.587 1.413T17 21zm2-4h2V8H9zm4 0h2V8h-2z" />
                                </svg>
                            </button>
                        </div>
                    </div>
                    <input type="hidden" name="`+setup.field_id+`_config" class="formipay-field-setup" value='`+setup_string+`'>
                    <textarea rows="4" id="`+setup.field_id+`" class="formipay-input formipay-form-field" placeholder="`+setup.placeholder+`" data-calc-value="`+setup.calc_value+`" `+is_required+`></textarea>
                    <p class="formipay-inline-desc">`+setup.description+`</p>
                </div>`;
            }
        }else{
            if(setup.field_type == 'select'){
                var options = setup.field_options;
                var options_html = '';
                if(setup.placeholder !== ''){
                    options_html = '<option>'+setup.placeholder+'</option>';
                }
                $.each(options, function(j, k){
                    var label = k.label;
                    var value = label;
                    if('' !== k.value && setup.show_toggle.value == 'yes'){
                        value = k.value;
                    }
                    var calc = 0;
                    if('' !== k.amount && setup.show_toggle.amount == 'yes'){
                        calc = k.amount;
                    }
                    options_html += '<option value="'+value+'" data-calc-value="'+calc+'">'+label+'</option>';
                });                
                preview_content = `
                <div class="formipay-field w-100"`+hidden+`>
                    <div class="d-flex justify-content-between field-controls">
                        <label for="`+setup.field_id+`">`+setup.label+asterisk+`</label>
                        <div class="field-icons d-flex gap-2 align-items-center the_buttons">
                            <button class="btn btn-sm edit-preview-field">
                                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24">
                                    <path fill="#000" d="M5 19h1.425L16.2 9.225L14.775 7.8L5 17.575zm-2 2v-4.25L16.2 3.575q.3-.275.663-.425t.762-.15t.775.15t.65.45L20.425 5q.3.275.438.65T21 6.4q0 .4-.137.763t-.438.662L7.25 21zM19 6.4L17.6 5zm-3.525 2.125l-.7-.725L16.2 9.225z" />
                                </svg>
                            </button>
                            <button class="btn btn-sm delete-preview-field">
                                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24">
                                    <path fill="#000" d="M7 21q-.825 0-1.412-.587T5 19V6H4V4h5V3h6v1h5v2h-1v13q0 .825-.587 1.413T17 21zm2-4h2V8H9zm4 0h2V8h-2z" />
                                </svg>
                            </button>
                        </div>
                    </div>
                    <input type="hidden" name="`+setup.field_id+`_config" class="formipay-field-setup" value='`+setup_string+`'>
                    <select id="`+setup.field_id+`" class="formipay-input formipay-form-field" `+is_required+`>
                        `+options_html+`
                    </select>
                    <p class="formipay-inline-desc">`+setup.description+`</p>
                </div>`;
            }else{
                var options = setup.field_options;
                var options_html = '';
                $.each(options, function(j, k){
                    var name = setup.field_id+`-`+j;
                    if(setup.field_type == 'radio'){
                        name = setup.field_id;
                    }
                    var label = k.label;
                    var value = label;
                    if('' !== k.value && setup.show_toggle.value == 'yes'){
                        value = k.value;
                    }
                    var calc = 0;
                    if('' !== k.amount && setup.show_toggle.amount == 'yes'){
                        calc = k.amount;
                    }
                    var image = '';
                    if('' !== k.image_id && '' !== k.image_url){
                        image = `<img src="`+k.image_url+`" style="width: 100%; height: 150px; object-fit: contain;">`;
                    }
                    options_html += 
                    `<div class="formipay-checkbox-group">
                        `+image+`
                        <input type="`+setup.field_type+`" id="`+setup.field_id+`-`+j+`" name="`+name+`" class="formipay-input formipay-form-field" value="`+k.value+`" />
                        <label for="`+setup.field_id+`-`+j+`">`+k.label+`</label>
                    </div>`;
                }); 
                if(setup.layout == ''){
                    setup.layout = 1;
                }
                preview_content = `
                <div class="formipay-field w-100"`+hidden+`>
                    <div class="d-flex justify-content-between field-controls">
                        <label for="`+setup.field_id+`">`+setup.label+asterisk+`</label>
                        <div class="field-icons d-flex gap-2 align-items-center the_buttons">
                            <button class="btn btn-sm edit-preview-field">
                                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24">
                                    <path fill="#000" d="M5 19h1.425L16.2 9.225L14.775 7.8L5 17.575zm-2 2v-4.25L16.2 3.575q.3-.275.663-.425t.762-.15t.775.15t.65.45L20.425 5q.3.275.438.65T21 6.4q0 .4-.137.763t-.438.662L7.25 21zM19 6.4L17.6 5zm-3.525 2.125l-.7-.725L16.2 9.225z" />
                                </svg>
                            </button>
                            <button class="btn btn-sm delete-preview-field">
                                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24">
                                    <path fill="#000" d="M7 21q-.825 0-1.412-.587T5 19V6H4V4h5V3h6v1h5v2h-1v13q0 .825-.587 1.413T17 21zm2-4h2V8H9zm4 0h2V8h-2z" />
                                </svg>
                            </button>
                        </div>
                    </div>
                    <input type="hidden" name="`+setup.field_id+`_config" class="formipay-field-setup" value='`+setup_string+`'>
                    <div class="formipay-checkbox-wrapper" style="display: grid; grid-template-columns: repeat(`+setup.layout+`, 1fr); gap: 10px;">
                        `+options_html+`
                    </div>
                    <p class="formipay-inline-desc">`+setup.description+`</p>
                </div>`;
            }
        }

        var hidden = is_required = '';
        if(setup.type == 'hidden'){
            hidden = ' style="display: none;"';
        }
        if(setup.require == 'yes'){
            is_required = ' required';
        }

        // Check if any

        var edit_to = $('.add-field').attr('data-edit-to');
        var the_existed_field = $('.preview-field[data-field="'+edit_to+'"]');

        if(the_existed_field.length > 0){
            $('.preview-field[data-field="'+edit_to+'"]').html(`
                    <span class="grab pb-4">
                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24">
                            <path fill="#000" d="M9 20q-.825 0-1.412-.587T7 18t.588-1.412T9 16t1.413.588T11 18t-.587 1.413T9 20m6 0q-.825 0-1.412-.587T13 18t.588-1.412T15 16t1.413.588T17 18t-.587 1.413T15 20m-6-6q-.825 0-1.412-.587T7 12t.588-1.412T9 10t1.413.588T11 12t-.587 1.413T9 14m6 0q-.825 0-1.412-.587T13 12t.588-1.412T15 10t1.413.588T17 12t-.587 1.413T15 14M9 8q-.825 0-1.412-.587T7 6t.588-1.412T9 4t1.413.588T11 6t-.587 1.413T9 8m6 0q-.825 0-1.412-.587T13 6t.588-1.412T15 4t1.413.588T17 6t-.587 1.413T15 8" />
                        </svg>
                    </span>
                    `+preview_content+`
            `);
        }else{
            $('#preview-wrapper').append(`
                <div class="preview-field d-flex gap-2 align-items-center" data-field="`+setup.field_id+`" data-field-type="`+setup.field_type+`">
                    <span class="grab pb-4">
                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24">
                            <path fill="#000" d="M9 20q-.825 0-1.412-.587T7 18t.588-1.412T9 16t1.413.588T11 18t-.587 1.413T9 20m6 0q-.825 0-1.412-.587T13 18t.588-1.412T15 16t1.413.588T17 18t-.587 1.413T15 20m-6-6q-.825 0-1.412-.587T7 12t.588-1.412T9 10t1.413.588T11 12t-.587 1.413T9 14m6 0q-.825 0-1.412-.587T13 12t.588-1.412T15 10t1.413.588T17 12t-.587 1.413T15 14M9 8q-.825 0-1.412-.587T7 6t.588-1.412T9 4t1.413.588T11 6t-.587 1.413T9 8m6 0q-.825 0-1.412-.587T13 6t.588-1.412T15 4t1.413.588T17 6t-.587 1.413T15 8" />
                        </svg>
                    </span>
                    `+preview_content+`
                </div>
            `);
        }

        $('.preview-field[data-field="'+setup.field_id+'"]').attr('data-field-type', setup.field_type);

        // scissors icon
        if(setup.field_type == 'page_break'){
            $('.preview-field[data-field="'+setup.field_id+'"]').append(`
                <span class="scissors">
                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24">
                        <path fill="#000" d="m12 14l-2.35 2.35q.2.375.275.8T10 18q0 1.65-1.175 2.825T6 22t-2.825-1.175T2 18t1.175-2.825T6 14q.425 0 .85.075t.8.275L10 12L7.65 9.65q-.375.2-.8.275T6 10q-1.65 0-2.825-1.175T2 6t1.175-2.825T6 2t2.825 1.175T10 6q0 .425-.075.85t-.275.8L20.6 18.6q.675.675.3 1.538T19.575 21q-.275 0-.537-.112t-.463-.313zm3-3l-2-2l5.575-5.575q.2-.2.463-.312T19.574 3q.95 0 1.313.875t-.313 1.55zM6 8q.825 0 1.413-.587T8 6t-.587-1.412T6 4t-1.412.588T4 6t.588 1.413T6 8m6 4.5q.2 0 .35-.15t.15-.35t-.15-.35t-.35-.15t-.35.15t-.15.35t.15.35t.35.15M6 20q.825 0 1.413-.587T8 18t-.587-1.412T6 16t-1.412.588T4 18t.588 1.413T6 20" />
                    </svg>
                </span>
            `)
        }else{
            $('.preview-field[data-field="'+setup.field_id+'"] > span.scissors').remove();
        }

        var builder_fields = $('#add_field_form').find('.formipay-builder-field');
        if(builder_fields.length > 0){
            $.each(builder_fields, function(a, b){
                if($(b).attr('type') == 'checkbox'){
                    $(b).val('no').prop('checked', false);
                }else{
                    $(b).val('');
                }
            });
        }

        $('.repeater-child-input:not(:first-child)').remove();
        $('.repeater-child-input > input').val('');
        $('.repeater-child-input > .add-thumbnail').removeClass('text-info').addClass('text-white');
        $('.repeater-child-input .check-qty').prop('checked', false);
        $('#add_field_form .field.has-conditional').slideUp();
        
        var all_option_toggle = $('.option-field-toggle');
        $.each(all_option_toggle, function(p, q){
            if($(q).is(':checked')){
                $(q).trigger('click');
            }
        });
        
        $('.child-field-image-wrapper').find('img').attr('src', '').hide();
        $('.child-field-image-wrapper').find('i').attr('src', '').show();
        $('#add_field_form .field:not(.has-conditional)').show();
        $('[name=field_type]').val('text').change();
        $('.add-field').removeAttr('data-edit-to').text('Add Field');

        formipay_sortable();
        
        setTimeout(() => {
            update_option_to_data_mapping('update');
        }, 1000);
    });

    $(document).on('change', '#customer_data-buyer_allow_choose_country_code', function() {
        update_option_to_data_mapping('update');
    });

    function update_option_to_data_mapping(initiation) {
        var fields = $('#preview-wrapper').find('input[type=hidden]');
        var options = [];
        $.each(fields, function(increment, field){
            var value = $(field).val();
            var config = JSON.parse(value);
            options.push(config);
        });
        var target = $('#customer_data').find('select');
        target.html('');
        target.append(`<option value="">${formipay_admin.config.datamapping.placeholder}</option>`);
        if(options.length > 0){
            $.each(options, function(increment, option){
                target.append(`<option value="${option.field_id}">${option.label}</option>`);
            });
        }
        if(initiation == 'initial'){
            $.ajax({
                type: 'post',
                url: formipay_admin.ajax_url,
                data: {
                    action: 'formipay_check_for_data_mapping_saved_value',
                    post: $('#post_ID').val(),
                    _wpnonce: formipay_admin.nonce
                },
                success: function(res) {
                    $.each(res, function(name, value){
                        if(value){
                            $(`[name="${name}"]`).attr('data-current-value', value).val(value);
                        }
                    });
                }
            });
        }else if(initiation == 'update'){
            $.each(target, function(increment, select){
                const current_value = $(select).attr('data-current-value');
                $(select).attr('data-current-value', current_value).val(current_value);
            })
        }
    }

    $(document).on('click', '.delete-preview-field', function(e){
        e.preventDefault();
        $(this).parents('.preview-field').remove();
        update_option_to_data_mapping('update');
    });

    $(document).on('click', '.edit-preview-field', function(e){
        e.preventDefault();
        
        // recondition all fields
        $('.option-field-toggle').prop('checked', false);
        $('.repeater-child-input:not(:first-child)').remove();
        $('.repeater-child-input:first-child').find('input').val('');
        // $('.repeater-child-input:first-child').find('.add-thumbnail').removeClass('text-info').addClass('text-white');

        var setup = $(this).closest('.preview-field').find('.formipay-field-setup').val();
        setup = JSON.parse(setup);
        console.log(setup);
        $.each(setup, function(x, y){
            if(x == 'field_options'){
                if(y.length > 0){
                    var first_repeater = $('.repeater-child-input:first-child')
                    var repeater_template = first_repeater.html();
                    var repeater_wrapper = $('.repeater-child-wrapper');
                    $.each(y, function(p, q){
                        repeater_wrapper.append(
                            `<div class="repeater-child-input d-flex justify-content-start align-items-start gap-2 my-2">
                            `+repeater_template+`
                            </div>`);
                        var repeater_target = $('.repeater-child-input:last-child');
                        repeater_target.find('.the_title').text(q.label);
                        repeater_target.find('.child-field-label').find('input').val(q.label);
                        repeater_target.find('.child-field-value').find('input').val(q.value);
                        repeater_target.find('.child-field-amount').find('input').val(q.amount);
                        if(q.qty == 'yes'){
                            repeater_target.find('.check-qty').val('yes').prop('checked', true);
                        }else{
                            repeater_target.find('.check-qty').val('no').prop('checked', false);
                        }
                        if('' !== q.image){
                            repeater_target.find('.field-image-id').val(q.image_id);
                            repeater_target.find('.field-image-url').val(q.image_url);
                            repeater_target.find('img').attr('src', q.image_url).removeClass('d-none');
                            repeater_target.find('.child-field-image').hide();
                            // repeater_target.find('.add-thumbnail').removeClass('text-white').addClass('text-info');
                        }
                        repeater_target.show();
                        first_repeater.hide();
                        first_repeater.remove();
                    });
                    $('.repeater-child-input:first-child').find('.open-option');
                }
            }else if(x == 'layout'){
                $('#add_field_form [name="option_grid_columns"]').val(y);
            }else{
                $('#add_field_form [name="' + x + '"]').val(y);
            }
        });

        $('#add_field_form [name=is_required]').prop('checked', setup.is_required === 'yes');
        // Handle show_toggle options
        if ('show_toggle' in setup) {

            if(setup.show_toggle.image === 'yes'){
                $('#repeater-child-0_thumbnail').trigger('click');
            }
            if(setup.show_toggle.value === 'yes'){
                $('#repeater-child-2_value').trigger('click');
            }
            if(setup.show_toggle.amount === 'yes'){
                $('#repeater-child-3_amount').trigger('click');
            }
        }
    
        formipay_sortable();
        // Trigger recondition and form change
        $('.formipay-builder-field[name=field_type]').trigger('change');

        $('.add-field').attr('data-edit-to', setup.field_id).text('Edit Field');
    });

    if( $('[name=daterange]').val() == '' ){
        $('[name=daterange]').daterangepicker({
            timePicker: true,
            startDate: moment().startOf('hour'),
            endDate: moment().startOf('hour').add(32, 'hour'),
            showDropdowns: true,
            timePicker24Hour: true, 
            locale: {
                format: 'D-M-Y HH:mm'
            }
        });
    }else{
        $('[name=daterange]').daterangepicker({
            timePicker: true,
            showDropdowns: true,
            timePicker24Hour: true, 
            locale: {
                format: 'D-M-Y HH:mm'
            }
        });
    }

    $(document).on('click', '[role=switch]', function(){
        var id = $(this).attr('id');
        if($(this).is(':checked')){
            $('#add_field_form [data-if-'+id+'=active]').show();
            $(this).val('no');
        }else{
            $('#add_field_form [data-if-'+id+'=active]').hide();
            $(this).val('yes');
        }
    });

    $(document).on('click change', '#add_field_form [type=radio]', function(){
        var id = $(this).attr('name');
        var value = $(this).val();
        $('#add_field_form [data-if-'+id+']').hide();
        if($(this).is(':checked')){
            $('#add_field_form [data-if-'+id+'='+value+']').show();
        }
    });

    $('[type=radio]').trigger('change');
    
    $(document).on('change', '.config-dropdown', function(){
        var id = $(this).attr('id');
        var value = $(this).val();
        var attr_value = $('#add_field_form [data-if-'+id+']');

        $('#add_field_form [data-if-'+id+']').hide();

        if(attr_value.length > 0){
            $.each(attr_value, function(x,y){
                var this_attr_value = $(y).attr('data-if-'+id);
                if(this_attr_value.indexOf('::') !== -1){
                    var split = this_attr_value.split('::');
                    if($.inArray(value, split) !== -1){
                        $(y).show();
                    }
                }else{
                    if(this_attr_value == value){
                        $(y).show();
                    }
                }
            });
        }
        
    });

    $('.config-dropdown').trigger('change');

    $(document).on('click', '.open-option', function(e){
        e.preventDefault();
        $(this).find('.bi').toggleClass('bi-arrow-up').toggleClass('bi-arrow-down');
        $(this).closest('.child-fields-wrapper').find('.child-field-wrapper').slideToggle();
        $(this).closest('.child-field-title').toggleClass('option-detail-opened');
    });

    // var all_checkbox = $('[type="checkbox"]');
    // if(all_checkbox.length > 0){
    //     $.each(all_checkbox, function(a,b){
    //         if($(b).val() == 'yes'){
    //             $(b).val('no').trigger('click');
    //         }
    //     });
    // }

    // function modify_payment_box_behavior() {

    //     var allbox = $('#payments multi_checkbox');
    //     var checkbox_input = $('.payments-payment input[type=checkbox]');
    //     var checked_value = [];
    //     if(checkbox_input.length > 0){
    //         $.each(checkbox_input, function(x, y){
    //             if($(y).is(':checked')){
    //                 checked_value.push($(y).val());
    //                 $('[data-field=wpcfto_addon_option_payment_'+$(y).val()+']').show();
    //             }else{
    //                 $('[data-field=wpcfto_addon_option_payment_'+$(y).val()+']').hide();
    //             }
    //         });
    //     }

    // }

    // setTimeout(() => {
    //     modify_payment_box_behavior();
    // }, 500);

    // $(document).on('click', '.payments-payment input[type=checkbox]', function(){
    //     modify_payment_box_behavior();
    // });

    $(document).on('mouseover', 'span.grab', function(){
        $(this).css('pointer', 'grab');
    });

    $(document).on('click', 'span.grab', function(){
        $(this).css('pointer', 'grabbing');
    });

    $(document).on('change blur', '.child-field-label input.formipay-builder-field', function(){
        $(this).closest('.child-fields-wrapper').find('.the_title').text($(this).val());
    });

    $(document).on('change', '#customer_data select', function() {
        var value = $(this).val();
        $(this).attr('data-current-value', value);
    });

});

// jQuery(function($){

    // setTimeout(() => {
    //     var autocomplete_fields = $('.wpcfto-box .autocomplete');
    //     if(autocomplete_fields.length > 0){
    //         $.each(autocomplete_fields, function(increment, field){
    //             var label = $(field).find('.wpcfto-field-aside__label').text();
    //             var placeholder = formipay_admin.config.autocomplete.placeholder.replace('{field_label}', label);
    //             var search_input = $(field).find('input');
    //             search_input.attr('placeholder', placeholder);
    //             search_input.parent().attr('data-input-placeholder', placeholder);
    //         });
    //     }
    // }, 1000);

    // $(document).on('mouseleave blur focusout', '.wpcfto-autocomplete-search input', function(){
    //     var placeholder = $(this).parent().attr('data-input-placeholder');
    //     setTimeout(() => {
    //         $(this).attr('placeholder', placeholder);
    //     }, 500);
    // });

    // $( document ).on( 'click', '.add-thumbnail', function( event ) {
        
    //     var gallery_items_frame;
    //     const $el = $( this );
    //     var target_field = $el.attr('data-field');
    //     var target_id = $el.siblings('.'+target_field+'-id');
    //     var target_url = $el.siblings('.'+target_field+'-url');
    //     var selected = target_id.val();
    //     var able_multiple = $el.attr('data-able-multiple');

    //     event.preventDefault();

    //     if ( gallery_items_frame ) {

    //         // Select the attachment when the frame opens
    //         gallery_items_frame.on( 'open', function() {
    //             var selection = gallery_items_frame.state().get( 'selection' );
    //             selection.reset( selected ? [ wp.media.attachment( selected ) ] : [] );
    //         });

    //         // Open the modal.
    //         gallery_items_frame.open();

    //         return;
    //     }

    //     // Create the media frame.
    //     gallery_items_frame = wp.media.frames.gallery_items = wp.media({
    //         // Set the title of the modal.
    //         title: 'Choose or upload media',
    //         button: {
    //             text: 'Select'
    //         },
    //         states: [
    //             new wp.media.controller.Library({
    //                 title: 'Choose or upload media',
    //                 filterable: 'all',
    //                 multiple: able_multiple
    //             })
    //         ]
    //     });

    //     // Select the attachment when the frame opens
    //     gallery_items_frame.on( 'open', function() {
    //         var selection = gallery_items_frame.state().get( 'selection' );
    //         selection.reset( selected ? [ wp.media.attachment( selected ) ] : [] );
    //     });

    //     gallery_items_frame.on( 'select', function() {
	// 		attachment = gallery_items_frame.state().get('selection').first().toJSON();
	// 		target_id.val( attachment.id );
    //         target_url.val( attachment.url );
    //         if(target_id.val() !== ''){
    //             // $el.removeClass('text-white').addClass('text-info d-none');
    //             if($el.hasClass('btn')){
    //                 $el.siblings('i').hide();
    //             }else{
    //                 $el.hide();
    //             }
    //             $el.siblings('img').removeClass('d-none').attr('src', attachment.url).show();
    //         }else{
    //             // $el.removeClass('text-info d-none').addClass('text-white');
    //             if($el.hasClass('btn')){
    //                 $el.siblings('i').show();
    //             }else{
    //                 $el.show();
    //             }
    //             $el.siblings('img').addClass('d-none').hide();
    //         }
	// 	});

    //     // Open the modal.
    //     gallery_items_frame.open();

    // });

    // $( document ).on( 'click', '.trumbowyg-button-group:has(.trumbowyg-insertImage-button)', function( event ) {
        
    //     var gallery_items_frame;

    //     event.preventDefault();

    //     // Create the media frame.
    //     gallery_items_frame = wp.media.frames.gallery_items = wp.media({
    //         // Set the title of the modal.
    //         title: 'Choose or upload media',
    //         button: {
    //             text: 'Select'
    //         },
    //         states: [
    //             new wp.media.controller.Library({
    //                 title: 'Choose or upload media',
    //                 filterable: 'all',
    //                 multiple: false
    //             })
    //         ]
    //     });

    //     gallery_items_frame.on( 'select', function() {
	// 		attachment = gallery_items_frame.state().get('selection').first().toJSON();
    //         var target_input_url = $('.trumbowyg-modal.trumbowyg-fixed-top .trumbowyg-input-html input');
    //         var target_confirm = $('.trumbowyg-modal.trumbowyg-fixed-top .trumbowyg-modal-submit');
    //         target_input_url.val( attachment.url );
    //         target_confirm.trigger('click');
            
	// 	});

    //     // Open the modal.
    //     gallery_items_frame.open();

    // });

// });