function success(message) {
    notifier.show('Well Done!', message, 'success', basePath + '../assets/admin/images/notification/ok-48.png', 4000);
}

function danger(message) {
    notifier.show('Sorry!', message, 'danger', basePath + '../assets/admin/images/notification/high_priority-48.png', 4000);
}

for (let instanceName in CKEDITOR.instances) {
    CKEDITOR.instances[instanceName].on('change', function () {
        let editor = CKEDITOR.instances[instanceName];
        let content = editor.getData().trim();
        let $textarea = $('#' + editor.name);
        let $feedback = $textarea.parent().find('.invalid-feedback');

        if (content === '') {
            $feedback.html("This field is required").show();
            formStatus = false; // Optional: if running inside a form submission
        } else {
            $feedback.html("").hide();
        }
    });
}


$("body").delegate("input.required", "keyup change", function () {
    if ($(this).val() == "") {
        $(this).parent().find(".invalid-feedback").html("This field is required").show();
    } else {
        $(this).parent().find(".invalid-feedback").html("").hide();
    }
});


var addForm = $('form#add-form');
$('.add-btn').on('click', function(e){
    e.preventDefault();
    var formId = $(this).parents('form').attr('id');
    var formStatus = true;
    $("form#" + formId + " input.required").each(function () {
        if ($(this).val() == "") {
            formStatus = false;
            $(this).parent().find(".invalid-feedback").html("This field is required").show();
        } else {
            $(this).parent().find(".invalid-feedback").html("").hide();
        }
    });

    if (typeof CKEDITOR !== "undefined") {
        for (let instanceName in CKEDITOR.instances) {
            let editor = CKEDITOR.instances[instanceName];
            let content = editor.getData().trim();
            let $textarea = $('#' + editor.name);
            let $feedback = $textarea.parent().find('.invalid-feedback');

            if (content === "") {
                $feedback.html("This field is required").show();
                formStatus = false;
            } else {
                $feedback.html("").hide();
            }
        }
    }

    if (!formStatus) {
        var $firstInvalidFeedback = $("#" + formId + " .invalid-feedback:visible").first();

        if ($firstInvalidFeedback.length) {
            var $firstInvalidField = $firstInvalidFeedback.closest('.form-group').find('input, select, textarea').first();
            if ($firstInvalidField.length) {
                if ($firstInvalidField.attr('id')) {
                    if ($firstInvalidField.attr('id') === 'short_description') {
                        // Focus CKEditor instance directly
                        CKEDITOR.instances[$firstInvalidField.attr('id')].focus();
                    }
                }
                $('html, body').animate({
                    scrollTop: $firstInvalidField.offset().top - 100
                }, 500);
                // Focus on the field
                $firstInvalidField.focus();
            }
        }
        return false;
    }

    CKEDITOR.instances.short_description.updateElement();
    var form_data = $("form#" + formId).serializeArray();
    $.ajax({
        type: "POST",
        url: basePath + "admin/our-strategic-alliance",
        data: form_data,

        beforeSend: function () {
            $('.modal-spinner').show();
        },
        success: function (data) {
            $("form#" + formId).find('.invalid-feedback').each(function(){
                $(this).empty().hide();
            });
            if (data.status) {
                $('#addModal').modal('hide');
                success(data.message);
            } else {
                danger(data.message);
            }
            setTimeout(function () {
                $('.modal-spinner').hide();
            }, 1000);
        },
        error: function (error) {
            $('.modal-spinner').hide();
            if (error.status === 422 && error.readyState === 4) {
                $("form#" + formId).find('.invalid-feedback').each(function(){
                    $(this).empty().hide();
                });
                var errors = $.parseJSON(error.responseText);
                let firstErrorKey = null;
                $.each(errors.errors, function (key, val) {
                    const errorElement = $("form#" + formId).find('#' + key + '_err');
                    errorElement.empty().append(val).show();
                    if (!firstErrorKey) {
                        firstErrorKey = key;
                    }
                });
                // Focus on the first field with error
                if (firstErrorKey) {
                    $("form#" + formId).find('[name="' + firstErrorKey + '"]').focus();
                }
            }
        },
        complete: function(){
            setInterval(function () {
                $('.modal-spinner').hide();
            }, 1000);
        }
    });
});
