jQuery(document).ready(function ($) {
    // Sortable on top-level field groups only
    $(".field-catcher").sortable({
        items: "> .form-group.ui-state-default",
        update: function () {
            normalizeFieldIndexes();
            ai_app_onsite_drag_data_save_database();
        }
    }).disableSelection();

    function updateFieldOrder() {
        $(".field-catcher > .form-group.ui-state-default").each(function (index) {
            $(this).attr("field_order", index);
        });
    }

    function logDivPositions() {
        $(".field-catcher > .form-group.ui-state-default").each(function (index) {
            var position = $(this).index();
            // console.log('Field', index, 'at position', position);
        });
    }

    $(".field-catcher").disableSelection();
    initAutoFieldIdGenerator();
});

function normalizeFieldIndexes() {
    jQuery(".field-catcher > .form-group.ui-state-default").each(function (newIndex) {

        // Fix field_order attribute
        jQuery(this).attr("field_order", newIndex);

        // Fix all ID attributes inside the group
        jQuery(this).find('[id]').each(function () {
            this.id = this.id.replace(/\d+$/, newIndex);
        });

        // Fix all name attributes
        jQuery(this).find('[name]').each(function () {
            this.name = this.name.replace(/\d+$/, newIndex);
        });
    });
}

/* --------------------------------------------------------------------------
   Helpers for error handling
--------------------------------------------------------------------------- */

function getErrorElementFromInput(inputEl) {
    if (!inputEl) return null;

    var parent = inputEl.closest('.col-ai-3, .col-ai-4, .col-ai-2, .col-ai-12, .full-width, .form-group') || inputEl.parentElement;
    if (!parent) return null;

    var errorEl = parent.querySelector('.fields-error');
    if (!errorEl && inputEl.nextElementSibling && inputEl.nextElementSibling.classList.contains('fields-error')) {
        errorEl = inputEl.nextElementSibling;
    }

    return errorEl;
}

function attachClearOnInput(inputEl) {
    if (!inputEl || inputEl._hasClearHandler) return;

    var errorEl = getErrorElementFromInput(inputEl);
    inputEl.addEventListener('input', function () {
        if (errorEl) errorEl.textContent = '';
    });

    inputEl._hasClearHandler = true;
}

/* --------------------------------------------------------------------------
   ID generator
--------------------------------------------------------------------------- */

// Auto-generate Field ID from Label input (with manual override support)
function initAutoFieldIdGenerator() {
    jQuery(document).on('keyup', '.field-label-gt', function () {
        var $labelInput = jQuery(this);
        var labelValue = $labelInput.val().trim();
        var $formGroup = $labelInput.closest('.form-group.ui-state-default');
        if ($formGroup.length === 0) return;

        var $fieldIdInput = $formGroup.find('.field-id-gt');
        if ($fieldIdInput.length === 0) return;

        // Skip if user has manually overridden the ID (marked via data attribute)
        if ($fieldIdInput.data('manual-override') === true) return;

        // Generate a clean, lowercase, safe ID slug
        var generatedId = labelValue
            .toLowerCase()
            .replace(/[^a-z0-9\s_-]/g, '') // remove invalid chars
            .trim()
            .replace(/\s+/g, '_');         // spaces → underscores

        $fieldIdInput.val(generatedId);
    });

    // Detect manual overrides on Field ID inputs
    jQuery(document).on('input', '.field-id-gt', function () {
        var $idInput = jQuery(this);
        if ($idInput.val().trim() !== '') {
            $idInput.data('manual-override', true);
        } else {
            $idInput.data('manual-override', false);
        }
    });
}

/* --------------------------------------------------------------------------
   Utils
--------------------------------------------------------------------------- */

function generateAlphanumericString() {
    var alphanumericChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var result = '';

    for (var i = 0; i < 12; i++) {
        var randomIndex = Math.floor(Math.random() * alphanumericChars.length);
        result += alphanumericChars.charAt(randomIndex);
    }

    return result;
}

/* --------------------------------------------------------------------------
   Add / Delete field
--------------------------------------------------------------------------- */

// Function to handle adding a new field (free version: max 4 fields)
function addField() {
    var fieldCatcher = document.querySelector(".field-catcher");
    if (!fieldCatcher) return;

    // Count only top-level groups
    var fieldCount = jQuery(".field-catcher > .form-group.ui-state-default").length;
    if (fieldCount >= 4) {
        Swal.fire({
            icon: "error",
            title: "Limit Reached",
            text: "You need to upgrade the Plan to add the fields!",
        });
        return;
    }

    var newField = document.createElement("div");
    newField.classList.add("form-group", "ui-state-default");

    var fieldId = fieldCount;
    var uniqueID = generateAlphanumericString();
    newField.setAttribute('field_order', fieldId);

    newField.innerHTML =
        ` 
        <div class="field-row top">
            <div class="col-ai-3">
                <label class="d-block fs-medium-14 mb-only-4 form-label">
                    Type <span class="mk-red">*</span></label>
                <select class="border" id="filed_creator_${fieldId}" name="filed_creator_${fieldId}" onchange="createDropdown(${fieldId})">
                    <option value="textbox">Textbox</option>
                    <option value="textarea">Textarea</option>
                    <option value="number">Number</option>
                    <option value="email">Email</option>
                    <option value="dropdown">Drop-down</option>
                </select>
                <p id="filed_creator_${fieldId}_error" class="fields-error"></p>
                <input type="hidden" id="field_unique_id_${fieldId}" value="${uniqueID}">
            </div>  
            <div class="col-ai-4">
                <label class="d-block fs-medium-14 mb-only-4  form-label ">Label <span class="mk-red">*</span></label>
                <input type="text" name="field-label-${fieldId}" id="field_label_${fieldId}" class="border field-label-gt" value="">
                <p id="field_label_${fieldId}_error" class="fields-error"></p>
            </div>  
            <div class="col-ai-4">
                <label class="d-block fs-medium-14 mb-only-4  form-label">ID <span class="mk-red">*</span></label>
                <input type="text" name="field-id-${fieldId}" id="field_id_${fieldId}" class="border  field-id-gt" value="">
                <p id="field_id_${fieldId}_error" class="fields-error"></p>
            </div>  
            <div class="col-ai-2" id="maxium-char_${fieldId}">
                <label class="d-block fs-medium-14 mb-only-4  form-label">
                    Max Char <span class="mk-red">*</span>
                </label>
                <input type="text" name="field-maxchar-${fieldId}" id="field_maxchar_${fieldId}" class="border  field-maxchar-gt field_maxchar-gt_${fieldId}" value="80">
                <p id="field_maxchar_${fieldId}_error" class="fields-error"></p> 
            </div>
            <div class="col-ai-1">
               <label class="assets-icon-center-label"> 
                    <span class="grab-icon">
                        <div class="assets-grab-icon"></div>
                    </span>
               </label>
                <p class="ai-remove-sec assets-icon-center">
                    <button type="button" data-uid="${uniqueID}" onclick="deleteFieldSection(this)">
                        <div class="assets-delete-icon"></div>
                    </button>
                </p>
            </div>  
        </div>
        <div class="field-row bottm" id="field_sampl_text_${fieldId}">
            <div class="col-ai-12">
                <label class="d-block fs-medium-14 mb-only-4 form-label">
                    Field Sample Text
                </label>
                <input type="text" name="field-sample-text-${fieldId}" id="field_sample_text_${fieldId}" class="full-width border field-sample-text-${fieldId}" value="">
            </div>
        </div>
        <div class="field-row input-check-row mt-3">
            <div class="form-group">
                <input type="checkbox" id="section_required_${fieldId}" name="section-required-${fieldId}" value="">
                <label class="fs-medium-14" for="section_required_${fieldId}"> Required Field</label>
            </div>
            <div class="form-group include-in-email-checkbox">
                <input type="checkbox" id="include_in_email_${fieldId}" name="include-in-email-${fieldId}" value="" checked>
                <label class="fs-medium-14" for="include_in_email_${fieldId}"> Include in export/email</label>
            </div>
        </div>
    `;

    fieldCatcher.appendChild(newField);
    // Apply initial visibility logic for this new group
    hideMaxCharIfDropdown();
}

// Function to handle deleting a field section
function deleteFieldSection(e) {
    var deleteNonce = myPluginAjax.deleteNonce;
    var uniqueID = jQuery(e).attr('data-uid');

    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                jQuery(e).closest(".form-group.ui-state-default").remove();
            } else {
                console.error("Failed to save data");
            }
        }
    };

    xhr.open("POST", myPluginAjax.ajaxurl, true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    var data = "action=ai_app_onsite_delete_field_selector&field_uniqueid=" +
        encodeURIComponent(uniqueID) +
        '&ai_app_onsite_field_selector_nonce_field_delete=' + encodeURIComponent(deleteNonce);

    xhr.send(data);
}

/* --------------------------------------------------------------------------
   Save field data (FULLY REFACTORED)
--------------------------------------------------------------------------- */

function ai_app_onsite_save_ai_app_fieldselector_data() {
    var messageContainer = document.getElementById('field-selector-msg-container');

    var formGroups = document.querySelectorAll(".field-catcher > .form-group.ui-state-default");
    if (formGroups.length === 0) {
        messageContainer.innerHTML = '<span style="color: red;">No field shown, please Add a field.</span>';
        setTimeout(function () { messageContainer.innerHTML = ''; }, 3000);
        return;
    }

    // Clear previous errors
    document.querySelectorAll('.fields-error').forEach(function (error) {
        error.textContent = '';
    });

    var formDataArray = [];
    var hasErrors = false;

    formGroups.forEach(function (group, idx) {
        var order = jQuery(group).attr('field_order') || idx;

        var fieldCreator    = group.querySelector("select[id^='filed_creator_']");
        var fieldLabel      = group.querySelector(".field-label-gt");
        var fieldId         = group.querySelector(".field-id-gt");
        var fieldMaxchar    = group.querySelector("input[id^='field_maxchar_']");
        var fieldDropdown   = group.querySelector("input[id^='dropdown_options_']");
        var fieldSampleText = group.querySelector("input[id^='field_sample_text_']");
        var fieldUnique     = group.querySelector("input[id^='field_unique_id_']");
        var sectionRequired = group.querySelector("input[id^='section_required_']");
        var includeInEmail  = group.querySelector("input[id^='include_in_email_']");

        var fieldCreatorTrim  = fieldCreator  ? fieldCreator.value.trim()  : '';
        var fieldLabelTrim    = fieldLabel    ? fieldLabel.value.trim()    : '';
        var fieldIdTrim       = fieldId       ? fieldId.value.trim()       : '';
        var fieldMaxcharTrim  = fieldMaxchar  ? fieldMaxchar.value.trim()  : '';
        var fieldDropdownTrim = fieldDropdown ? fieldDropdown.value.trim() : '';

        var creatorErrorEl  = getErrorElementFromInput(fieldCreator);
        var labelErrorEl    = getErrorElementFromInput(fieldLabel);
        var idErrorEl       = getErrorElementFromInput(fieldId);
        var maxCharErrorEl  = getErrorElementFromInput(fieldMaxchar);
        var dropdownErrorEl = getErrorElementFromInput(fieldDropdown);

        [fieldCreator, fieldLabel, fieldId, fieldMaxchar, fieldDropdown].forEach(attachClearOnInput);

        var errors = [];

        if (fieldCreatorTrim === '') {
            errors.push({ el: creatorErrorEl, message: 'Field type is required.' });
        }

        if (fieldLabelTrim === '') {
            errors.push({ el: labelErrorEl, message: 'Field label is required.' });
        }

        if (fieldIdTrim === '') {
            errors.push({ el: idErrorEl, message: 'Field ID is required.' });
        }

        if (fieldCreatorTrim !== 'dropdown' && fieldMaxchar && fieldMaxcharTrim === '') {
            errors.push({ el: maxCharErrorEl, message: 'Max character is required.' });
        }

        if (fieldCreatorTrim === 'dropdown' && fieldDropdown && fieldDropdownTrim === '') {
            errors.push({ el: dropdownErrorEl, message: 'This field is required.' });
        }

        if (errors.length > 0) {
            hasErrors = true;
            errors.forEach(function (error) {
                if (error.el) error.el.textContent = error.message;
            });
            return;
        }

        var formData = {
            app_width_figure: document.getElementById("app_width_figure").value,
            field_creator: fieldCreatorTrim,
            field_uniqueid: fieldUnique ? fieldUnique.value : '',
            field_uniqueidAfterPosition: fieldUnique ? fieldUnique.value : '',
            field_order: order,
            field_label: fieldLabelTrim,
            field_id: fieldIdTrim,
            field_maxchar: fieldCreatorTrim === 'dropdown' ? '' : fieldMaxcharTrim,
            field_dropdown_options: fieldDropdownTrim,
            field_sample_text: fieldSampleText ? fieldSampleText.value : '',
            section_required: sectionRequired ? sectionRequired.checked : false,
            include_in_email: includeInEmail ? includeInEmail.checked : false
        };

        formDataArray.push(formData);
    });

    if (hasErrors) {
        return;
    }

    var loader = document.getElementById('loader');
    if (loader) loader.style.display = 'flex';

    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (loader) loader.style.display = 'none';

            if (xhr.status === 200) {
                var response = JSON.parse(xhr.responseText);
                messageContainer.innerHTML = '<span style="color: green;">' + response.data + '</span>';
            } else {
                messageContainer.innerHTML = '<span style="color: red;">Failed to save data</span>';
            }

            setTimeout(function () {
                messageContainer.innerHTML = '';
            }, 5000);
        }
    };

    xhr.open("POST", myPluginAjax.ajaxurl, true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    var nonce = document.getElementById("ai_app_onsite_field_selector_nonce_field").value;

    var data = "action=ai_app_onsite_save_field_selector&form_data_array=" +
        encodeURIComponent(JSON.stringify(formDataArray)) +
        '&ai_app_onsite_field_selector_nonce_field=' + encodeURIComponent(nonce);

    xhr.send(data);
}

/* --------------------------------------------------------------------------
   Read field data
--------------------------------------------------------------------------- */

function ai_app_onsite_read_field_selector() {
    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            var response = JSON.parse(xhr.responseText);

            if (xhr.status === 200) {
                var appWidth = document.getElementById('app_width_figure');
                appWidth.value = response.app_width ? response.app_width : '70';

                var fieldCatcher = document.querySelector(".field-catcher");
                fieldCatcher.innerHTML = response.html_content;

                hideMaxCharIfDropdown();
            } else {
                console.error('Error occurred: ' + xhr.responseText);
            }

            document.getElementById('app_width_figure').setAttribute('name', 'app_width_figure');

            jQuery(".field-catcher > .form-group.ui-state-default").each(function (index) {
                jQuery(this).find("select[id^='filed_creator_']").attr("name", "filed_creator_" + index);
            });

            const appFieldSelectorSettingsformTracker = trackFormChanges('#myForm');
            window.FormChangeRegistry.register('app_field_selector_settings', appFieldSelectorSettingsformTracker, 'field-selector');

            document.getElementById('save_ai_app_ai_app_fieldselector_data').addEventListener('click', function () {
                const nonceValue = document.getElementById("ai_app_onsite_field_selector_nonce_field").value;
                appFieldSelectorSettingsformTracker.reset();
                document.getElementById("ai_app_onsite_field_selector_nonce_field").value = nonceValue;
            });
        }
    };

    xhr.open('POST', myPluginAjax.ajaxurl, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    xhr.send('action=ai_app_onsite_read_field_selector');
}

// Initial fetch
ai_app_onsite_read_field_selector();

/* --------------------------------------------------------------------------
   Max-char / dropdown visibility (index-agnostic)
--------------------------------------------------------------------------- */

function hideMaxCharIfDropdown() {
    var formGroups = document.querySelectorAll('.field-catcher > .form-group.ui-state-default');
    if (!formGroups || formGroups.length === 0) return;

    formGroups.forEach(function (group) {
        var selectBox    = group.querySelector("select[id^='filed_creator_']");
        if (!selectBox) return;

        var maxCharField = group.querySelector("[id^='maxium-char_']");
        var fieldSample  = group.querySelector("[id^='field_sampl_text_']");
        var dropdownCol  = group.querySelector("[class*='dropdown-options-col_']");
        var maxCharInput = group.querySelector("input[id^='field_maxchar_']");

        function applyState(type) {
            if (type === 'dropdown') {
                if (maxCharField) maxCharField.style.display = 'none';
                if (fieldSample)  fieldSample.style.display  = 'none';
                if (dropdownCol)  dropdownCol.style.display  = 'block';
            } else {
                if (maxCharField) maxCharField.style.display = 'block';
                if (fieldSample)  fieldSample.style.display  = 'block';
                if (dropdownCol)  dropdownCol.style.display  = 'none';

                if (maxCharInput) {
                    if (type === 'textbox')  maxCharInput.value = '80';
                    if (type === 'textarea') maxCharInput.value = '300';
                    if (type === 'number')   maxCharInput.value = '10';
                    if (type === 'email')    maxCharInput.value = '50';
                }
            }
        }

        applyState(selectBox.value);

        selectBox.addEventListener('change', function () {
            applyState(selectBox.value);
        });
    });
}

/* --------------------------------------------------------------------------
   createDropdown for newly added fields
--------------------------------------------------------------------------- */

function createDropdown(ctr) {
    var selectBox = document.querySelector("#filed_creator_" + ctr);
    if (!selectBox) return;

    var group         = selectBox.closest('.form-group.ui-state-default');
    if (!group) return;

    var topFieldRow   = group.querySelector('.field-row.top');
    var dropdownColumn = group.querySelector(".dropdown-options-col_" + ctr);
    var maxCharField  = group.querySelector("#maxium-char_" + ctr);
    var maxCharInput  = group.querySelector("#field_maxchar_" + ctr);
    var fieldSample   = group.querySelector("#field_sampl_text_" + ctr);

    var type = selectBox.value;

    if (type === 'textbox') {
        if (maxCharField) maxCharField.style.display = 'block';
        if (maxCharInput) maxCharInput.value = '80';
        if (fieldSample)  fieldSample.style.display  = 'block';
        if (dropdownColumn) dropdownColumn.style.display = 'none';
    } else if (type === 'textarea') {
        if (maxCharField) maxCharField.style.display = 'block';
        if (maxCharInput) maxCharInput.value = '300';
        if (fieldSample)  fieldSample.style.display  = 'block';
        if (dropdownColumn) dropdownColumn.style.display = 'none';
    } else if (type === 'number') {
        if (maxCharField) maxCharField.style.display = 'block';
        if (maxCharInput) maxCharInput.value = '10';
        if (fieldSample)  fieldSample.style.display  = 'block';
        if (dropdownColumn) dropdownColumn.style.display = 'none';
    } else if (type === 'email') {
        if (maxCharField) maxCharField.style.display = 'block';
        if (maxCharInput) maxCharInput.value = '50';
        if (fieldSample)  fieldSample.style.display  = 'block';
        if (dropdownColumn) dropdownColumn.style.display = 'none';
    } else { // dropdown
        if (!dropdownColumn) {
            var dropdownOptionsCol = document.createElement('div');
            dropdownOptionsCol.classList.add('full-width', "dropdown-options-col_" + ctr);
            dropdownOptionsCol.innerHTML = `
                    <label for="dropdown-options-${ctr}" class="d-block fs-medium-14 mb-only-4 form-label">
                        Drop-down options <span class="mk-red">*</span>
                    </label>
                    <input type="text" name="dropdown-options-${ctr}" id="dropdown_options_${ctr}" class="border border-1 dropdown-options" value="">
                    <p>Separate values with "|"</p>
                    <p id="dropdown_options_${ctr}_error" class="fields-error"></p>`;
            topFieldRow.appendChild(dropdownOptionsCol);
            dropdownColumn = dropdownOptionsCol;
        }
        if (maxCharField) maxCharField.style.display = 'none';
        if (fieldSample)  fieldSample.style.display  = 'none';
        dropdownColumn.style.display = 'block';
    }
}

/* --------------------------------------------------------------------------
   Drag order save (refactored to top-level groups only)
--------------------------------------------------------------------------- */

function ai_app_onsite_drag_data_save_database() {
    var formDataArray = [];
    var messageContainer = document.getElementById('field-selector-msg-container');
    var ai_app_onsite_fields_selector_order_nonce = myPluginAjax.fieldSelectorOrder;

    var formGroups = document.querySelectorAll(".field-catcher > .form-group.ui-state-default");
    if (formGroups.length === 0) {
        messageContainer.innerHTML = '<span style="color: red;">No field shown, please Add a field.</span>';
        setTimeout(function () { messageContainer.innerHTML = ''; }, 3000);
        return;
    }

    jQuery(".field-catcher > .form-group.ui-state-default").each(function (index) {

        var fieldUniqueId = jQuery(this).find("[id^='field_unique_id_']").val();

        formDataArray.push({
            fieldUniqueId: fieldUniqueId,
            fieldOrder: index       // ALWAYS CORRECT
        });
    });

    var loader = document.getElementById('loader');

    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (loader) {
                setTimeout(function () { loader.style.display = 'none'; }, 3000);
            }

            if (xhr.status === 200) {
                var response = JSON.parse(xhr.responseText);
                messageContainer.innerHTML = '<span style="color: green;">' + response.data + '</span>';
            } else {
                messageContainer.innerHTML = '<span style="color: red;">Failed to save data</span>';
            }

            setTimeout(function () {
                messageContainer.innerHTML = '';
            }, 5000);
        }
    };

    xhr.open("POST", myPluginAjax.ajaxurl, true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    var data = "action=ai_app_onsite_drag_data_save_database" +
        "&ai_app_onsite_fields_selector_order_nonce=" + encodeURIComponent(ai_app_onsite_fields_selector_order_nonce) +
        "&form_data_array=" + encodeURIComponent(JSON.stringify(formDataArray));

    xhr.send(data);
}
