jQuery(document).ready(function ($) {
    'use strict';

    /**
     * Only proceed if current page is a 'Post Forms' form builder page
     */
    if (!$('#wpuf-form-builder.wpuf-form-builder-post').length) {
        return;
    }

    var has_missing_country_list = function (fields) {
        var missing = false;

        var scan_fields = function (field_group) {
            if (missing || !_.isArray(field_group)) {
                return;
            }

            _.each(field_group, function (field) {
                if (missing || !field) {
                    return;
                }

                // Check country_list field
                if (field.country_list) {
                    var visibility = field.country_list.country_list_visibility_opt_name || 'all';
                    if ('show' === visibility && !field.country_list.country_select_show_list.length) {
                        missing = true;
                        return;
                    }
                    if ('hide' === visibility && !field.country_list.country_select_hide_list.length) {
                        missing = true;
                        return;
                    }
                }

                // Check address.country_select field
                if (field.address && field.address.country_select) {
                    var visibility = field.address.country_select.country_list_visibility_opt_name || 'all';
                    if ('show' === visibility && !field.address.country_select.country_select_show_list.length) {
                        missing = true;
                        return;
                    }
                    if ('hide' === visibility && !field.address.country_select.country_select_hide_list.length) {
                        missing = true;
                        return;
                    }
                }

                // Scan nested fields
                if (field.inner_fields && _.isArray(field.inner_fields)) {
                    scan_fields(field.inner_fields);
                }
            });
        };

        scan_fields(fields);
        return missing;
    };

    if (window.wpuf_forms_mixin_root && window.wpuf_forms_mixin_root.methods && _.isFunction(window.wpuf_forms_mixin_root.methods.validate_form_before_submit)) {
        var original_validate_form_before_submit = window.wpuf_forms_mixin_root.methods.validate_form_before_submit;

        window.wpuf_forms_mixin_root.methods.validate_form_before_submit = function () {
            var is_valid = original_validate_form_before_submit.call(this);
            if (!is_valid) {
                return false;
            }

            if (has_missing_country_list(this.form_fields)) {
                this.validation_error_msg = wpuf_form_builder.i18n.any_of_three_needed;
                return false;
            }

            return true;
        };
    }

    var changeExpirationFieldVisibility = function(e){
        var checkbox_obj = e.target ? $(e.target) : $(e);
        checkbox_obj.is(':checked') ? $('.wpuf_expiration_field').show() : $('.wpuf_expiration_field').hide();
    };

    var setTimeExpiration = function(e){
        var timeArray = {
            'day' : 30,
            'month' : 12,
            'year': 100
        };

        $('#wpuf-expiration_time_value').html('');
        var timeVal = e.target?$(e.target).val():$(e).val();

        for(var time = 1; time <= timeArray[timeVal]; time++){
            $('#wpuf-expiration_time_value').append('<option value="'+ time +'" >'+ time +'</option>');
        }
    };

    // on page load
    changeExpirationFieldVisibility(':checkbox#wpuf-enable_post_expiration');
    //on change enable expiration check status
    $('#wpuf-enable_post_expiration').on('click', changeExpirationFieldVisibility);
    //on change expiration type drop down
    $('#wpuf-expiration_time_type').on('change', setTimeExpiration);

    const multistep = $('#enable_multistep');
    const post_expiration = $('#enable_post_expiration');

    // initial show/hide fields when page loads
    if ( multistep.is(':checked') ) {
        show_multistep_cond_fields();
    } else {
        hide_multistep_cond_fields();
    }

    if ( post_expiration.is(':checked') ) {
        show_post_expiration_cond_fields();
    } else {
        hide_post_expiration_cond_fields();
    }

    multistep.on('change', function() {
        if ( $(this).is(':checked') ) {
            show_multistep_cond_fields();
        } else {
            hide_multistep_cond_fields();
        }
    });

    post_expiration.on('change', function() {
        if ( $(this).is(':checked') ) {
            show_post_expiration_cond_fields();
        } else {
            hide_post_expiration_cond_fields();
        }
    });

    function show_multistep_cond_fields() {
        $('#multistep_progressbar_type').parents('.wpuf-input-container').fadeIn();
        $('#ms_ac_txt_color').parents('.wpuf-input-container').fadeIn();
        $('#ms_active_bgcolor').parents('.wpuf-input-container').fadeIn();
        $('#ms_bgcolor').parents('.wpuf-input-container').fadeIn();
    }

    function hide_multistep_cond_fields() {
        $('#multistep_progressbar_type').parents('.wpuf-input-container').fadeOut();
        $('#ms_ac_txt_color').parents('.wpuf-input-container').fadeOut();
        $('#ms_active_bgcolor').parents('.wpuf-input-container').fadeOut();
        $('#ms_bgcolor').parents('.wpuf-input-container').fadeOut();
    }

    function show_post_expiration_cond_fields() {
        $('#expiration_time_value').parents('.wpuf-input-container').fadeIn();
        $('#expired_post_status').parents('.wpuf-input-container').fadeIn();
        $('#enable_mail_after_expired').parents('.wpuf-input-container').fadeIn();
        $('#post_expiration_message').parents('.wpuf-input-container').fadeIn();
    }

    function hide_post_expiration_cond_fields() {
        $('#expiration_time_value').parents('.wpuf-input-container').fadeOut();
        $('#expired_post_status').parents('.wpuf-input-container').fadeOut();
        $('#enable_mail_after_expired').parents('.wpuf-input-container').fadeOut();
        $('#post_expiration_message').parents('.wpuf-input-container').fadeOut();
    }

    // load only post form settings related dependencies
    if (wpuf_form_builder.form_type === 'wpuf_forms') {
        const dependencies = {
            // Fields and their show/hide conditions
            fields: {
                notification_edit_to: {
                    type: 'text',
                    dependsOn: [{
                        field: 'notification_edit',
                        value: true
                    }],
                },
                notification_edit_subject: {
                    type: 'text',
                    dependsOn: [{
                        field: 'notification_edit',
                        value: true
                    }],
                },
                notification_edit_body: {
                    type: 'text',
                    dependsOn: [{
                        field: 'notification_edit',
                        value: true
                    }],
                },
                post_expiration_message: {
                    type: 'textarea',
                    dependsOn: [{
                        field: 'enable_mail_after_expired',
                        value: true
                    }],
                },
                n8n_webhook_url: {
                    type: 'text',
                    dependsOn: [{
                        field: 'enable_n8n',
                        value: true
                    }],
                },
                ai_review_prompt: {
                    type: 'textarea',
                    dependsOn: [{
                        field: 'ai_review_enabled',
                        value: true
                    }],
                },
            }
        };

        new window.FormDependencyHandler(dependencies);
    }
});
