/**
 * Form inline fields
 * this one is going to be tough!
 */
IGDATAPOOLFE.plugins.add('formInlineRecord', {
    form: null,
    initFields: function(form) {
	this.init(form);
    },
    init: function(form) {
	this.form = form;

	// called on insert/delete records - hide/show add button
	function onUpdate(fieldWrap) {
	    if (!fieldWrap) {
		return;
	    }
	    let addButton = fieldWrap.querySelector(".dp-form-inline-record-add");
	    let maxItems = fieldWrap.dataset.maxitems ? parseInt(fieldWrap.dataset.maxitems, 10) : 0;
	    let currentItems = fieldWrap.querySelectorAll("div.dp-record-container-show").length;

	    if (maxItems > 0 && currentItems >= maxItems) {
		addButton.parentElement.style.display = "none";
	    } else {
		addButton.parentElement.style.display = "block";
	    }
	}
	
	var deleteRecord = function(event) {
            let deleteElement = event.target.closest("div.dp-record-container");
            let fieldWrap = deleteElement.closest("div.dp-form-inline-record");
            let deleteId = deleteElement.dataset.rel;
	    if (fieldWrap) {
		let confirmMessage = fieldWrap.dataset.confirmText || '';
		if (!confirm(confirmMessage)) return;
	    }

            // Remove the record element
            deleteElement.remove();

            if (deleteId) {
		// Remove the corresponding hidden field if the record is persistent
		let hiddenField = form.querySelector(`.${deleteId}`);
		if (hiddenField) hiddenField.remove();
            }

            // Enable the hidden field if no records are left (only dummy remains)
            if (fieldWrap && fieldWrap.querySelectorAll(".dp-record-container").length === 1) {
		let hiddenFields = fieldWrap.querySelector("div.hiddenfields");
		if (hiddenFields) {
                    let isEmptyInput = hiddenFields.querySelector("input.isEmpty");
                    if (isEmptyInput) isEmptyInput.disabled = false;
		}
            }

            onUpdate(fieldWrap);
	}
	form.querySelectorAll(".dp-form-inline-record .dp-record .dp-panel .dp-sprite.dp-delete").forEach((element) => {
            element.style.display = "block";
            element.addEventListener("click", deleteRecord);
	});

	

	form.querySelectorAll(".dp-sorting-up").forEach((button) => {
            button.addEventListener("click", function () {
		let el = button.closest(".dp-record-container");
		let prevEl = el.previousElementSibling;

		if (prevEl) {
                    let elCurSort = el.querySelector("input.dp-file-upload-sort").value;
                    let elPrevSort = prevEl.querySelector("input.dp-file-upload-sort").value;

                    el.querySelector("input.dp-file-upload-sort").value = elPrevSort;
                    prevEl.querySelector("input.dp-file-upload-sort").value = elCurSort;

                    prevEl.before(el);
		}
            });
	});

	form.querySelectorAll(".dp-sorting-down").forEach((button) => {
            button.addEventListener("click", function () {
		let el = button.closest(".dp-record-container");
		let nextEl = el.nextElementSibling;

		if (nextEl) {
                    let elCurSort = el.querySelector("input.dp-file-upload-sort").value;
                    let elNextSort = nextEl.querySelector("input.dp-file-upload-sort").value;

                    el.querySelector("input.dp-file-upload-sort").value = elNextSort;
                    nextEl.querySelector("input.dp-file-upload-sort").value = elCurSort;

                    nextEl.after(el);
		}
            });
	});
	//for each field of this type...
	form.querySelectorAll(".dp-form-inline-record .dp-form-inline-record-add").forEach((addButton) => {
            let fieldWrap = addButton.closest("div.dp-form-inline-record");
            onUpdate(fieldWrap);

            addButton.addEventListener("click", function () {
		let containerNew = addButton.nextElementSibling.querySelector(".dp-record-container");
		let containerEntries =  addButton.previousElementSibling?.parentElement?.parentElement;
		let containerClone = containerNew.cloneNode(true); // Clone the element

		// If sorting field exists
		let sortInputs = containerClone.querySelectorAll("input.dp-file-upload-sort");
		if (sortInputs.length > 0) {
                    let maxVal = 0;
                    containerEntries.parentElement.querySelectorAll(".dp-record-show").forEach((record) => {
			let sortValue = parseInt(record.querySelector("input.dp-file-upload-sort").value) || 0;
			if (sortValue > maxVal) maxVal = sortValue;
                    });
                    maxVal++;
                    sortInputs.forEach((input) => (input.value = maxVal));
		}

		containerEntries.insertAdjacentElement("beforebegin", containerClone); // Insert before entries

		onUpdate(fieldWrap);

		// Generate a unique temp name
		let tempName = containerEntries.parentElement.querySelectorAll("div.dp-record-container").length + 99;

		// Update name attributes
		containerClone.querySelectorAll("[name]").forEach((input) => {
                    let name = input.getAttribute("name").replace("dummy-", "").replace("TEMP", tempName);
                    input.setAttribute("name", name);
		});

		// Update id attributes
		containerClone.querySelectorAll("[id]").forEach((el) => {
                    let id = el.getAttribute("id").replace("dummy-", "").replace("TEMP", tempName);
                    el.setAttribute("id", id);
		});

		// Find delete button and attach event listener
		let deleteButton = containerClone.querySelector(".dp-record-container .dp-record .dp-panel .dp-sprite.dp-delete");
		if (deleteButton) {
                    deleteButton.style.display = "block";
                    deleteButton.addEventListener("click", deleteRecord);
		}
		let targetElement = addButton.previousElementSibling?.parentElement?.parentElement?.previousElementSibling;
		if (targetElement) {
		    this.form.initFields(targetElement);
		}
            });
	});

    }
});