/* eslint-disable */
import Sortable from 'sortablejs';

export const initSortableViewSet = () => {
    const tbody = document.querySelector('.listing tbody');
    if (!tbody) return;

    const sortableInstance = Sortable.create(tbody, {
        handle: '.w-orderable__item__handle',
        animation: 150,
        onEnd: function(evt) {
            const items = Array.from(tbody.querySelectorAll('.w-orderable__item__handle'))
                .map(button => button.dataset.id);

            const formData = new FormData();
            items.forEach(id => formData.append('items[]', id));

            fetch('update/', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': window.wagtailConfig.CSRF_TOKEN
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    console.error('Error updating order:', data.error);
                }
            })
            .catch(error => console.error('Error:', error));
        }
    });

    return sortableInstance;
};
