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

function addDropdownBehavior(section) {
    const accessDropdown = section.querySelector('[id^="access"]');
    const portInputDiv = section.querySelector('[id^="portInputDiv"]');
    const dynamicDropdownDiv = section.querySelector('[id^="dynamicDropdownDiv"]');
    const dynamicDropdown = section.querySelector('[id^="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>`;
            }

            // Ensure a full <select> element is rendered inside the dynamic dropdown div
            dynamicDropdownDiv.innerHTML = `<select id="${dynamicDropdown.id}" name="${dynamicDropdown.name}">${options}</select>`;
        } 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
        cloneCounter++; // Increment the global counter

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

        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, assign unique ids/names
function resetInputs(section, counter) {
    const inputs = section.querySelectorAll('input, select');
    inputs.forEach(input => {
        if (input.type !== 'checkbox') {
            input.value = ''; // Clear input fields
        } else {
            input.checked = false; // Uncheck checkboxes
        }

        // Assign unique names and IDs to cloned inputs
        const baseName = input.name.replace(/_\d+$/, ''); // Strip off any previous clone counter
        input.name = `${baseName}_${counter}`; // Add clone counter to name

        const baseId = input.id.replace(/_\d+$/, ''); // Strip off any previous clone counter
        input.id = `${baseId}_${counter}`; // Add clone counter to ID
    });

    section.querySelector('[id^="access"]').selectedIndex = 0; // Reset dropdown to default

    // Hide input fields for the cloned section by default
    const portInputDiv = section.querySelector('[id^="portInputDiv"]');
    const dynamicDropdownDiv = section.querySelector('[id^="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
        cloneCounter++; // Increment counter for the clone

        resetInputs(newFormClone, cloneCounter); // Reset inputs in the cloned form

        // 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);




//--------------------------Almost done code for cloning----------//
//let cloneCounter = 0; // Global counter to track cloned sections

function addDropdownBehavior(section) {
    const accessDropdown = section.querySelector('[id^="access"]');
    const portInputDiv = section.querySelector('[id^="portInputDiv"]');
    const dynamicDropdownDiv = section.querySelector('[id^="dynamicDropdownDiv"]');

    // 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>`;
            }

            // Ensure a full <select> element is rendered inside the dynamic dropdown div
            dynamicDropdownDiv.innerHTML = `<select id="dynamicDropdown_${cloneCounter}" name="dynamicDropdown_${cloneCounter}">${options}</select>`;
        } 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

        // Increment the global counter to ensure unique ids/names
        cloneCounter++;

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

        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, assign unique ids/names
function resetInputs(section, counter) {
    const inputs = section.querySelectorAll('input, select');
    inputs.forEach(input => {
        if (input.type !== 'checkbox') {
            input.value = ''; // Clear input fields
        } else {
            input.checked = false; // Uncheck checkboxes
        }

        // Assign unique names and IDs to cloned inputs
        const baseName = input.name.replace(/_\d+$/, ''); // Strip off any previous clone counter
        input.name = `${baseName}_${counter}`; // Add clone counter to name

        const baseId = input.id.replace(/_\d+$/, ''); // Strip off any previous clone counter
        input.id = `${baseId}_${counter}`; // Add clone counter to ID
    });

    section.querySelector('[id^="access"]').selectedIndex = 0; // Reset dropdown to default

    // Hide input fields for the cloned section by default
    const portInputDiv = section.querySelector('[id^="portInputDiv"]');
    const dynamicDropdownDiv = section.querySelector('[id^="dynamicDropdownDiv"]');
    portInputDiv.classList.add('hidden');
    dynamicDropdownDiv.innerHTML = ''; // Clear any previous dynamic dropdowns
}

// Function to clear all dynamic sections in the cloned form
function clearDynamicSections(form) {
    const existingDynamicSections = form.querySelectorAll('.dynamic');
    existingDynamicSections.forEach(section => {
        const dynamicDropdownDiv = section.querySelector('[id^="dynamicDropdownDiv"]');
        dynamicDropdownDiv.innerHTML = ''; // Clear dynamic dropdowns
    });
}

// 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
        cloneCounter++; // Increment counter for the clone

        resetInputs(newFormClone, cloneCounter); // Reset inputs in the cloned form
        clearDynamicSections(newFormClone); // Clear any dynamic dropdowns in the cloned form

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

        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);
