document.addEventListener('DOMContentLoaded', function() {
    const list = document.getElementById('security_level_form_content');
    let draggedItem = null;

    for (const item of list.querySelectorAll('li')) {
        item.setAttribute('draggable', true);

        item.addEventListener('dragstart', function(e) {
            draggedItem = this;
            setTimeout(() => this.classList.add('hide'), 0);
        });

        item.addEventListener('dragend', function(e) {
            setTimeout(() => this.classList.remove('hide'), 0);
        });

        item.addEventListener('dragover', function(e) {
            e.preventDefault();
        });

        item.addEventListener('dragenter', function(e) {
            e.preventDefault();
            this.classList.add('over');
        });

        item.addEventListener('dragleave', function(e) {
            this.classList.remove('over');
        });

        item.addEventListener('drop', function(e) {
            e.preventDefault();
            this.classList.remove('over');
            if (this !== draggedItem) {
                const items = Array.from(list.querySelectorAll('li'));
                const draggedIndex = items.indexOf(draggedItem);
                const droppedIndex = items.indexOf(this);

                if (draggedIndex < droppedIndex) {
                    this.after(draggedItem);
                } else {
                    this.before(draggedItem);
                }
            }
        });
    }
});

function saveOrder() {
    const listItems = document.querySelectorAll('#security_level_form_content li');
    const order = Array.from(listItems).map(item => item.textContent.trim());
    localStorage.setItem('listOrder', JSON.stringify(order));
}

function loadOrder() {
    const storedOrder = JSON.parse(localStorage.getItem('listOrder'));
    if (storedOrder) {
        const list = document.getElementById('security_level_form_content');
        list.innerHTML = '';
        storedOrder.forEach(itemText => {
            const li = document.createElement('li');
            li.textContent = itemText;
            li.setAttribute('draggable', true);
            list.appendChild(li);
        });
    }
}

// Call loadOrder to initialize the list with the saved order
loadOrder();
