// Function to add dynamic dropdown behavior
function addDropdownBehavior(section) {
    const accessDropdown = section.querySelector('[id="access"]');
    const portInputDiv = section.querySelector('#portInputDiv');
    const dynamicDropdownDiv = section.querySelector('#dynamicDropdownDiv');
    const dynamicDropdown = section.querySelector('#dynamicDropdown');

    // Event listener function 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>`;
            }
            dynamicDropdown.innerHTML = options;
        } else {
            portInputDiv.classList.add('hidden');
            dynamicDropdownDiv.classList.add('hidden');
        }
    }

    // Remove any existing event listener first
    accessDropdown.removeEventListener('change', handleDropdownChange);
    accessDropdown.addEventListener('change', handleDropdownChange);
}

// Function to add event listeners for plus and minus icons in the dynamic section
function addDynamicSectionListeners(section) {
    const plusIcon = section.querySelector('.plus');
    const minusIcon = section.querySelector('.minus');

    // Plus functionality: clone the dynamic section
    plusIcon.addEventListener('click', function () {
        const newDynamicClone = section.cloneNode(true); // Clone the dynamic section

        // Reset inputs and dropdowns in the cloned section
        resetInputs(newDynamicClone);

        // Remove dynamically added dropdowns or sections if needed
        const dynamicSections = newDynamicClone.querySelectorAll('.dynamic');
        dynamicSections.forEach((dynamicSection, index) => {
            if (index > 0) { // If it's a cloned section, remove it from the cloned form
                dynamicSection.remove();
            }
        });

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

    // Minus functionality: remove the dynamic section
    minusIcon.addEventListener('click', function () {
        if (section.parentNode.childElementCount > 1) { // Ensure at least one section remains
            section.remove();
        }
    });

    addDropdownBehavior(section); // Initialize dropdown behavior for this section
}

// Function to reset inputs and dropdowns
function resetInputs(section) {
    const inputs = section.querySelectorAll('input, select');
    inputs.forEach(input => {
        if (input.type !== 'checkbox') {
            input.value = ''; // Clear input fields
        } else {
            input.checked = false; // Uncheck checkboxes
        }
    });
    section.querySelector('#access').selectedIndex = 0; // Reset dropdown to default

    // Hide input fields for the cloned section by default
    const portInputDiv = section.querySelector('#portInputDiv');
    const dynamicDropdownDiv = section.querySelector('#dynamicDropdownDiv');
    portInputDiv.classList.add('hidden');
    dynamicDropdownDiv.classList.add('hidden');
}

// Function to add event listeners for the entire form
function addFormEventListeners(form) {
    const plusIcon = form.querySelector('.add_sec .plus');
    const minusIcon = form.querySelector('.add_sec .minus');

    // Plus functionality: clone the entire form
    plusIcon.addEventListener('click', function () {
        const newFormClone = form.cloneNode(true); // Clone the entire form
        resetInputs(newFormClone); // Reset inputs in the cloned form

        // Remove dynamically added dropdowns from the cloned form
        const dynamicSections = newFormClone.querySelectorAll('.dynamic');
        dynamicSections.forEach((dynamicSection, index) => {
            if (index > 0) { // If it's a dynamically added section, remove it from the cloned form
                dynamicSection.remove();
            }
        });

        // Add event listeners to the new cloned form
        addFormEventListeners(newFormClone);

        // Add dynamic section listeners for the cloned form
        const originalDynamicSections = newFormClone.querySelectorAll('.dynamic');
        originalDynamicSections.forEach(section => {
            addDynamicSectionListeners(section);
        });

        form.parentNode.appendChild(newFormClone); // Append the new cloned form
    });

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

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

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