var nonce = brainxNinjaLocalizedData.nonce;
var form_id = brainxNinjaLocalizedData.form_id;
jQuery(document).ready(function ($) {
    setTimeout(function () {
        jQuery('.success_message').hide();
    }, 3000);

    // Get localized variables

    const fieldsData = brainxNinjaLocalizedData.fields_array;
    const requiredFields = brainxNinjaLocalizedData.required_fields;

    const formFields = {
        form1: fieldsData,
    };

    function loadFields(form) {
        const fieldsbrx_box = $("#fields-brx_box");
        fieldsbrx_box.empty();

        Object.entries(formFields[form]).forEach(([key, field]) => {
            const fieldElement = $(`<div class="draggable-item" data-key="${key}">${field}</div>`);
            fieldsbrx_box.append(fieldElement);
        });

        const formFieldsDiv = $('.form_fields');
        let previousOverflow;

        // Make draggable items draggable
        $(".draggable-item").draggable({
            revert: "invalid",
            helper: "clone",
            cursor: "move",
            cursorAt: {top: 0, left: 0},
            start: function (event, ui) {
                previousOverflow = formFieldsDiv.css('overflow');
                formFieldsDiv.css('overflow', 'visible');
                $(ui.helper).css("z-index", 1000);
            },
            stop: function () {
                formFieldsDiv.css('overflow', previousOverflow);
            },
        });
    }

    loadFields("form1");
    function upcheck_non_checked_values() {
        var tag = jQuery('input.istrueflase');
        tag.each(function (i, j) {
            if (jQuery(this).closest('.droppable ').hasClass('Checkbox')) {

            } else {
                jQuery(this).attr('checked', false);
                jQuery(this).prop('checked', false);
            }
        });
    }
    $(".droppable").droppable({
        accept: ".draggable-item",
        hoverClass: "drop-hover",
        drop: function (event, ui) {
            const droppedItem = $(ui.helper).clone().removeAttr("style").detach();
            $(this).empty().html(droppedItem).addClass("success");

            const removeButton = $('<button class="remove-btn">Entfernen</button>');
            const checkboxDiv = $(`
            <div class="istrueflasediv">
                <input type="checkbox" class="istrueflase" name="istrueflase" checked="" /> Kontrollkästchen(wahr/falsch)?
            </div>
        `);

            $(this).append(removeButton, checkboxDiv);

            // Ensure click event is only for .remove-btn, not the checkbox
            removeButton.on("click", function () {
                $(this).parent().empty().removeClass("success error")
                        .append('<input type="text" placeholder="Feld ausfüllen oder hinterlegen" class="custom-value">');
            });
            upcheck_non_checked_values();
        }
    });

    jQuery(document).on('click', '.remove-btn', function () {
        jQuery(this).closest('.droppable').removeClass('success error');
        jQuery(this).closest('.droppable').html('<input type="text" placeholder="Feld ausfüllen oder hinterlegen" class="custom-value">');
    });

    function showModal(message) {
        $("#modal-alert").find("p").text(message);
        $("#modal-alert").fadeIn();
    }

    $("#close-modal").click(function () {
        $("#modal-alert").fadeOut();
    });

    $("#get-mapping").click(function () {
        let mapping = {};
        let allFieldsValid = true;
        let required_field_values = {};
        let checkfields = {};
        $(".droppable").each(function () {
            const apiField = $(this).data("map-to");
            const mappedField = $(this).find(".draggable-item").data("key");
            const customValue = $(this).find(".custom-value").val();

            if (requiredFields.includes(apiField) && !mappedField && !customValue) {
                $(this).addClass("error");
                allFieldsValid = false;
            } else {
                required_field_values[apiField] = customValue;
                $(this).removeClass("error");
            }
            if (jQuery(this).find('.istrueflase').is(':checked')) {
                checkfields[apiField] = mappedField;
            }
            if (mappedField) {
                mapping[apiField] = mappedField;
            }
        });

        if (!allFieldsValid) {
            showModal("Bitte alle Pflichtfelder hinterlegen.");
            return;
        }

        jQuery.ajax({
            url: brainxNinjaLocalizedData.ajax_url,
            type: 'POST',
            data: {
                action: 'brainx_save_form_data_linking',
                mapping: mapping,
                required_field_values: required_field_values,
                checkfields: checkfields,
                form_id: form_id,
                nonce: nonce
            },
            success: function (response) {
                $('.success_message1').addClass('show');
                $('.brainx_success-toast').addClass('shownow');
                setTimeout(function () {
                    $('.success_message1').removeClass('show');
                    $('.brainx_success-toast').removeClass('shownow');
                }, 2000);
                load_field_mapping_ninja();
            },
            error: function (xhr, status, error) {
                load_field_mapping_ninja();
                console.error(error);
            },
        });
    });

    function load_field_mapping_ninja() {
        jQuery.ajax({
            url: brainxNinjaLocalizedData.ajax_url,
            type: 'POST',
            data: {
                action: 'brainx_load_field_mapping',
                form_id: form_id,
                type: 'ninja',
                nonce: nonce
            },
            success: function (response) {
                jQuery('.fields_mapping_for_api').html(response);
            },
            error: function (xhr, status, error) {
                console.error(error);
            },
        });
    }

    load_field_mapping_ninja();
});
