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

    // ===== LOADING FUNCTIONS =====
    function showLoading(message = 'Loading...') {
        $('.loading-overlay').remove();
        
        const loadingHTML = `
            <div class="loading-overlay">
                <div class="loading-content">
                    <div class="loading-spinner"></div>
                    <p style="margin-top: 15px; font-size: 16px; color: #333;">${message}</p>
                </div>
            </div>
        `;
        
        $('body').append(loadingHTML);
    }

    function hideLoading() {
        $('.loading-overlay').fadeOut(300, function() {
            $(this).remove();
        });
    }

    function disableButton(button, showSpinner = true) {
        const $button = $(button);
        $button.prop('disabled', true);
        if (showSpinner) {
            $button.addClass('button-loading');
        }
    }

    function enableButton(button) {
        const $button = $(button);
        $button.prop('disabled', false);
        $button.removeClass('button-loading');
    }

    // ===== CONTENT COUNT UPDATE FUNCTION =====
    function updateFolderContentCount(folderId) {
        console.log('Refreshing page to update content count...');
        
        // 🔥 REFRESH PAGE
        location.reload();
    }

    // ===== FOLDER NAME EDITING IN DETAILS PAGE =====

    // Function to handle folder name editing in details page
    function initFolderNameEditingInDetails() {
        $('.folder-edit-icon').off('click').on('click', function() {
            const folderId = $(this).data('folder-id');
            const currentName = $(this).data('folder-name');
            
            editFolderNameInDetails(folderId, currentName, $(this));
        });
    }

    // Function to open edit dialog in details page
    function editFolderNameInDetails(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;
            }
            
            updateFolderNameInDetails(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 in details page
    function updateFolderNameInDetails(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-details-title`).text('Folder: ' + newName);
                    
                    // Update the edit icon data attribute
                    editIcon.attr('data-folder-name', newName);
                    
                    // Show success message
                    const confirmationMessage = `<h3>Folder name updated successfully!</h3>`;
                    openPopup(confirmationMessage, true);
                } 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.');
            }
        });
    }

    // Function to update duplicate icons
    function updateDuplicateIcons() {
        console.log('Updating duplicate icons...');
        
        // Enable all duplicate icons
        $('.duplicate-content-icon, .duplicate-content-mobile').each(function() {
            $(this).css('opacity', '1')
                   .css('cursor', 'pointer')
                   .off('click.duplicate') // Remove only duplicate handlers
                   .on('click.duplicate', function(e) {
                       e.preventDefault();
                       e.stopPropagation();
                       
                       console.log('Duplicate icon clicked');
                       const contentId = $(this).data('content-id');
                       const folderId = $('#add-page-btn').data('folder-id');
                       
                       if (!contentId) {
                           console.error('No content ID found');
                           return;
                       }
                       
                       if (confirm('Do you want to duplicate this content? A copy will be created with the same name plus "- Copy".')) {
                           duplicateContent(folderId, contentId);
                       }
                   });
        });
        
        console.log('Duplicate icons updated, count:', $('.duplicate-content-icon, .duplicate-content-mobile').length);
    }

    // ===== MOBILE CONTENT MENU FUNCTION =====
    function initMobileContentMenus() {
        // Hamburger menu toggle
        $('.content-menu-toggle').off('click').on('click', function(e) {
            e.stopPropagation();
            const $menu = $(this).siblings('.content-dropdown-menu');
            $('.content-dropdown-menu').not($menu).removeClass('show');
            $menu.toggleClass('show');
        });
        
        // Close menu by clicking outside
        $(document).on('click', function() {
            $('.content-dropdown-menu').removeClass('show');
        });
        
        // Prevent closing when clicking on menu
        $('.content-dropdown-menu').on('click', function(e) {
            e.stopPropagation();
        });
                      
        // Mobile actions - Delete
        $('.delete-content-mobile').off('click').on('click', function() {
            const contentId = $(this).data('content-id');
            const folderId = $('#add-page-btn').data('folder-id');
            
            $('.content-dropdown-menu').removeClass('show');
            
            if (confirm('Are you sure you want to delete this content?')) {
                deleteContentFromFolder(folderId, contentId);
            }
        });
        
        // Mobile actions - Duplicate
        $('.duplicate-content-mobile').off('click').on('click', function() {
            const contentId = $(this).data('content-id');
            const folderId = $('#add-page-btn').data('folder-id');
            
            $('.content-dropdown-menu').removeClass('show');
            
            if (confirm('Do you want to duplicate this content? A copy will be created with the same name plus "- Copy".')) {
                duplicateContent(folderId, contentId);
            }
        });
    }

    // Function to enable drag-and-drop
    function enableDragAndDrop() {
        console.log('Enabling drag and drop...');
        
        $('.pages-container').sortable({
            handle: '.content-drag',
            axis: 'y',
            placeholder: 'content-placeholder',
            tolerance: 'pointer',
            start: function(e, ui) {
                ui.placeholder.height(ui.item.height());
            },
            update: function(event, ui) {
                const contentOrder = $('.content-block').map(function() {
                    return $(this).data('content-id');
                }).get();

                console.log('Saving content order:', contentOrder);
                showLoading('Saving order...');

                $.ajax({
                    url: fold82smData.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'fold82sm_save_page_order',
                        nonce: fold82smData.nonce,
                        order: contentOrder,
                        folder_id: $('#add-page-btn').data('folder-id')
                    },
                    success: function(response) {
                        console.log('Save order response:', response);
                        hideLoading();
                        if (!response.success) {
                            alert('Error saving content order.');
                        } else {
                            showTemporaryMessage('Content order saved successfully!', 'success');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('Error saving order:', error);
                        hideLoading();
                        alert('Error saving order.');
                    }
                });
            }
        }).disableSelection();
        
        console.log('Drag and drop enabled');
    }

    // Function to load content in folder
    function loadContentInFolder(folderId) {
        console.log('Loading content for folder:', folderId);
        showLoading('Loading content...');
        
        // Get current page and per_page from URL for AJAX call
        const urlParams = new URLSearchParams(window.location.search);
        const currentPage = urlParams.get('paged') ? parseInt(urlParams.get('paged')) : 1;
        const perPage = urlParams.get('per_page') ? parseInt(urlParams.get('per_page')) : 10;
        
        console.log('AJAX pagination params - Page:', currentPage, 'Per page:', perPage);
        
        $.ajax({
            url: fold82smData.ajax_url,
            type: 'POST',
            data: {
                action: 'fold82sm_get_content_in_folder',
                folder_id: folderId,
                page: currentPage,
                per_page: perPage,
                nonce: fold82smData.nonce
            },
            success: function(response) {
                console.log('Content loaded:', response);
                hideLoading();
                if (response.success) {
                    let contentHtml = '';
                    
                    if (response.data.content && response.data.content.length > 0) {
                        // Build content HTML
                        response.data.content.forEach(function(item) {
                            contentHtml += `<div class="content-block" data-content-id="${item.id}">
                                        <i class="dashicons dashicons-move content-drag" title="Drag"></i>
                                        <h2 class="content-title">${item.title} <span class="content-type-badge">${item.type}</span></h2>
                                        
                                        <!-- Desktop actions - visible on large screens -->
                                        <div class="content-actions">
                                            <a href="${item.view_url}" target="_blank">
                                                <i class="dashicons dashicons-visibility" title="View"></i>
                                            </a>
                                            <a href="${item.edit_url}">
                                                <i class="dashicons dashicons-edit" title="Edit"></i>
                                            </a>
                                            <a href="javascript:void(0);" class="duplicate-content-icon" data-content-id="${item.id}">
                                                <i class="dashicons dashicons-admin-page" title="Duplicate"></i>
                                            </a>
                                            <a href="javascript:void(0);" class="delete-content-icon" data-content-id="${item.id}">
                                                <i class="dashicons dashicons-trash" title="Delete"></i>
                                            </a>
                                        </div>
                                        
                                        <!-- Mobile actions - visible on small screens -->
                                        <div class="content-actions-menu">
                                            <button class="content-menu-toggle">
                                                <i class="dashicons dashicons-menu-alt3" title="Actions menu"></i>
                                            </button>
                                            <div class="content-dropdown-menu">
                                                <a href="${item.view_url}" target="_blank" class="content-dropdown-item">
                                                    <i class="dashicons dashicons-visibility"></i>
                                                    View
                                                </a>
                                                <a href="${item.edit_url}" class="content-dropdown-item">
                                                    <i class="dashicons dashicons-edit"></i>
                                                    Edit
                                                </a>
                                                <a href="javascript:void(0);" class="content-dropdown-item duplicate-content-mobile" data-content-id="${item.id}">
                                                    <i class="dashicons dashicons-admin-page"></i>
                                                    Duplicate
                                                </a>
                                                <a href="javascript:void(0);" class="content-dropdown-item delete-content-mobile" data-content-id="${item.id}">
                                                    <i class="dashicons dashicons-trash"></i>
                                                    Delete
                                                </a>
                                            </div>
                                        </div>
                                     </div>`;
                        });
                        
                    } else if (response.data.empty_state) {
                        // Use custom empty-folder HTML provided by PHP
                        contentHtml = response.data.empty_html;
                    } else {
                        // Fallback for safety
                        contentHtml = '<div style="text-align: center; padding: 40px; color: #666;">No content found in this folder.</div>';
                    }
                    
                    // Insert content into the content container
                    $('.pages-container').html(contentHtml);
                    
                    // Initialize other functionalities - IMPORTANT ORDER!
                    enableDragAndDrop();
                    initMobileContentMenus();
                    updateDuplicateIcons(); 
                    bindContentActions(folderId); 
                    
                    console.log('Content loaded successfully');
                } else {
                    $('.pages-container').html('<div style="text-align: center; padding: 40px; color: #666;">Error loading content: ' + response.data.message + '</div>');
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX error loading content:', error);
                hideLoading();
                $('.pages-container').html('<div style="text-align: center; padding: 40px; color: #666;">AJAX error loading content. Please refresh the page.</div>');
            }
        });
    }

    // Function to bind content actions
    function bindContentActions(folderId) {
        console.log('Binding content actions for folder:', folderId);
        
        // Bind click event for trash icon (desktop)
        $('.delete-content-icon').off('click.delete').on('click.delete', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            const contentId = $(this).data('content-id');
            
            if (confirm('Are you sure you want to delete this content?')) {
                deleteContentFromFolder(folderId, contentId);
            }
        });

        // Bind click event for duplicate icon (desktop)
        $('.duplicate-content-icon').off('click.duplicate').on('click.duplicate', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            console.log('Desktop duplicate icon clicked');
            const contentId = $(this).data('content-id');
            
            if (confirm('Do you want to duplicate this content? A copy will be created with the same name plus "- Copy".')) {
                duplicateContent(folderId, contentId);
            }
        });

        // Bind click event for duplicate mobile (mobile)
        $('.duplicate-content-mobile').off('click.duplicate').on('click.duplicate', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            console.log('Mobile duplicate icon clicked');
            const contentId = $(this).data('content-id');
            
            if (confirm('Do you want to duplicate this content? A copy will be created with the same name plus "- Copy".')) {
                duplicateContent(folderId, contentId);
            }
        });
    }

    // Function to duplicate content
    function duplicateContent(folderId, contentId) {
        showLoading('Duplicating content...');
        
        $.ajax({
            url: fold82smData.ajax_url,
            type: 'POST',
            data: {
                action: 'fold82sm_duplicate_page',
                page_id: contentId,
                folder_id: folderId,
                nonce: fold82smData.nonce
            },
            success: function(response) {
                hideLoading();
                if (response.success) {
                    const confirmationMessage = `<h3>Content duplicated successfully!</h3>`;
                    openPopup(confirmationMessage, true);
                    loadContentInFolder(folderId);
                    updateFolderContentCount(folderId);
                } else {
                    alert('Error during duplication: ' + response.data.message);
                }
            },
            error: function() {
                hideLoading();
                alert('AJAX error during content duplication.');
            }
        });
    }

    // Function to delete content directly from block
    function deleteContentFromFolder(folderId, contentId) {
        showLoading('Deleting content...');
        
        $.ajax({
            url: fold82smData.ajax_url,
            type: 'POST',
            data: {
                action: 'fold82sm_remove_content_from_folder',
                folder_id: folderId,
                content_id: contentId,
                nonce: fold82smData.nonce
            },
            success: function(response) {
                hideLoading();
                if (response.success) {
                    loadContentInFolder(folderId);
                } else {
                    alert('Error deleting content: ' + response.data.message);
                }
            },
            error: function() {
                hideLoading();
                alert('AJAX error deleting content.');
            }
        });
    }

    // Function to get available content
    function getAvailableContent(folderId) {
        showLoading('Loading available content...');
        
        $.ajax({
            url: fold82smData.ajax_url,
            type: 'POST',
            data: {
                action: 'fold82sm_get_available_content',
                folder_id: folderId,
                nonce: fold82smData.nonce
            },
            success: function(response) {
                hideLoading();
                if (response.success) {
                    let contentOptions = '<select id="content-select" style="width: 100%; padding: 8px; margin: 10px 0;">';
                    if (response.data.content && response.data.content.length > 0) {
                        response.data.content.forEach(function(item) {
                            contentOptions += `<option value="${item.id}">${item.title} (${item.type})</option>`;
                        });
                    } else {
                        contentOptions += '<option value="">No available content found</option>';
                    }
                    contentOptions += '</select>';

                    const popupContent = `
                        <h3>Select content to add to the folder</h3>
                        ${contentOptions}
                        <div style="display: flex; gap: 10px; margin-top: 15px;">
                            <button id="confirm-add-content" class="button button-primary">Add Content</button>
                            <button id="cancel-add-content" class="button">Cancel</button>
                        </div>
                    `;
                    openPopup(popupContent);

                    $('#confirm-add-content').off('click').on('click', function() {
                        const selectedContentId = $('#content-select').val();
                        
                        if (selectedContentId) {
                            addContentToFolder(folderId, selectedContentId);
                        } else {
                            alert('Please select valid content.');
                        }
                    });

                    $('#cancel-add-content').on('click', function() {
                        $('.popup-overlay').fadeOut(function() {
                            $(this).remove();
                        });
                    });
                } else {
                    alert('Error loading available content: ' + response.data.message);
                }
            },
            error: function() {
                hideLoading();
                alert('AJAX error loading available content.');
            }
        });
    }

    // Function to open popup
    function openPopup(content, autoClose = false) {
        $('.popup-overlay, .popup-content').remove();

        const popupOverlay = $('<div class="popup-overlay"></div>');
        const popupContent = $(`<div class="popup-content">${content}</div>`);

        popupOverlay.append(popupContent);
        $('body').append(popupOverlay);

        popupContent.css({
            'position': 'fixed',
            'top': '50%',
            'left': '50%',
            'transform': 'translate(-50%, -50%)',
            'background-color': '#fff',
            'padding': '20px',
            'box-shadow': '0 0 10px rgba(0, 0, 0, 0.5)',
            'z-index': 1002,
            'min-width': '400px',
            'border-radius': '8px'
        });

        popupOverlay.css({
            'position': 'fixed',
            'top': 0,
            'left': 0,
            'width': '100%',
            'height': '100%',
            'background': 'rgba(0, 0, 0, 0.5)',
            'z-index': 1001
        }).fadeIn();

        popupOverlay.on('click', function(event) {
            if ($(event.target).is('.popup-overlay')) {
                popupOverlay.fadeOut(function() {
                    $(this).remove();
                });
            }
        });

        if (autoClose) {
            setTimeout(function() {
                popupOverlay.fadeOut(function() {
                    $(this).remove();
                });
            }, 3000);
        }
    }

    // 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);
    }

    // Function to add content to folder
    function addContentToFolder(folderId, contentId) {
        const $addButton = $('#confirm-add-content');
        
        disableButton($addButton);
        showLoading('Adding content...');
        
        $.ajax({
            url: fold82smData.ajax_url,
            type: 'POST',
            data: {
                action: 'fold82sm_add_content_to_folder',
                folder_id: folderId,
                content_id: contentId,
                nonce: fold82smData.nonce
            },
            success: function(response) {
                hideLoading();
                enableButton($addButton);
                
                if (response.success) {
                    $('.popup-overlay').fadeOut(function() {
                        $(this).remove();
                    });

                    const confirmationMessage = `<h3>Content added successfully!</h3>`;
                    openPopup(confirmationMessage, true);
                    loadContentInFolder(folderId);
                    updateFolderContentCount(folderId);
                } else {
                    alert('Error: ' + response.data.message);
                }
            },
            error: function() {
                hideLoading();
                enableButton($addButton);
                alert('AJAX error adding content.');
            }
        });
    }

    // Function to remove content
    function removeContentFromFolder(folderId) {
        showLoading('Loading content...');
        
        $.ajax({
            url: fold82smData.ajax_url,
            type: 'POST',
            data: {
                action: 'fold82sm_get_content_in_folder',
                folder_id: folderId,
                nonce: fold82smData.nonce
            },
            success: function(response) {
                hideLoading();
                if (response.success && response.data.content && response.data.content.length > 0) {
                    let contentOptions = '<select id="content-select" style="width: 100%; padding: 8px; margin: 10px 0;">';
                    response.data.content.forEach(function(item) {
                        contentOptions += `<option value="${item.id}">${item.title} (${item.type})</option>`;
                    });
                    contentOptions += '</select>';

                    const popupContent = `
                        <h3>Select content to remove</h3>
                        ${contentOptions}
                        <div style="display: flex; gap: 10px; margin-top: 15px;">
                            <button id="confirm-remove-content" class="button">Remove Content</button>
                            <button id="cancel-popup" class="button">Cancel</button>
                        </div>
                    `;
                    
                    openPopup(popupContent);

                    $('#confirm-remove-content').off('click').on('click', function() {
                        const selectedContentId = $('#content-select').val();
                        
                        if (selectedContentId) {
                            $('.popup-overlay').fadeOut(function() {
                                $(this).remove();
                            });

                            showLoading('Removing content...');
                            
                            $.ajax({
                                url: fold82smData.ajax_url,
                                type: 'POST',
                                data: {
                                    action: 'fold82sm_remove_content_from_folder',
                                    folder_id: folderId,
                                    content_id: selectedContentId,
                                    nonce: fold82smData.nonce
                                },
                                success: function(response) {
                                    hideLoading();
                                    if (response.success) {
                                        const confirmationMessage = `<h3>Content removed successfully!</h3>`;
                                        openPopup(confirmationMessage, true);
                                        loadContentInFolder(folderId);
                                        updateFolderContentCount(folderId);
                                    } else {
                                        alert('Error: ' + response.data.message);
                                    }
                                },
                                error: function() {
                                    hideLoading();
                                    alert('AJAX error removing content.');
                                }
                            });
                        } else {
                            alert('Please select valid content.');
                        }
                    });

                    $('#cancel-popup').off('click').on('click', function() {
                        $('.popup-overlay').fadeOut(function() {
                            $(this).remove();
                        });
                    });
                } else {
                    alert('No content found in this folder to remove.');
                }
            },
            error: function() {
                hideLoading();
                alert('AJAX error loading content.');
            }
        });
    }

    // Function to delete a folder
    function deleteFolder(folderId) {
        const $deleteButton = $('#confirm-delete-folder');
        
        disableButton($deleteButton);
        showLoading('Deleting folder...');
        
        $.ajax({
            url: fold82smData.ajax_url,
            type: 'POST',
            data: {
                action: 'fold82sm_delete_folder',
                folder_id: folderId,
                nonce: fold82smData.nonce
            },
            success: function(response) {
                hideLoading();
                enableButton($deleteButton);
                
                if (response.success) {
                    $('.popup-overlay').fadeOut(function() {
                        $(this).remove();
                    });

                    const confirmationMessage = `<h3>Folder deleted successfully!</h3>`;
                    openPopup(confirmationMessage, true);

                    setTimeout(function() {
                        window.location.href = 'admin.php?page=folderra-sfo-folders';
                    }, 2000);
                } else {
                    alert('Error deleting folder: ' + response.data.message);
                }
            },
            error: function() {
                hideLoading();
                enableButton($deleteButton);
                alert('AJAX error deleting folder.');
            }
        });
    }

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

    // Load folder content on page load
    const folderId = $('#add-page-btn').data('folder-id');

    console.log('Initializing folder details page with folder ID:', folderId);

    if (folderId) {
        loadContentInFolder(folderId);  
    } else {
        console.error('No folder ID found');
        $('.pages-container').html('<div style="text-align: center; padding: 40px; color: #666;">Error: No folder ID specified.</div>');
    }

    // Initialize folder name editing in details page
    initFolderNameEditingInDetails();

    // Handle button clicks
    $('#add-page-btn').on('click', function() {
        const $button = $(this);
        if ($button.prop('disabled')) {
            return; // Do nothing if button is disabled
        }
        getAvailableContent(folderId);
    });

    // Existing handlers remain the same
    $('#remove-page-btn').on('click', function() {
        removeContentFromFolder(folderId);
    });

    $('#delete-folder-btn').on('click', function() {
        const popupContent = `
            <h3>Are you sure you want to delete this folder?</h3>
            <p>This action cannot be undone.</p>
            <div style="display: flex; gap: 10px; margin-top: 15px;">
                <button id="confirm-delete-folder" class="button button-link-delete">Delete Folder</button>
                <button id="cancel-delete-folder" class="button">Cancel</button>
            </div>
        `;
        openPopup(popupContent);

        $('#confirm-delete-folder').on('click', function() {
            deleteFolder(folderId);
        });

        $('#cancel-delete-folder').on('click', function() {
            $('.popup-overlay').fadeOut(function() {
                $(this).remove();
            });
        });
    });
});