jQuery(document).ready(function($) {
    console.log('WP Smart Folder management JavaScript loaded');

    // ===== DRAG & DROP FUNCTIONS =====
    
    // Function to enable folders drag & drop
    function enableFoldersDragAndDrop() {
        $('#folders-sortable').sortable({
            handle: '.folder-drag-handle',
            placeholder: 'ui-sortable-placeholder',
            opacity: 0.7,
            tolerance: 'pointer',
            update: function(event, ui) {
                const foldersOrder = $('#folders-sortable .sortable-folder').map(function() {
                    return $(this).data('folder-id');
                }).get();

                saveFoldersOrder(foldersOrder);
            }
        });
    }

    // Function to save folders order
    function saveFoldersOrder(foldersOrder) {
        console.log('Saving folder order:', foldersOrder);
        
        $.ajax({
            url: fold82smData.ajax_url,
            type: 'POST',
            data: {
                action: 'fold82sm_save_folders_order',
                nonce: fold82smData.nonce,
                order: foldersOrder
            },
            success: function(response) {
                console.log('Save response:', response);
                if (response.success) {
                    showTemporaryMessage('Folder order saved successfully!', 'success');
                } else {
                    showTemporaryMessage('Error saving order: ' + response.data.message, 'error');
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX error:', error);
                showTemporaryMessage('AJAX error saving order.', 'error');
            }
        });
    }

    // ===== FOLDER NAME EDITING FUNCTIONS =====

    // Function to handle folder name editing
    function initFolderNameEditing() {
        // Edit icon click handler
        $('.folder-edit-icon').off('click').on('click', function() {
            const folderId = $(this).data('folder-id');
            const currentName = $(this).data('folder-name');
            
            editFolderName(folderId, currentName, $(this));
        });
    }

    // Function to open edit dialog
    function editFolderName(folderId, currentName, editIcon) {
        const popupContent = `
            <h3>Edit Folder Name</h3>
            <input type="text" id="edit-folder-name" value="${currentName}" style="width: 100%; padding: 8px; margin: 10px 0;">
            <div style="display: flex; gap: 10px; margin-top: 15px;">
                <button id="confirm-edit-folder" class="button button-primary">Save</button>
                <button id="cancel-edit-folder" class="button">Cancel</button>
            </div>
        `;
        
        openPopup(popupContent);
        
        // Focus on input
        $('#edit-folder-name').focus().select();
        
        // Save handler
        $('#confirm-edit-folder').off('click').on('click', function() {
            const newName = $('#edit-folder-name').val().trim();
            
            if (!newName) {
                alert('Please enter a folder name.');
                return;
            }
            
            if (newName === currentName) {
                $('.popup-overlay').fadeOut(function() { $(this).remove(); });
                return;
            }
            
            updateFolderName(folderId, newName, editIcon);
        });
        
        // Cancel handler
        $('#cancel-edit-folder').off('click').on('click', function() {
            $('.popup-overlay').fadeOut(function() { $(this).remove(); });
        });
        
        // Enter key handler
        $('#edit-folder-name').off('keypress').on('keypress', function(e) {
            if (e.which === 13) {
                $('#confirm-edit-folder').click();
            }
        });
    }

    // Function to update folder name via AJAX
    function updateFolderName(folderId, newName, editIcon) {
        const $saveButton = $('#confirm-edit-folder');
        
        $saveButton.prop('disabled', true).text('Saving...');
        
        $.ajax({
            url: fold82smData.ajax_url,
            type: 'POST',
            data: {
                action: 'fold82sm_update_folder_name',
                folder_id: folderId,
                new_name: newName,
                nonce: fold82smData.nonce
            },
            success: function(response) {
                $saveButton.prop('disabled', false).text('Save');
                
                if (response.success) {
                    $('.popup-overlay').fadeOut(function() { $(this).remove(); });
                    
                    // Update the folder name in the UI
                    $(`#folder-title-${folderId}`).text(newName);
                    
                    // Update the edit icon data attribute
                    editIcon.attr('data-folder-name', newName);
                    
                    // Show success message
                    showTemporaryMessage('Folder name updated successfully!', 'success');
                } else {
                    alert('Error: ' + response.data.message);
                }
            },
            error: function(xhr, status, error) {
                $saveButton.prop('disabled', false).text('Save');
                console.error('AJAX Error:', error);
                alert('AJAX error updating folder name. Check console for details.');
            }
        });
    }

    // ===== HELPER FUNCTIONS =====

    // Simple popup function
    function openPopup(content) {
        $('.popup-overlay').remove();
        
        const popupOverlay = $('<div class="popup-overlay"></div>');
        const popupContent = $(`<div class="popup-content">${content}</div>`);
        
        popupOverlay.append(popupContent);
        $('body').append(popupOverlay);
        
        // Basic styling
        popupOverlay.css({
            'position': 'fixed',
            'top': 0,
            'left': 0,
            'width': '100%',
            'height': '100%',
            'background': 'rgba(0,0,0,0.5)',
            'z-index': 10000,
            'display': 'flex',
            'justify-content': 'center',
            'align-items': 'center'
        });
        
        popupContent.css({
            'background': 'white',
            'padding': '20px',
            'border-radius': '5px',
            'min-width': '300px'
        });
        
        // Close on overlay click
        popupOverlay.on('click', function(e) {
            if ($(e.target).is('.popup-overlay')) {
                popupOverlay.remove();
            }
        });
    }

    // Function to show temporary messages
    function showTemporaryMessage(message, type = 'success') {
        const messageClass = type === 'success' ? 'notice notice-success' : 'notice notice-error';
        const messageHTML = `<div class="${messageClass} is-dismissible" style="margin: 10px 0; position: fixed; top: 50px; right: 20px; z-index: 10000;">
            <p>${message}</p>
        </div>`;
        
        $('body').append(messageHTML);
        
        setTimeout(function() {
            $('.notice').fadeOut(300, function() {
                $(this).remove();
            });
        }, 3000);
    }

    // ===== INITIALIZATION =====

    // Initialize drag & drop
    if ($('#folders-sortable').length) {
        enableFoldersDragAndDrop();
    }

    // Initialize folder name editing
    initFolderNameEditing();

    // Add style for drag handle
    $('head').append(`
        <style>
            .ui-sortable-placeholder {
                height: 80px !important;
                background: #f8f9fa !important;
                border: 2px dashed #0073aa !important;
                visibility: visible !important;
                border-radius: 5px;
            }
        </style>
    `);
});