document.addEventListener('DOMContentLoaded', function () {
    function updateSubmitButtonVisibility() {
        const containers = document.querySelectorAll('.initialPositionContainer:not([style*="display: none"])');
        const submitButton = document.getElementById('submitButton');
        if (containers.length > 0) {
            submitButton.classList.remove('hidden');
            submitButton.style.display = 'flex';
        } else {
            submitButton.classList.add('hidden');
            submitButton.style.display = 'none';
        }
    }

    function removePositionContainer(event) {
        event.preventDefault();
        const container = event.target.closest('.initialPositionContainer');
        container.remove();
        updateSubmitButtonVisibility();
    }

    document.getElementById('addNewPosition').addEventListener('click', function () {
        const container = document.getElementById('positionsContainer');
        const initialPositionContainer = document.querySelector('.initialPositionContainer');

        const newPositionContainer = initialPositionContainer.cloneNode(true);
        newPositionContainer.classList.remove('hidden');
        newPositionContainer.style.display = 'flex';

        const selectElement = newPositionContainer.querySelector('select');
        selectElement.name = 'position[]';

        const dateInputElements = newPositionContainer.querySelectorAll('input[type="date"]');
        dateInputElements.forEach((input, index) => {
            if (index === 0) {
                input.name = 'start_date[]';
            } else {
                input.name = 'end_date[]';
            }
        });

        const removeButton = newPositionContainer.querySelector('.removePositionOption');
        removeButton.addEventListener('click', removePositionContainer);

        container.appendChild(newPositionContainer);
        updateSubmitButtonVisibility();
    });

    document.querySelectorAll('.removePositionOption').forEach(button => {
        button.addEventListener('click', removePositionContainer);
    });

    updateSubmitButtonVisibility();
});
