let cloneCounter = 0; // Global counter to track cloned sections

// Add behavior to dropdowns in a dynamic section
function addDropdownBehavior(section) {
    const accessDropdown = section.querySelector('[id^="access"]');
    const portInputDiv = section.querySelector('[id^="portInputDiv"]');
    const dynamicDropdownDiv = section.querySelector('[id^="dynamicDropdownDiv"]');

    // Event listener for dropdown change
    function handleDropdownChange() {
        const selectedValue = this.value;

        // Show or hide input fields based on selection
        if (selectedValue === 'Port') {
            portInputDiv.classList.remove('hidden');
            dynamicDropdownDiv.classList.add('hidden');
        } else if (selectedValue !== '') {
            portInputDiv.classList.add('hidden');
            dynamicDropdownDiv.classList.remove('hidden');

            let options = '';
            if (selectedValue === 'Connectiontype') {
                options = `<option value="wifi">WiFi</option><option value="ethernet">Ethernet</option>`;
            } else if (selectedValue === 'Subtype') {
                options = `<option value="fiber">Fiber</option><option value="dsl">DSL</option>`;
            } else if (selectedValue === 'Switch') {
                options = `<option value="switchA">Switch A</option><option value="switchB">Switch B</option>`;
            }

            // Populate dynamic dropdown options
            dynamicDropdownDiv.innerHTML = `<select id="dynamicDropdown_${cloneCounter}" name="dynamicDropdown_${cloneCounter}">${options}</select>`;
        } else {
            portInputDiv.classList.add('hidden');
            dynamicDropdownDiv.classList.add('hidden');
        }
    }

    // Update event listeners for dropdown
    accessDropdown.removeEventListener('change', handleDropdownChange);
    accessDropdown.addEventListener('change', handleDropdownChange);
}

// Add dynamic dropdown add/remove listeners
function addDynamicSectionListeners(section) {
    const plusIcon = section.querySelector('.plus');
    const minusIcon = section.querySelector('.minus');

    plusIcon.addEventListener('click', function () {
        const newDynamicClone = section.cloneNode(true); // Clone dynamic section
        cloneCounter++; // Update clone counter

        resetInputs(newDynamicClone, cloneCounter); // Reset cloned inputs

        section.parentNode.appendChild(newDynamicClone); // Add new cloned section
        addDynamicSectionListeners(newDynamicClone); // Add listeners to new section
        addDropdownBehavior(newDynamicClone); // Initialize dropdown behavior for new section
    });

    minusIcon.addEventListener('click', function () {
        if (section.parentNode.childElementCount > 1) { // Keep at least one section
            section.remove();
        }
    });

    addDropdownBehavior(section); // Initialize behavior
}

// Reset input fields and assign unique IDs/names
function resetInputs(section, counter) {
    const inputs = section.querySelectorAll('input, select');
    inputs.forEach(input => {
        if (input.type !== 'checkbox') {
            input.value = ''; // Clear non-checkbox inputs
        } else {
            input.checked = false; // Uncheck checkboxes
        }

        // Update name and ID to unique for cloned elements
        const baseName = input.name.replace(/_\d+$/, '');
        input.name = `${baseName}_${counter}`;

        const baseId = input.id.replace(/_\d+$/, '');
        input.id = `${baseId}_${counter}`;
    });

    section.querySelector('[id^="access"]').selectedIndex = 0; // Reset main dropdown
    section.querySelector('[id^="portInputDiv"]').classList.add('hidden'); // Hide port input
    section.querySelector('[id^="dynamicDropdownDiv"]').innerHTML = ''; // Clear dynamic dropdown
}

// Clear extra dynamic sections when cloning a form
function clearDynamicSections(section) {
    const extraDynamicSections = section.querySelectorAll('.dynamic');
    extraDynamicSections.forEach((section, index) => {
        if (index > 0) { // Remove all but the first dropdown section
            section.remove();
        }
    });
}

// Add listeners to clone/remove forms
function addFormEventListeners(form) {
    const plusIcon = form.querySelector('.add_sec .plus');
    const minusIcon = form.querySelector('.add_sec .minus');

    plusIcon.addEventListener('click', function () {
        const newFormClone = form.cloneNode(true); // Clone entire form
        cloneCounter++; // Increment clone counter

        resetInputs(newFormClone, cloneCounter); // Reset inputs in cloned form
        clearDynamicSections(newFormClone); // Remove extra dropdowns, keep only first

        addFormEventListeners(newFormClone); // Add event listeners for cloned form
        form.parentNode.appendChild(newFormClone); // Append cloned form
    });

    minusIcon.addEventListener('click', function () {
        const allForms = document.querySelectorAll('.userdetails form');
        if (allForms.length > 1) { // Ensure one form remains
            form.remove();
        }
    });

    addDropdownBehavior(form); // Add dropdown behavior for form
    const dynamicSections = form.querySelectorAll('.dynamic');
    dynamicSections.forEach(section => addDynamicSectionListeners(section)); // Add dynamic behavior
}

// Initialize original form
const originalForm = document.querySelector('.userdetails form');
addFormEventListeners(originalForm);
