// resources/js/folder-dnd.js
document.addEventListener('DOMContentLoaded', () => {
    const folders = document.querySelectorAll('.folder-item');
    
    folders.forEach(folder => {
        folder.draggable = true;
        
        folder.addEventListener('dragstart', (e) => {
            e.dataTransfer.setData('text/plain', folder.dataset.folderId);
            folder.classList.add('opacity-50');
        });

        folder.addEventListener('dragend', () => {
            folder.classList.remove('opacity-50');
        });
    });

    const dropZones = document.querySelectorAll('[data-drop-zone]');
    
    dropZones.forEach(zone => {
        zone.addEventListener('dragover', (e) => {
            e.preventDefault();
            zone.classList.add('bg-blue-50', 'border-blue-200');
        });

        zone.addEventListener('dragleave', () => {
            zone.classList.remove('bg-blue-50', 'border-blue-200');
        });

        zone.addEventListener('drop', async (e) => {
            e.preventDefault();
            const folderId = e.dataTransfer.getData('text/plain');
            const newParentId = zone.dataset.folderId;
            
            try {
                const response = await fetch(`/folders/${folderId}/move`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    },
                    body: JSON.stringify({ parent_id: newParentId })
                });

                if (response.ok) {
                    window.location.reload();
                }
            } catch (error) {
                console.error('Error moving folder:', error);
            }
            
            zone.classList.remove('bg-blue-50', 'border-blue-200');
        });
    });
});

document.querySelectorAll('.folder-item').forEach(item => {
    item.addEventListener('click', function() {
        const folderId = this.dataset.folderId;
        Livewire.emit('folderSelected', folderId);
    });
});