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 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
                    }],
                },
                ai_review_prompt: {
                    type: 'textarea',
                    dependsOn: [{
                        field: 'ai_review_enabled',
                        value: true
                    }],
                },
            }
        };

        new window.FormDependencyHandler(dependencies);
    }

    // Wait for Vue component to be initialized, then extend its validation function
    var checkVueComponent = function() {
        var vueApp = document.querySelector('#wpuf-form-builder').__vue__;
        if (vueApp && vueApp.validate_form_before_submit) {
            // Store reference to the original validation function
            var originalValidation = vueApp.validate_form_before_submit;

            // Extend the Vue component's validation function directly
            vueApp.validate_form_before_submit = function() {
                // Call the original validation first
                var isValid = originalValidation.call(this);

                // If original validation failed, stop here
                if (!isValid) {
                    return false;
                }

                // Add AI review validation
                var aiReviewEnabled = $('[name="wpuf_settings[ai_review_enabled]"]').is(':checked');

                if (aiReviewEnabled) {
                    var aiReviewPrompt = $('[name="wpuf_settings[ai_review_prompt]"]').val();

                    if (!aiReviewPrompt || aiReviewPrompt.trim() === '') {
                        this.validation_error_msg = 'AI Review Criterion is required when AI Review is enabled.';
                        return false;
                    }

                    // Check character limit (500 characters)
                    if (aiReviewPrompt.length > 500) {
                        this.validation_error_msg = 'AI Review Criterion must not exceed 500 characters.';
                        return false;
                    }
                }

                return true;
            };

            return true;
        }
        return false;
    };

    // Try immediately
    if (!checkVueComponent()) {
        // If not ready, wait a bit and try again
        setTimeout(function() {
            checkVueComponent();
        }, 1000);
    }
});
