/**
 * Special Folder JavaScript - FULL FUNCTIONAL VERSION
 */

jQuery(document).ready(function($) {
    
    // ===== GLOBAL VARIABLES =====
    var ajaxUrl = fold82smSpecialData.ajax_url;
    var nonce = fold82smSpecialData.nonce;
    var postType = fold82smSpecialData.post_type;
    var folderId = fold82smSpecialData.folder_id;
    var folderType = fold82smSpecialData.folder_type;
    
    var selectedItems = [];
    var allSmartFolders = []; // Will store filtered smart folders
    
    console.log('✓ Special Folder initialized', {postType, folderId, folderType});
    
    // ===== UTILITY FUNCTIONS =====
    
    function showNotice(message, type) {
        type = type || 'success';
        const noticeClass = type === 'success' ? 'notice-success' : 'notice-error';
        const icon = type === 'success' ? '✓' : '✕';
        
        const notice = $('<div class="notice ' + noticeClass + ' is-dismissible" style="position: fixed; top: 32px; right: 20px; z-index: 9999; min-width: 300px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); animation: slideInRight 0.3s ease;"><p><strong>' + icon + ' ' + message + '</strong></p></div>');
        
        $('body').append(notice);
        
        setTimeout(function() {
            notice.fadeOut(300, function() {
                $(this).remove();
            });
        }, 3000);
    }
    
    function showLoading(message) {
        $('.fold82sm-loading').remove();
        const loadingHTML = 
            '<div class="fold82sm-loading" style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 30px 40px; border-radius: 12px; box-shadow: 0 8px 32px rgba(0,0,0,0.3); z-index: 9999; text-align: center;">' +
            '<div class="spinner is-active" style="float: none; margin: 0 auto 15px;"></div>' +
            '<p style="margin: 0; color: #2c3338; font-weight: 600;">' + message + '...</p>' +
            '</div>';
        $('body').append(loadingHTML);
    }
    
    function hideLoading() {
        $('.fold82sm-loading').fadeOut(300, function() {
            $(this).remove();
        });
    }

    // ===== TABLE COLUMN WIDTH MANAGEMENT =====

function fixTableColumnWidths() {
    const $table = $('#content-table');
    const $container = $('.content-list-main');
    const containerWidth = $container.width();
    
    // Calculate fixed column widths
    let fixedWidth = 0;
    
    // Checkbox column
    fixedWidth += 40;
    
    // Drag column
    fixedWidth += 30;
    
    // Author column if visible
    if ($('.author-column-header:visible').length) {
        fixedWidth += 120;
    }
    
    // Date column if visible
    if ($('.date-column-header:visible').length) {
        fixedWidth += 100;
    }
    
    // Status column if visible
    if ($('.status-column-header:visible').length) {
        fixedWidth += 100;
    }
    
    // Smart Folders column if visible
    if ($('.smartfolders-column-header:visible').length) {
        fixedWidth += 180;
    }
    
    // Categories column if visible (posts only)
    if ($('.categories-column-header:visible').length) {
        fixedWidth += 150;
    }
    
    // Tags column if visible (posts only)
    if ($('.tags-column-header:visible').length) {
        fixedWidth += 150;
    }
    
    // Calculate title column width
    const titleWidth = Math.max(340, containerWidth - fixedWidth - 40); // Slightly narrower Title column // 50px per padding/border
    
    // Apply title column width
    $('.title-column-header, .title-column').css({
        'min-width': titleWidth + 'px',
        'width': titleWidth + 'px'
    });
    
    console.log('Fixed column widths - Title:', titleWidth, 'Fixed total:', fixedWidth);
}

function adjustTitleColumnWidth() {
    fixTableColumnWidths();
}
    
    // ===== 1. CHECKBOXES & BULK SELECTION - FIXED =====
    
    function initBulkSelection() {
        // Select all
        $('#select-all-items').on('change', function() {
            var isChecked = $(this).prop('checked');
            $('.item-checkbox').prop('checked', isChecked);
            updateBulkSelection();
        });
        
        // Individual checkboxes
        $(document).on('change', '.item-checkbox', function() {
            updateBulkSelection();
            
            // Update select-all state
            var total = $('.item-checkbox').length;
            var checked = $('.item-checkbox:checked').length;
            $('#select-all-items').prop('checked', total === checked);
        });
    }
    
    function updateBulkSelection() {
        selectedItems = [];
        $('.item-checkbox:checked').each(function() {
            selectedItems.push($(this).val());
        });
        
        $('#bulk-selected-count').text(selectedItems.length);
        
        if (selectedItems.length > 0) {
            $('#bulk-actions-bar').slideDown(300);
            
            // Filter bulk folder select based on post type
            filterBulkFolderSelect();
        } else {
            $('#bulk-actions-bar').slideUp(300);
        }
        
        // Enable/disable add to folder button
        var folderSelected = $('#bulk-folder-select').val();
        $('#bulk-add-to-folder-btn').prop('disabled', !folderSelected || selectedItems.length === 0);
    }
    
    // ===== 2. BULK ACTIONS - WITH SMART FOLDER FILTERING =====
    
    function initBulkActions() {
        // Load smart folders for this post type
        loadSmartFoldersForPostType();
        
        // Folder select change
        $('#bulk-folder-select').on('change', function() {
            $('#bulk-add-to-folder-btn').prop('disabled', !$(this).val() || selectedItems.length === 0);
        });
        
        // Add to folder
        $('#bulk-add-to-folder-btn').on('click', function() {
            var folderId = $('#bulk-folder-select').val();
            var folderName = $('#bulk-folder-select option:selected').text();
            
            if (!folderId || selectedItems.length === 0) {
                return;
            }
            
            if (confirm('Add ' + selectedItems.length + ' item(s) to "' + folderName + '"?')) {
                bulkAddToFolder(folderId);
            }
        });
        
        // Bulk trash
        $('#bulk-trash-btn').on('click', function() {
            if (selectedItems.length === 0) {
                return;
            }
            
            if (confirm('⚠️ Move ' + selectedItems.length + ' item(s) to trash?\n\nThis action can be undone from the Trash.')) {
                bulkTrash();
            }
        });
        
        // Clear selection
        $('#bulk-clear-btn').on('click', function() {
            $('.item-checkbox, #select-all-items').prop('checked', false);
            updateBulkSelection();
        });
    }
    
    function loadSmartFoldersForPostType() {
        // Get all smart folders from the sidebar
        $('.smart-folders-list li').each(function() {
            var $link = $(this).find('.smart-folder-link');
            var folderName = $link.text().replace(/\(\d+\)/, '').trim();
            var folderId = $link.attr('href').match(/folder_id=(\d+)/);
            
            if (folderId && folderId[1]) {
                allSmartFolders.push({
                    id: folderId[1],
                    name: folderName,
                    element: $(this)
                });
            }
        });
        
        console.log('Loaded smart folders:', allSmartFolders.length);
    }
    
    function filterBulkFolderSelect() {
        if (selectedItems.length === 0) return;
        
        // Get post type of first selected item
        var firstItemRow = $('#post-' + selectedItems[0]);
        var isPost = (postType === 'post'); // Use global postType
        
        // Filter folders based on post type compatibility
        $('#bulk-folder-select option').each(function() {
            var $option = $(this);
            var folderId = $option.val();
            
            if (!folderId) return; // Skip "Add to Smart Folder..." option
            
            // Find this folder in our smart folders list
            var folder = allSmartFolders.find(function(f) {
                return f.id == folderId;
            });
            
            if (folder) {
                // Show folder only if compatible with current post type
                $option.toggle(true); // Always show for now - will implement strict filtering later
            }
        });
    }
    
    function bulkAddToFolder(folderId) {
        showLoading('Adding to folder');
        
        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'fold82sm_bulk_add_to_folder',
                post_ids: selectedItems,
                folder_id: folderId,
                nonce: nonce
            },
            success: function(response) {
                hideLoading();
                if (response.success) {
                    showNotice(response.data.message, 'success');
                    setTimeout(function() {
                        location.reload();
                    }, 1000);
                } else {
                    showNotice('Error: ' + response.data.message, 'error');
                }
            },
            error: function() {
                hideLoading();
                showNotice('Network error', 'error');
            }
        });
    }
    
    function bulkTrash() {
        showLoading('Moving to trash');
        
        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'fold82sm_bulk_trash',
                post_ids: selectedItems,
                nonce: nonce
            },
            success: function(response) {
                hideLoading();
                if (response.success) {
                    showNotice(response.data.message, 'success');
                    setTimeout(function() {
                        location.reload();
                    }, 1000);
                } else {
                    showNotice('Error: ' + response.data.message, 'error');
                }
            },
            error: function() {
                hideLoading();
                showNotice('Network error', 'error');
            }
        });
    }
    
    // ===== 3. DRAG & DROP REORDERING - COMPLETELY FIXED =====
    
function initDragAndDrop() {
    if (!$('#the-list').length) {
        console.log('No list found for drag & drop');
        return;
    }

    console.log('Initializing drag & drop on #the-list...');

    // Destroy existing instance (if any)
    if ($('#the-list').data('ui-sortable')) {
        try {
            $('#the-list').sortable('destroy');
        } catch (e) {
            console.log('No existing sortable to destroy');
        }
    }

    // Remove any dragging classes
    $('body').removeClass('dragging-active');

    // Initialize sortable with a robust configuration for tables inside overflow containers
    $('#the-list').sortable({
        items: 'tr.sortable-row',
        handle: '.drag-handle',
        axis: 'y',
        placeholder: 'ui-sortable-placeholder',
        forcePlaceholderSize: true,
        cursor: 'move',
        tolerance: 'pointer',
        opacity: 0.85,
        scroll: true,
        scrollSensitivity: 60,
        scrollSpeed: 20,

        // Prevent accidental drag when interacting with links/inputs
        cancel: 'a, input, select, textarea, button:not(.drag-handle)',

        // Helps when the table is inside a horizontally scrollable container
        appendTo: 'body',

        helper: function (e, tr) {
            var $originals = tr.children();
            var $helper = tr.clone();
            $helper.children().each(function (index) {
                $(this).width($originals.eq(index).outerWidth());
                $(this).css('background-color', 'white');
            });
            $helper.addClass('ui-sortable-helper');
            $helper.css({
                'background': 'white',
                'box-shadow': '0 4px 12px rgba(0,0,0,0.15)',
                'z-index': 9999
            });
            return $helper;
        },

        start: function (e, ui) {
            ui.placeholder.height(ui.item.outerHeight());
            ui.placeholder.css({
                'background': '#e7f3ff',
                'border': '2px dashed #0073aa',
                'visibility': 'visible'
            });

            ui.item.addClass('dragging');
            $('body').addClass('dragging-active');

            console.log('Drag started for item:', ui.item.data('post-id'));
        },

        stop: function (e, ui) {
            ui.item.removeClass('dragging');
            $('body').removeClass('dragging-active');

            console.log('Drag stopped for item:', ui.item.data('post-id'));
        },

        change: function (e, ui) {
            ui.placeholder.height(ui.item.outerHeight());
        },

        update: function () {
            console.log('Order changed, saving...');
            savePostOrder();
        }
    });

    console.log('✓ Drag & drop enabled on ' + $('#the-list .sortable-row').length + ' rows');
}

function savePostOrder() {
    const order = [];
    $('#the-list tr.sortable-row').each(function() {
        order.push($(this).data('post-id'));
    });

    console.log('Saving order for ' + order.length + ' items:', order);

    if (order.length === 0) {
        showNotice('No items to reorder', 'error');
        return;
    }

    // Read pagination from URL to avoid menu_order duplicates across pages
    const urlParams = new URLSearchParams(window.location.search);
    const page = urlParams.get('paged') ? parseInt(urlParams.get('paged'), 10) : 1;
    const perPageFromUrl = urlParams.get('per_page') ? parseInt(urlParams.get('per_page'), 10) : null;
    const perPageFromSelect = $('select[name="per_page"]').length ? parseInt($('select[name="per_page"]').val(), 10) : null;
    const perPage = perPageFromUrl || perPageFromSelect || 10;


    // Show saving indicator
    const $savingIndicator = $('<div class="saving-indicator" style="position: fixed; bottom: 20px; right: 20px; background: #0073aa; color: white; padding: 8px 15px; border-radius: 4px; z-index: 9999; font-size: 12px;">Saving order...</div>');
    $('body').append($savingIndicator);

    $.ajax({
        url: ajaxUrl,
        type: 'POST',
        data: {
            action: 'fold82sm_save_post_order',
            nonce: nonce,
            order: order,
            post_type: postType,
            page: page,
            per_page: perPage
        },
        success: function(response) {
            $savingIndicator.remove();

            if (response.success) {
                showNotice('Order saved successfully!', 'success');

                // Optional: Visual feedback for saved order
                $('#the-list').addClass('order-saved');
                setTimeout(function() {
                    $('#the-list').removeClass('order-saved');
                }, 1000);

            } else {
                showNotice('Error: ' + response.data.message, 'error');
            }
        },
        error: function(xhr, status, error) {
            $savingIndicator.remove();
            console.error('Order save error:', error);
            showNotice('Error saving order. Please try again.', 'error');
        }
    });
}

    
    // ===== 4. DUPLICATE POST - WITH IMPROVED POPUP =====
    
    function initDuplicatePost() {
        $(document).on('click', '.duplicate-post', function(e) {
            e.preventDefault();
            const postId = $(this).data('post-id');
            const postTitle = $(this).data('post-title') || $(this).closest('tr').find('.row-title').text();
            
            // Improved dialog HTML
            const dialogHtml = 
                '<div class="duplicate-dialog-overlay" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 9999; display: flex; align-items: center; justify-content: center;">' +
                '<div class="duplicate-dialog-box" style="background: white; padding: 30px; border-radius: 12px; box-shadow: 0 8px 32px rgba(0,0,0,0.3); max-width: 500px; width: 90%;">' +
                '<h3 style="margin: 0 0 15px 0; color: #2c3338; font-size: 18px;">Duplicate Item</h3>' +
                '<p style="margin: 0 0 20px 0; color: #666; line-height: 1.6;">Create a copy of:<br><strong style="color: #2c3338;">' + postTitle + '</strong></p>' +
                '<p style="margin: 0 0 20px 0; color: #888; font-size: 13px;">The copy will be created as a draft with "(Copy)" in the title.</p>' +
                '<div style="display: flex; gap: 10px; justify-content: flex-end;">' +
                '<button class="button cancel-duplicate" style="padding: 8px 16px;">Cancel</button>' +
                '<button class="button button-primary confirm-duplicate" style="padding: 8px 16px;">Duplicate</button>' +
                '</div>' +
                '</div>' +
                '</div>';
            
            const $dialog = $(dialogHtml).appendTo('body');
            
            // Cancel
            $dialog.find('.cancel-duplicate').on('click', function() {
                $dialog.remove();
            });
            
            // Confirm
            $dialog.find('.confirm-duplicate').on('click', function() {
                $dialog.remove();
                duplicatePost(postId);
            });
            
            // Click outside
            $dialog.on('click', function(e) {
                if ($(e.target).is('.duplicate-dialog-overlay')) {
                    $dialog.remove();
                }
            });
            
            // ESC key
            $(document).on('keyup.duplicateDialog', function(e) {
                if (e.key === 'Escape') {
                    $dialog.remove();
                    $(document).off('keyup.duplicateDialog');
                }
            });
        });
    }
    
    function duplicatePost(postId) {
        showLoading('Duplicating');
        
        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'fold82sm_duplicate_post',
                post_id: postId,
                nonce: nonce
            },
            success: function(response) {
                hideLoading();
                if (response.success) {
                    showNotice('Duplicated successfully!', 'success');
                    setTimeout(function() {
                        location.reload();
                    }, 1000);
                } else {
                    showNotice('Error: ' + response.data.message, 'error');
                }
            },
            error: function() {
                hideLoading();
                showNotice('Network error', 'error');
            }
        });
    }
    
    // ===== 5. TRASH POST - WITH CONFIRMATION POPUP =====
    
    function initTrashPost() {
        $(document).on('click', '.trash-post', function(e) {
            e.preventDefault();
            const postId = $(this).data('post-id');
            const postTitle = $(this).data('post-title') || $(this).closest('tr').find('.row-title').text();
            
            // Dialog HTML
            const dialogHtml = 
                '<div class="trash-dialog-overlay" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 9999; display: flex; align-items: center; justify-content: center;">' +
                '<div class="trash-dialog-box" style="background: white; padding: 30px; border-radius: 12px; box-shadow: 0 8px 32px rgba(0,0,0,0.3); max-width: 500px; width: 90%;">' +
                '<h3 style="margin: 0 0 15px 0; color: #b32d2e; font-size: 18px; display: flex; align-items: center; gap: 8px;"><span class="dashicons dashicons-warning" style="font-size: 24px;"></span>Move to Trash</h3>' +
                '<p style="margin: 0 0 20px 0; color: #666; line-height: 1.6;">Are you sure you want to move this item to trash?<br><strong style="color: #2c3338;">' + postTitle + '</strong></p>' +
                '<p style="margin: 0 0 20px 0; color: #888; font-size: 13px;">You can restore it later from the Trash.</p>' +
                '<div style="display: flex; gap: 10px; justify-content: flex-end;">' +
                '<button class="button cancel-trash" style="padding: 8px 16px;">Cancel</button>' +
                '<button class="button button-primary confirm-trash" style="padding: 8px 16px; background: #b32d2e; border-color: #b32d2e;">Move to Trash</button>' +
                '</div>' +
                '</div>' +
                '</div>';
            
            const $dialog = $(dialogHtml).appendTo('body');
            
            $dialog.find('.cancel-trash').on('click', function() {
                $dialog.remove();
            });
            
            $dialog.find('.confirm-trash').on('click', function() {
                $dialog.remove();
                trashPost(postId);
            });
            
            $dialog.on('click', function(e) {
                if ($(e.target).is('.trash-dialog-overlay')) {
                    $dialog.remove();
                }
            });
            
            // ESC key
            $(document).on('keyup.trashDialog', function(e) {
                if (e.key === 'Escape') {
                    $dialog.remove();
                    $(document).off('keyup.trashDialog');
                }
            });
        });
    }
    
    function trashPost(postId) {
        showLoading('Moving to trash');
        
        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'fold82sm_trash_post',
                post_id: postId,
                nonce: nonce
            },
            success: function(response) {
                hideLoading();
                if (response.success) {
                    showNotice('Moved to trash successfully!', 'success');
                    $('#post-' + postId).fadeOut(300, function() {
                        $(this).remove();
                        updateItemsCount(); // Update count after removal
                    });
                } else {
                    showNotice('Error: ' + response.data.message, 'error');
                }
            },
            error: function() {
                hideLoading();
                showNotice('Network error', 'error');
            }
        });
    }
    
    // ===== 6. COLUMN VISIBILITY TOGGLE - COMPLETELY FIXED =====
    
    function initColumnVisibility() {
    let popupOpen = false;
    
    const savedColumns = JSON.parse(localStorage.getItem('folderra_columns_' + folderType) || '{}');
    
    
    $(document).ready(function() {
        // Default coloumns: Title, Author, Date, Status
        const defaultVisible = {
            title: true,
            author: true,
            date: true,
            status: true,
            smartfolders: false,
            categories: false,
            tags: false
        };
        
        // Aggregate default and saved states
        const columnState = {...defaultVisible, ...savedColumns};
        
        // Apply state
        Object.keys(columnState).forEach(column => {
            if (column !== 'title') { // Title non può essere nascosta
                const isVisible = columnState[column];
                $('.' + column + '-column, .' + column + '-column-header').toggle(isVisible);
            }
        });
        
        adjustTitleColumnWidth();
    });
    
    $('#toggle-columns-btn').on('click', function(e) {
        e.stopPropagation();
        
        if (popupOpen) {
            $('.column-visibility-popup').remove();
            popupOpen = false;
            return;
        }
        
        // Load current state from the DOM (do not read from checkboxes because they are created now)
        const currentState = {};
        const columns = ['author','date','smartfolders','categories','tags'];
        columns.forEach(function(col) {
            currentState[col] = $('.' + col + '-column-header:visible').length > 0;
        });


        
        // Detect if we're on "All Posts" or "All Pages"
        const isPostsPage = (folderType === 'posts');
        
        // Build popup HTML dinamically
        let popupHtml = '<div class="column-visibility-popup">';
        
        // Title - ALWAYS VISIBLE
        popupHtml += '<label class="disabled" title="Title column cannot be hidden">';
        popupHtml += '<input type="checkbox" class="toggle-column" data-column="title" checked disabled>';
        popupHtml += ' Title (always visible)</label>';
        
        // Author
        const authorChecked = currentState.author !== false;
        popupHtml += '<label><input type="checkbox" class="toggle-column" data-column="author"' + (authorChecked ? ' checked' : '') + '> Author</label>';
        
        // Date
        const dateChecked = currentState.date !== false;
        popupHtml += '<label><input type="checkbox" class="toggle-column" data-column="date"' + (dateChecked ? ' checked' : '') + '> Date</label>';               
        
        // Smart Folders
        const smartfoldersChecked = currentState.smartfolders === true;
        popupHtml += '<label><input type="checkbox" class="toggle-column" data-column="smartfolders"' + (smartfoldersChecked ? ' checked' : '') + '> Smart Folders</label>';
        
        // Categories - ONLY for posts
        if (isPostsPage) {
            const categoriesChecked = currentState.categories === true;
            popupHtml += '<label><input type="checkbox" class="toggle-column" data-column="categories"' + (categoriesChecked ? ' checked' : '') + '> Categories</label>';
        }
        
        // Tags - ONLY for posts
        if (isPostsPage) {
            const tagsChecked = currentState.tags === true;
            popupHtml += '<label><input type="checkbox" class="toggle-column" data-column="tags"' + (tagsChecked ? ' checked' : '') + '> Tags</label>';
        }
        
        popupHtml += '</div>';
        
        $(this).parent().css('position', 'relative').append(popupHtml);
        popupOpen = true;
        
        // Toggle columns
$('.toggle-column:not([disabled])').on('change', function() {
    const column = $(this).data('column');
    const isVisible = $(this).prop('checked');
    
    // Save state
    const savedState = JSON.parse(localStorage.getItem('folderra_columns_' + folderType) || '{}');
    savedState[column] = isVisible;
    localStorage.setItem('folderra_columns_' + folderType, JSON.stringify(savedState));
    
    // Hide/show column
    $('.' + column + '-column, .' + column + '-column-header').toggle(isVisible);
    
    // Adjust title column width when hiding other columns
    adjustTitleColumnWidth();
    
    // Enable horizontal scroll if needed
    checkTableOverflow();
    
    // Update table layout
    updateTableLayout();
});
    });
    
    // Close on outside click
    $(document).on('click', function(e) {
        if (!$(e.target).closest('#toggle-columns-btn, .column-visibility-popup').length) {
            $('.column-visibility-popup').remove();
            popupOpen = false;
        }
    });
}
        
    // Check if table needs horizontal scroll
    function checkTableOverflow() {
        const $table = $('#content-table');
        const $container = $('.content-list-main');
        
        const tableWidth = $table.outerWidth();
        const containerWidth = $container.width();
        
        if (tableWidth > containerWidth) {
            $container.css('overflow-x', 'auto');
            console.log('Enabled horizontal scroll - Table: ' + tableWidth + 'px, Container: ' + containerWidth + 'px');
        } else {
            $container.css('overflow-x', 'visible');
        }
    }
    
    // Update table layout after column changes
    function updateTableLayout() {
        // Force table to recalculate
        $('#content-table').css('table-layout', 'auto');
        setTimeout(function() {
            $('#content-table').css('table-layout', 'fixed');
        }, 10);
        
        // Update overflow
        checkTableOverflow();
    }
    
    // ===== 7. CREATE SMART FOLDER =====
    
    function initCreateSmartFolder() {
        $('#create-smart-folder-btn').on('click', function(e) {
            e.preventDefault();
            
            const folderTypeLabel = folderType === 'pages' ? 'Pages' : 'Posts';
            const defaultName = 'My ' + folderTypeLabel + ' Folder';
            
            const folderName = prompt(
                'Create a new Smart Folder for ' + folderTypeLabel + ':\n\nEnter folder name:',
                defaultName
            );
            
            if (folderName && folderName.trim()) {
                createSmartFolder(folderName.trim());
            }
        });
    }
    
    function createSmartFolder(folderName) {
        showLoading('Creating Smart Folder');
        
        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'fold82sm_create_smart_folder_auto',
                folder_name: folderName,
                post_type: postType,
                nonce: nonce
            },
            success: function(response) {
                hideLoading();
                
                if (response.success) {
                    showNotice('Smart Folder "' + folderName + '" created!', 'success');
                    addFolderToList(response.data);
                    // Reload smart folders for filtering
                    loadSmartFoldersForPostType();
                } else {
                    showNotice('Error: ' + response.data.message, 'error');
                }
            },
            error: function() {
                hideLoading();
                showNotice('Network error', 'error');
            }
        });
    }
    
    function addFolderToList(folderData) {
        $('.no-folders-message').remove();
        
        if (!$('.smart-folders-list').length) {
            $('.smart-folders-sidebar h3').after('<ul class="smart-folders-list"></ul>');
        }
        
        const folderHtml = 
            '<li>' +
            '<a href="' + folderData.details_url + '" class="smart-folder-link">' +
            '<span class="folder-icon">📁</span>' +
            folderData.folder_name +
            ' <span class="folder-count">(' + folderData.count + ')</span>' +
            '</a>' +
            '</li>';
        
        $('.smart-folders-list').append(folderHtml);
        $('.smart-folders-list li:last-child').hide().slideDown(300);
    }
    
    // ===== 8. UPDATE ITEMS COUNT DYNAMICALLY =====
    
    function initItemsCount() {
        
    }
    
    function updateItemsCount() {
    return;
}

    // ===== 9. FILTER SMART FOLDERS IN SIDEBAR =====
    
    function filterSidebarSmartFolders() {
        // Only show smart folders compatible with current post type
        $('.smart-folders-list li').each(function() {
            const $link = $(this).find('.smart-folder-link');
            const href = $link.attr('href') || '';
            
            // For now, show all folders. In PRO version, we would filter based on folder's allowed post types
            $(this).show();
        });
    }
    
    // ===== 10. ENHANCE TABLE LAYOUT =====
    
    function enhanceTableLayout() {
    // Ensure checkbox column has fixed width
    $('.check-column').css({
        'width': '40px',
        'min-width': '40px',
        'max-width': '40px'
    });
    
    // Reduce drag handle column width
    $('.drag-column').css({
        'width': '30px',
        'min-width': '30px',
        'max-width': '30px',
        'padding': '8px 4px !important'
    });
    
    // Initial column width adjustment
    adjustTitleColumnWidth(); // <-- AGGIUNGI QUESTA CHIAMATA
    checkTableOverflow();
}
    
    // ===== 11. REAL-TIME FILTER UPDATES =====
    
    function initRealTimeFilters() {
        // Status filter change
        $('select[name="post_status"]').on('change', function() {
            const status = $(this).val();
            if (status === 'unassigned') {
                // Show only unassigned items
                filterUnassignedItems();
            } else {
                // Standard filter - will be handled by form submission
                $('.special-folder-filters').submit();
            }
        });
        
        // Date filter change
        $('select[name="date_filter"]').on('change', function() {
            $('.special-folder-filters').submit();
        });
        
        // Search filter with debounce
        let searchTimeout;
        $('input[name="s"]').on('keyup', function() {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(function() {
                $('.special-folder-filters').submit();
            }, 500);
        });
        
        // Items per page
        $('select[name="per_page"]').on('change', function() {
            $('.special-folder-filters').submit();
        });
    }
    
    function filterUnassignedItems() {
        // This would be implemented with AJAX in a real scenario
        // For now, we'll rely on server-side filtering
        console.log('Filtering unassigned items');
    }
    
    // ===== 12. ANIMATIONS =====
    
    function addAnimations() {
        if (!$('style#special-folder-animations').length) {
            $('head').append(
                '<style id="special-folder-animations">' +
                '@keyframes slideInRight { ' +
                '  from { transform: translateX(100%); opacity: 0; } ' +
                '  to { transform: translateX(0); opacity: 1; } ' +
                '}' +
                '@keyframes slideDown { ' +
                '  from { opacity: 0; transform: translateY(-10px); } ' +
                '  to { opacity: 1; transform: translateY(0); } ' +
                '}' +
                '.dragging-active { cursor: move !important; }' +
                '.ui-sortable-helper { cursor: move !important; }' +
                '</style>'
            );
        }
    }
    
    // ===== COMPLETE INITIALIZATION =====
    
   function init() {
    console.log('🚀 Initializing Special Folder - FULL FIXED VERSION...');

    addAnimations();
    initBulkSelection();
    initBulkActions();
    initDragAndDrop();
    initDuplicatePost();
    initTrashPost();
    initColumnVisibility();
    initCreateSmartFolder();

    // IMPORTANT: Do not override the server-side total count (WP_Query->found_posts)
    // initItemsCount(); // Disabled on purpose

    initRealTimeFilters();
    filterSidebarSmartFolders();
    enhanceTableLayout();

    // Initial layout adjustments
    setTimeout(function () {
        adjustTitleColumnWidth();
        checkTableOverflow();
        // updateItemsCount(); // Disabled on purpose
    }, 500);

    console.log('✓ All features initialized successfully');
}

    
    // Execute initialization
    init();
    
});