var wppb_ffc_ajax_request = false;
let start_icon = '<svg width="10" height="10" viewBox="0 0 10 10" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M8.92357 2.51546L2.51541 2.51546L2.51541 8.92361L0.592965 9.56443L0.592965 0.593008L9.56438 0.593009L8.92357 2.51546Z" fill="white"/></svg>';
let end_icon = '<svg width="10" height="10" viewBox="0 0 10 10" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1.0764 7.48454L7.48456 7.48454L7.48456 1.07639L9.407 0.435574L9.407 9.40699L0.435586 9.40699L1.0764 7.48454Z" fill="white"/></svg>';

jQuery( document ).ready( function() {
    var form_id = wppb_ffc_getUrlParameter( 'page' );
    if( form_id === undefined ) {
        form_id = wppb_ffc_getUrlParameter( 'post' );
    }

     wppb_ffc_break_points_buttons( form_id );

    var data = {
        'action'				: 'wppb_ffc_check_break_points',
        'wppb_ffc_form_id'		: form_id
    };

    jQuery.post( wppb_ffc_data.ajaxUrl , data, function( response ) {
        wppb_ffc_add_break_points( response, form_id );
    } );


    jQuery( document ).on( 'click', '.wppb-ffc-break', function() {
        if( typeof form_id !== 'undefined' && ! wppb_ffc_ajax_request  ) {
            var id = jQuery( this ).parents( 'tr' ).attr( 'id' );

            if( jQuery( this ).attr( 'data-break-point' ) === 'yes' ) {
                jQuery( '#'+ id +'_break_point' ).remove();

                if( jQuery( this ).attr( 'interval-point' ) === 'start'  ){
                    jQuery( this ).attr( 'data-break-point', 'no' ).attr( 'interval-point', 'no' ).attr( 'title', wppb_ffc_data.breakpointStartTitle ).html( '<b class="wppb-ffc-add-sign">' + start_icon + '</b>' );
                }
                else if( jQuery( this ).attr( 'interval-point' ) === 'end' ){
                    jQuery( this ).attr( 'data-break-point', 'no' ).attr( 'interval-point', 'no' ).attr( 'title', wppb_ffc_data.breakpointEndTitle ).html( '<b class="wppb-ffc-add-sign">' + end_icon + '</b>' );
                    jQuery( this ).removeClass('wppb-ffc-break-end');
                }

                var data_remove = {
                    'action'				 : 'wppb_ffc_save_break_points',
                    'wppb_ffc_ajax_nonce'    : wppb_ffc_data.ajaxNonce,
                    'wppb_ffc_action'		 : 'remove',
                    'wppb_ffc_field_id'		 : jQuery( this ).parents( 'tr' ).find( '.wck-content li.row-id pre' ).text(),
                    'wppb_ffc_form_id'		 : form_id,
                    'wppb_ffc_interval_point': 'no'
                };

                wppb_ffc_ajax_request = true;
                jQuery.post( wppb_ffc_data.ajaxUrl , data_remove, function() {
                    wppb_ffc_ajax_request = false;
                } );
                wppb_ffc_check_break_points_message();

            } else {
                if(  ( hasPreviousBreakPoint( this, 'start' ) && hasNextBreakPoint( this, 'end' ) ) || jQuery(this).closest('tr').hasClass('element_type_language')){
                    return;
                }
                else {
                    var interval_point;

                    if ( hasPreviousBreakPoint(this, 'start') ) {
                        jQuery(this).attr('interval-point', 'end');
                        interval_point = 'end';
                    }

                    if ( hasPreviousBreakPoint(this, 'end') || ( !hasPreviousBreakPoint(this,'end') && !hasPreviousBreakPoint(this,'start') ) ) {
                        jQuery(this).attr('interval-point', 'start');
                        interval_point = 'start';
                    }

                    if ( !hasPreviousBreakPoint(this, 'start') && !hasPreviousBreakPoint(this, 'end') && !hasNextBreakPoint(this, 'start') && !hasNextBreakPoint(this, 'end') ) {
                        jQuery(this).attr('interval-point', 'start');
                        interval_point = 'start';
                    }

                    if (jQuery(this).attr('interval-point') === 'start') {
                        jQuery(this).attr('data-break-point', 'yes').attr('title', wppb_ffc_data.breakpointRemoveStartTitle).css('display', 'block').html('<b class="wppb-ffc-remove-sign">' + start_icon + '</b>');
                    } else if (jQuery(this).attr('interval-point') === 'end') {
                        jQuery(this).attr('data-break-point', 'yes').attr('title', wppb_ffc_data.breakpointRemoveEndTitle).css('display', 'block').addClass('wppb-ffc-break-end').html('<b class="wppb-ffc-remove-sign-end">' + end_icon + '</b>');
                    }


                    var data_add = {
                        'action': 'wppb_ffc_save_break_points',
                        'wppb_ffc_ajax_nonce': wppb_ffc_data.ajaxNonce,
                        'wppb_ffc_action': 'add',
                        'wppb_ffc_field_id': jQuery(this).parents('tr').find('.wck-content li.row-id pre').text(),
                        'wppb_ffc_form_id': form_id,
                        'wppb_ffc_interval_point': interval_point
                    };

                    wppb_ffc_ajax_request = true;
                    jQuery.post(wppb_ffc_data.ajaxUrl, data_add, function () {
                        wppb_ffc_ajax_request = false;
                    });
                    wppb_ffc_check_break_points_message();

                    if( typeof wppb_msf_compatibility_ffc === 'function' ){
                        wppb_msf_compatibility_ffc( form_id );
                    }
                }
            }

            handle_interval_highlight();
        } else if( wppb_ffc_ajax_request ) {
            alert( wppb_ffc_data.alertAjaxRequestInProcess );
        } else {
            alert( wppb_ffc_data.alertUnsavedForm );
        }
    } );

} );


function wppb_ffc_add_break_points( break_points, form_id ) {
    if( break_points !== 'not_found' && break_points !== 'NULL' ) {
        var break_points_array;

        if( typeof break_points != 'object' ) {
            break_points_array = JSON.parse( break_points );
        } else {
            break_points_array = break_points;
        }


        jQuery.each( break_points_array, function( key, value ) {

            jQuery( '.mb-table-container tbody' ).find( 'tr' ).each( function() {
                if( jQuery( this ).find( '.wck-content li.row-id pre' ).text() == key && !jQuery(this).hasClass('element_type_language') ) {

                    if( value === "start" ){
                        jQuery( this ).find( '.wppb-ffc-break' ).attr( 'data-break-point', 'yes' ).attr( 'interval-point', 'start' ).attr( 'title', wppb_ffc_data.breakpointRemoveStartTitle ).css( 'display', 'block' ).html( '<b class="wppb-ffc-remove-sign">' + start_icon + '</b>' );
                    }
                    else if( value === "end" ){
                        jQuery( this ).find( '.wppb-ffc-break' ).attr( 'data-break-point', 'yes' ).attr( 'interval-point', 'end' ).attr( 'title', wppb_ffc_data.breakpointRemoveEndTitle ).css('display', 'block').addClass('wppb-ffc-break-end').html( '<b class="wppb-ffc-remove-sign-end">' + end_icon + '</b>' );
                    }
                }
            } );
        } );

        handle_interval_highlight();
        wppb_ffc_check_break_points_message();

        if( typeof wppb_msf_compatibility_ffc === 'function' ){
            wppb_msf_compatibility_ffc( form_id );
        }
    }
}

function handle_interval_highlight(){
    jQuery( '.mb-table-container tbody' ).find( 'tr' ).each( function() {
        if( ( hasPreviousBreakPoint( this, 'start' ) && hasNextBreakPoint( this, 'end' ) ) || jQuery( this ).find( '.wppb-ffc-break' ).attr( 'interval-point' ) === 'start' || jQuery( this ).find( '.wppb-ffc-break' ).attr( 'interval-point' ) === 'end' ){
            jQuery( this ).find( '.wck-number' ).addClass('background-interval');
        }
        else{
            jQuery( this ).find( '.wck-number' ).removeClass('background-interval');
        }
    });

}

function wppb_ffc_break_points_validation(){
    var table_elements = jQuery( 'span.wppb-ffc-break' );
    var is_valid = true;

    table_elements.each( function( index ) {
        if( jQuery( this ).attr( 'data-break-point' ) === 'yes' && jQuery( this ).attr( 'interval-point' ) === 'start' && !hasNextBreakPoint( this, 'end' ) ){
            is_valid = false;
            jQuery( this ).addClass('wppb-ffc-break-unpaired');
        }
        else if( jQuery( this ).attr( 'data-break-point' ) === 'yes' && jQuery( this ).attr( 'interval-point' ) === 'start' && hasNextBreakPoint( this, 'end' ) ){
            jQuery( this ).removeClass('wppb-ffc-break-unpaired');
        }

        if( jQuery( this ).attr( 'data-break-point' ) === 'yes' && jQuery( this ).attr( 'interval-point' ) === 'end' && !hasPreviousBreakPoint( this, 'start' ) ){
            is_valid = false;
            jQuery(this).attr('class', 'wppb-ffc-break-end-unpaired ' + jQuery(this).attr('class'));
        }
        else if( jQuery( this ).attr( 'data-break-point' ) === 'yes' && jQuery( this ).attr( 'interval-point' ) === 'end' /*&& hasPreviousBreakPoint( this, 'start' )*/ ){
            jQuery( this ).removeClass('wppb-ffc-break-end-unpaired');
        }
    });

    return is_valid;
}

function wppb_ffc_check_break_points_message(){
    if( !wppb_ffc_break_points_validation() ){
        jQuery('#ffc-breakpoint-message').css( 'display', 'block' );
    }
    else{
        jQuery('#ffc-breakpoint-message').css( 'display', 'none' );
    }
}

async function wppb_ffc_remove_unpaired_break_points_after_reorder(form_id) {
    if ( typeof form_id !== 'undefined' && !wppb_ffc_ajax_request ) {
        var table_elements = jQuery('span.wppb-ffc-break').toArray();

        for (const element of table_elements) {
            await processBreakPoint(element, form_id);
        }
    }

    handle_interval_highlight();
}

async function processBreakPoint(element, form_id) {
    return new Promise((resolve) => {
        var $element = jQuery(element);
        var id = $element.parents('tr').attr('id');

        if ( $element.attr('data-break-point') === 'yes' && $element.attr('interval-point') === 'start' && !hasNextBreakPoint(element, 'end') ) {
            jQuery('#' + id + '_break_point').remove();

            $element
                .attr('data-break-point', 'no')
                .attr('interval-point', 'no')
                .attr('title', wppb_ffc_data.breakpointStartTitle)
                .html('<b class="wppb-ffc-add-sign">' + start_icon + '</b>')
                .fadeOut(0)
                .removeClass('wppb-ffc-break-unpaired');

            var data_remove = {
                action: 'wppb_ffc_save_break_points',
                wppb_ffc_ajax_nonce: wppb_ffc_data.ajaxNonce,
                wppb_ffc_action: 'remove',
                wppb_ffc_field_id: $element.parents('tr').find('.wck-content li.row-id pre').text(),
                wppb_ffc_form_id: form_id,
                wppb_ffc_interval_point: 'no'
            };

            wppb_ffc_ajax_request = true;
            jQuery.post(wppb_ffc_data.ajaxUrl, data_remove, function () {
                wppb_ffc_ajax_request = false;
                resolve(); // Resolve the promise when the AJAX call completes
            });

            wppb_ffc_check_break_points_message();
        } else if ( $element.attr('data-break-point') === 'yes' && $element.attr('interval-point') === 'end' && !hasPreviousBreakPoint(element, 'start') ) {
            jQuery('#' + id + '_break_point').remove();

            $element
                .attr('data-break-point', 'no')
                .attr('interval-point', 'no')
                .attr('title', wppb_ffc_data.breakpointEndTitle)
                .html('<b class="wppb-ffc-add-sign">' + start_icon + '</b>')
                .fadeOut(0)
                .removeClass('wppb-ffc-break-end')
                .removeClass('wppb-ffc-break-end-unpaired');

            var data_remove = {
                action: 'wppb_ffc_save_break_points',
                wppb_ffc_ajax_nonce: wppb_ffc_data.ajaxNonce,
                wppb_ffc_action: 'remove',
                wppb_ffc_field_id: $element.parents('tr').find('.wck-content li.row-id pre').text(),
                wppb_ffc_form_id: form_id,
                wppb_ffc_interval_point: 'no'
            };

            wppb_ffc_ajax_request = true;
            jQuery.post(wppb_ffc_data.ajaxUrl, data_remove, function () {
                wppb_ffc_ajax_request = false;
                resolve();
            });

            wppb_ffc_check_break_points_message();
        } else {
            resolve();
        }
    });
}

function wppb_ffc_break_points_buttons( form_id ) {
    var table_elements = jQuery( 'span.wppb-ffc-break' );

    table_elements.each( function( index ) {
        if( jQuery( this ).closest( 'tr' ).find( 'td.wck-content #wppb-login-email-nag, td.wck-content #wppb-display-name-nag' ).length !== 1 ) {
            jQuery( this ).appendTo( jQuery( this ).closest( 'tr' ).find( 'td.wck-number' ) );
        } else if( jQuery( this ).attr( 'data-break-point' ) === 'yes' ) {
            jQuery( this ).attr( 'data-break-point', 'no' );

           if( jQuery( this ).attr( 'interval-point' ) === 'end' ){
                jQuery( this ).removeClass('wppb-ffc-break-end');
            }

            jQuery( this ).attr( 'interval-point', 'no' );

            var data_remove = {
                'action'				 : 'wppb_ffc_save_break_points',
                'wppb_ffc_ajax_nonce'    : wppb_ffc_data.ajaxNonce,
                'wppb_ffc_action'		 : 'remove',
                'wppb_ffc_field_id'		 : jQuery( this ).parents( 'tr' ).find( '.wck-content li.row-id pre' ).text(),
                'wppb_ffc_form_id'		 : form_id,
                'wppb_ffc_interval_point': 'no'
            };

            jQuery.post( wppb_ffc_data.ajaxUrl , data_remove, function() {} );
        }
    } );
    onHoverInOut();
}

function onHoverInOut(){

    jQuery( 'tr.added_fields_list' ).on('mouseenter', function() {
        let $rows = jQuery('tr.added_fields_list');
        let lastIndex = $rows.length - 1;
        let index = $rows.index(jQuery( this ));
        let $nextRow = $rows.eq(index + 1);
        let $previousRow = $rows.eq(index - 1);

        if( ( index === 0 && $nextRow.find('span.wppb-ffc-break').attr('interval-point') === 'start' ) || ( index === lastIndex && $previousRow.find('span.wppb-ffc-break').attr('interval-point') === 'end' ) ){
            return;
        }
        else{
            if( !( hasPreviousBreakPoint( this, 'start' ) && hasNextBreakPoint( this, 'end' ) ) && !jQuery(this).hasClass('element_type_language') ){
                if( hasPreviousBreakPoint(this, 'start') && !hasNextBreakPoint(this, 'end') )
                    jQuery( this ).find( 'span.wppb-ffc-break' ).addClass('wppb-ffc-break-has-start');

                jQuery( this ).find( 'span.wppb-ffc-break' ).fadeIn( 0 );
            }

            jQuery( this ).find( '.wppb-ffc-break b' ).html( start_icon );

            jQuery( this ).find( '.wppb-ffc-break.wppb-ffc-break-has-start b' ).html( end_icon );

            if( jQuery( this ).find('span.wppb-ffc-break').attr('interval-point') === 'start' ){
                jQuery( this ).find('.wppb-ffc-break b').attr('title', wppb_ffc_data.breakpointRemoveStartTitle);
            }
            else if( jQuery( this ).find('span.wppb-ffc-break').attr('interval-point') === 'end' ){
                jQuery( this ).find('.wppb-ffc-break.wppb-ffc-break-has-start b').attr('title', wppb_ffc_data.breakpointRemoveEndTitle);
            }
            else if( jQuery( this ).find('span.wppb-ffc-break').attr('interval-point') === 'no' || jQuery( this ).find('span.wppb-ffc-break').attr('interval-point') === undefined ){
                jQuery( this ).find('.wppb-ffc-break b').attr('title', wppb_ffc_data.breakpointStartTitle);
                jQuery( this ).find('.wppb-ffc-break.wppb-ffc-break-has-start b').attr('title', wppb_ffc_data.breakpointEndTitle);
            }
        }

        }
    );
    jQuery( 'tr.added_fields_list' ).on('mouseleave', function() {
            if( jQuery( this ).find( 'span.wppb-ffc-break' ).attr( 'data-break-point' ) !== 'yes' ) {
                jQuery( this ).find( 'span.wppb-ffc-break' ).fadeOut( 0 ).removeClass('wppb-ffc-break-has-start');
            }
        }
    );

}

function wppb_ffc_getUrlParameter( wppbParam ) {
    var wppbPageURL = decodeURIComponent( window.location.search.substring( 1 ) ),
        wppbURLVariables = wppbPageURL.split( '&' ),
        wppbParameterName,
        i;

    for( i = 0; i < wppbURLVariables.length; i++ ) {
        wppbParameterName = wppbURLVariables[i].split( '=' );

        if( wppbParameterName[0] === wppbParam ) {
            return wppbParameterName[1] === undefined ? true : wppbParameterName[1];
        }
    }
}

function hasPreviousBreakPoint( currentElement, intervalPoint ) {
    let previousRows = jQuery(currentElement).closest('tr').prevAll();

    for ( let i = 0; i < previousRows.length; i++ ) {
        let breakpoint = jQuery(previousRows[i]).find('.wppb-ffc-break[data-break-point="yes"]');

        if ( breakpoint.length > 0 ) {
            return breakpoint.attr('interval-point') === intervalPoint;
        }
    }

    return false;
}

function hasNextBreakPoint( currentElement, intervalPoint ) {
    let nextRows = jQuery(currentElement).closest('tr').nextAll();

    for ( let i = 0; i < nextRows.length; i++ ) {
        let breakpoint = jQuery(nextRows[i]).find('.wppb-ffc-break[data-break-point="yes"]');

        if ( breakpoint.length > 0)  {
            return breakpoint.attr('interval-point') === intervalPoint;
        }
    }

    return false;
}
