// Global variables for navigation
let currentFolderId = null;
let navigationHistory = [];
let tableUpdateInProgress = false; // Flag to prevent conflicts during table updates
let activeShareFolderId = null;
let currentFolderContents = [];
let currentFolderInfo = null;

document.addEventListener('DOMContentLoaded', function() {
    // Form validation for create folder (with null checks)
    var form = document.getElementById('createFolderForm');
    var errorMsg = document.getElementById('clientErrorMsg');
    var modalEl = document.getElementById('createFolderModal');
    // Get folder names from window object (will be set in the blade template)
            // Debug: Log permission before rendering View File link
            console.log('canViewFile permission:', window.permissions && window.permissions.canViewFile);
    var folderNames = window.folderNames || [];

    if (form && errorMsg) {
        form.addEventListener('submit', function(e) {
            e.preventDefault();

            var nameInput = document.getElementById('name');
            var name = nameInput ? nameInput.value.trim() : '';
            var errors = [];

            if (!name) {
                errors.push('Folder name is required.');
            }
            if (folderNames.includes(name)) {
                errors.push('Folder name already exists.');
            }

            if (errors.length > 0) {
                errorMsg.innerHTML = errors.join('<br>');
                errorMsg.classList.remove('d-none');
                return;
            }

            errorMsg.classList.add('d-none');

            // Submit via AJAX to stay at current location
            var formData = new FormData(form);
            // If inside a subfolder, set parent_id so subfolder is created under it
            var parentIdInput = document.getElementById('parent_id');
            if (!parentIdInput.value && currentFolderId) {
                formData.set('parent_id', currentFolderId);
            }

            var submitBtn = form.querySelector('button[type="submit"]');
            var originalText = submitBtn ? submitBtn.innerHTML : '';
            if (submitBtn) {
                submitBtn.innerHTML = '<i class="ri-loader-4-line me-1"></i>Creating...';
                submitBtn.disabled = true;
            }

            fetch(form.action, {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                },
                body: formData
            })
            .then(async response => {
                const contentType = response.headers.get('content-type') || '';
                if (contentType.includes('application/json')) {
                    return response.json().then(data => ({ ok: response.ok, data }));
                }
                // Non-JSON means server redirected (success) — treat as success
                return { ok: response.ok || response.redirected, data: { success: true, message: 'Folder created successfully!' } };
            })
            .then(({ ok, data }) => {
                if (ok && data && data.success !== false) {
                    // Close modal
                    var modalEl = document.getElementById('createFolderModal');
                    var bsModal = bootstrap.Modal.getInstance(modalEl);
                    if (bsModal) bsModal.hide();

                    showToast(data.message || 'Folder created successfully!', 'success');
                    form.reset();

                    // Stay at current location
                    if (currentFolderId) {
                        loadFolderContents(currentFolderId);
                    } else {
                        setTimeout(() => { window.location.reload(); }, 1000);
                    }
                } else {
                    var msg = (data && data.message) ? data.message : 'Failed to create folder.';
                    // Show server-side validation errors if present
                    if (data && data.errors) {
                        var msgs = Object.values(data.errors).flat();
                        errorMsg.innerHTML = msgs.join('<br>');
                        errorMsg.classList.remove('d-none');
                    } else {
                        errorMsg.innerHTML = msg;
                        errorMsg.classList.remove('d-none');
                    }
                }
            })
            .catch(error => {
                console.error('Error creating folder:', error);
                errorMsg.innerHTML = 'Error creating folder: ' + error.message;
                errorMsg.classList.remove('d-none');
            })
            .finally(() => {
                if (submitBtn) {
                    submitBtn.innerHTML = originalText;
                    submitBtn.disabled = false;
                }
            });
        });
    }

    // Clear error message when modal is closed or opened
    if (modalEl && errorMsg && form) {
        modalEl.addEventListener('hidden.bs.modal', function () {
            errorMsg.classList.add('d-none');
            errorMsg.innerHTML = '';
            form.reset();
        });
        modalEl.addEventListener('show.bs.modal', function () {
            errorMsg.classList.add('d-none');
            errorMsg.innerHTML = '';
        });
    }
    
    // Add cleanup for share folder modal
    var shareModalEl = document.getElementById('shareFolderModal');
    if (shareModalEl) {
        shareModalEl.addEventListener('hidden.bs.modal', function () {
            // Properly destroy selectpickers when modal is closed
            try {
                if ($('#shareUsersSelect').hasClass('selectpicker')) {
                    $('#shareUsersSelect').selectpicker('destroy');
                }
                if ($('#shareRolesSelect').hasClass('selectpicker')) {
                    $('#shareRolesSelect').selectpicker('destroy');
                }
            } catch (e) {
                console.log('Error cleaning up selectpickers:', e);
            }
            
            // Clear the share form
            document.getElementById('shareFolderForm').reset();
            activeShareFolderId = null;
            shareModalEl.dataset.folderId = '';
            
            // Clear selections manually
            $('#shareUsersSelect option').prop('selected', false);
            $('#shareRolesSelect option').prop('selected', false);
            document.getElementById('shareUsersSelect').selectedIndex = -1;
            document.getElementById('shareRolesSelect').selectedIndex = -1;
            
            // Clear the permissions table
            clearShareTable();
        });

        shareModalEl.addEventListener('show.bs.modal', function () {
            const shareFolderIdInput = document.getElementById('share_folder_id');
            const folderId = activeShareFolderId || shareModalEl.dataset.folderId || shareFolderIdInput?.value || '';

            if (shareFolderIdInput && folderId) {
                shareFolderIdInput.value = folderId;
            }
        });
        
        // Add event listeners for permission buttons when modal is shown
        shareModalEl.addEventListener('shown.bs.modal', function () {
            console.log('Share modal shown, setting up button listeners...');
            
            // Add event listener for Add Permissions button
            const addBtn = document.getElementById('addPermissionsBtn');
            if (addBtn) {
                // Use onclick assignment to avoid stacking multiple listeners on every modal open
                addBtn.onclick = function(e) {
                    console.log('Add permissions button clicked');
                    
                    if (typeof addPermissions === 'function') {
                        addPermissions();
                    } else {
                        console.error('addPermissions function not found');
                    }
                };
                console.log('Add button listener attached');
            } else {
                console.error('addPermissionsBtn not found!');
            }
        });
    }
});

// Navigation functions
function openFolder(folderId, folderName) {
    navigationHistory.push({
        id: currentFolderId,
        view: currentFolderId ? 'table' : 'grid'
    });
    
    currentFolderId = folderId;
    updateBreadcrumb(folderName);
    document.getElementById('backBtn').classList.remove('initially-hidden');
    document.getElementById('gridView').classList.add('d-none');
    document.getElementById('tableView').classList.remove('d-none');
    loadFolderContents(folderId);
}

function navigateBack() {
    if (navigationHistory.length > 0) {
        const previousState = navigationHistory.pop();
        currentFolderId = previousState.id;
        
        if (previousState.view === 'grid') {
            currentFolderContents = [];
            currentFolderInfo = null;
            document.getElementById('tableView').classList.add('d-none');
            document.getElementById('gridView').classList.remove('d-none');
            document.getElementById('backBtn').classList.add('initially-hidden');
            updateBreadcrumb();
        } else {
            loadFolderContents(currentFolderId);
        }
    }
}

function navigateToRoot() {
    navigationHistory = [];
    currentFolderId = null;
    currentFolderContents = [];
    currentFolderInfo = null;
    document.getElementById('tableView').classList.add('d-none');
    document.getElementById('gridView').classList.remove('d-none');
    document.getElementById('backBtn').classList.add('initially-hidden');
    updateBreadcrumb();
}

function updateBreadcrumb(folderName = null) {
    const breadcrumb = document.getElementById('folderBreadcrumb');
    
    if (!folderName) {
        breadcrumb.innerHTML = `
            <li class="breadcrumb-item active">
                <i class="ri-home-4-line me-1"></i>Root
            </li>
        `;
    } else {
        breadcrumb.innerHTML = `
            <li class="breadcrumb-item">
                <a href="#" onclick="navigateToRoot()" class="text-primary">
                    <i class="ri-home-4-line me-1"></i>Root
                </a>
            </li>
            <li class="breadcrumb-item active">
                <i class="ri-folder-line me-1"></i>${folderName}
            </li>
        `;
    }
}

function loadFolderContents(folderId) {
    const tableBody = document.getElementById('folderTableBody');
    tableBody.innerHTML = `
        <tr>
            <td colspan="5" class="text-center py-4">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <div class="mt-2">Loading folder contents...</div>
            </td>
        </tr>
    `;
    
    // Debug: Log the URL being called
    console.log('Loading folder contents for ID:', folderId);
    
    // Get the base URL from window object (will be set in the blade template)
    const baseUrl = window.baseUrl || '';
    const url = `${baseUrl}/folders/${folderId}/contents`;
    console.log('URL:', url);
    
    // Fetch actual folder contents
    fetch(url, {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        }
    })
    .then(response => {
        console.log('Response status:', response.status);
        console.log('Response headers:', response.headers);
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        return response.text(); // Get as text first to debug
    })
    .then(text => {
        console.log('Raw response:', text); // Debug log
        
        try {
            const data = JSON.parse(text);
            if (data.success) {
                currentFolderContents = Array.isArray(data.contents) ? data.contents : [];
                currentFolderInfo = data.folder || { id: folderId };
                applyCurrentViewFilters();
            } else {
                throw new Error(data.message || 'Failed to load folder contents');
            }
        } catch (parseError) {
            console.error('JSON parse error:', parseError);
            console.error('Response text:', text);
            throw new Error('Invalid JSON response from server');
        }
    })
    .catch(error => {
        console.error('Error loading folder contents:', error);
        tableBody.innerHTML = `
            <tr>
                <td colspan="5" class="text-center text-danger py-4">
                    <i class="ri-error-warning-line font-size-24 mb-2 d-block"></i>
                    Error loading folder contents: ${error.message}
                    <div class="mt-2">
                        <small class="text-muted">Check browser console for details</small>
                    </div>
                </td>
            </tr>
        `;
    });
}

function displayFolderContents(contents, folderInfo) {
    const tableBody = document.getElementById('folderTableBody');

    if (contents.length === 0) {
        tableBody.innerHTML = `
            <tr>
                <td colspan="5" class="text-center text-muted py-4">
                    <i class="ri-folder-line font-size-24 mb-2 d-block"></i>
                    This folder is empty
                    <div class="mt-2">
                        <button type="button" class="btn btn-primary btn-sm" 
                                data-bs-toggle="modal" 
                                data-bs-target="#createFolderModal" 
                                onclick="document.getElementById('parent_id').value = '${folderInfo.id}';">
                            <i class="ri-folder-add-line me-1"></i> Create Subfolder
                        </button>
                    </div>
                </td>
            </tr>
        `;
        return;
    }

    const csrfToken = window.csrfToken || '';
    let tableHTML = '';
    contents.forEach(item => {
        if (item.type === 'folder') {
            tableHTML += `
                <tr onclick="openFolder(${item.id}, '${item.name.replace(/'/g, "\\'")})'" style="cursor: pointer;">
                    <td>
                        <div class="d-flex align-items-center">
                            <i class="ri-folder-fill folder-icon-table me-2"></i>
                            <span class="fw-medium">${item.name}</span>
                        </div>
                    </td>
                    <td>
                        <span class="badge bg-warning-subtle text-warning">
                            <i class="ri-folder-line me-1"></i>Folder
                        </span>
                    </td>
                    <td>
                        <span class="text-muted">
                            ${item.items_count} ${item.items_count === 1 ? 'item' : 'items'}
                        </span>
                    </td>
                    <td>
                        <small class="text-muted">${item.updated_at}</small>
                    </td>
                    <td>
                        <div class="dropdown">
                            <button class="btn btn-link p-0 text-muted" type="button" data-bs-toggle="dropdown" aria-expanded="false" onclick="event.stopPropagation();">
                                <i class="ri-more-2-fill"></i>
                            </button>
                            <ul class="dropdown-menu dropdown-menu-end shadow-sm">
                                <li>
                                    <a class="dropdown-item" href="#" onclick="openFolder(${item.id}, '${item.name.replace(/'/g, "\\'")}'); event.stopPropagation();">
                                        <i class="ri-folder-open-line me-2 text-primary"></i>
                                        Open Folder
                                    </a>
                                </li>
                                <li>
                                    <a class="dropdown-item" href="#" 
                                       data-bs-toggle="modal" 
                                       data-bs-target="#createFolderModal" 
                                       onclick="document.getElementById('parent_id').value = '${item.id}'; event.stopPropagation();">
                                        <i class="ri-add-line me-2 text-success"></i>
                                        Add Subfolder
                                    </a>
                                </li>
                                <li>
                                    <a class="dropdown-item" href="#" 
                                       data-bs-toggle="modal" 
                                       data-bs-target="#shareFolderModal" 
                                       onclick="openShareModal(${item.id}, '${item.name.replace(/'/g, "\\'")}'); event.stopPropagation(); return false;">
                                        <i class="ri-share-line me-2 text-warning"></i>
                                        Share Folder
                                    </a>
                                </li>
                                <li><hr class="dropdown-divider"></li>
                                <li>
                                    <button type="button" class="dropdown-item text-danger" 
                                            onclick="deleteFolder(${item.id}, '${item.name.replace(/'/g, "\\'")}'); event.stopPropagation();">
                                        <i class="ri-delete-bin-line me-2"></i>
                                        Delete Folder
                                    </button>
                                </li>
                            </ul>
                        </div>
                    </td>
                </tr>
            `;
        } else if (item.type === 'file') {
            // Determine file icon by extension
            let ext = '';
            let icon = 'ri-file-3-line';
            if (item.name) {
                ext = item.name.split('.').pop().toLowerCase();
                if (ext === 'pdf') icon = 'ri-file-pdf-line text-danger';
                else if (["doc","docx"].includes(ext)) icon = 'ri-file-word-line text-primary';
                else if (["xls","xlsx"].includes(ext)) icon = 'ri-file-excel-line text-success';
                else if (["ppt","pptx"].includes(ext)) icon = 'ri-file-ppt-line text-warning';
                else if (["jpg","jpeg","png","gif"].includes(ext)) icon = 'ri-image-line text-info';
            }
            // Build file preview URL (match my_folder.blade.php logic)
            let fileUrl = '';
            if (ext === 'pdf') {
                fileUrl = `${window.baseUrl}/files/ajax-preview-pdf?file_name=${encodeURIComponent(item.name)}&folder_id=${encodeURIComponent(item.folder_id)}`;
            } else if (["doc","docx","xls","xlsx","ppt","pptx"].includes(ext)) {
                fileUrl = `${window.baseUrl}/files/stream-office?file_name=${encodeURIComponent(item.name)}&folder_id=${encodeURIComponent(item.folder_id)}`;
            } else {
                fileUrl = `${window.baseUrl}/files/view?file_name=${encodeURIComponent(item.name)}&folder_id=${encodeURIComponent(item.folder_id)}&view_mode=inline`;
            }
            tableHTML += `
                <tr>
                    <td>
                        <div class="d-flex align-items-center">
                            <i class="${icon} me-2"></i>
                            <span class="fw-medium">${item.name}</span>
                        </div>
                    </td>
                    <td>
                        <span class="badge bg-info-subtle text-info">
                            <i class="ri-file-line me-1"></i>File
                        </span>
                    </td>
                    <td>-</td>
                    <td>
                        <small class="text-muted">${item.updated_at || ''}</small>
                    </td>
                    <td>
                        <div class="dropdown">
                            <button class="btn btn-link p-0 text-muted" type="button" data-bs-toggle="dropdown" aria-expanded="false" onclick="event.stopPropagation();">
                                <i class="ri-more-2-fill"></i>
                            </button>
                            <ul class="dropdown-menu dropdown-menu-end shadow-sm">
                                ${window.permissions && window.permissions.canViewFile ? `
                                <li>
                                    <a class="dropdown-item view-file-btn debug-view-file-link" href="#" data-file-url="${fileUrl}" data-file-name="${item.name}">
                                        <i class="ri-eye-line me-2 text-primary"></i>View File
                                    </a>
                                </li>` : ''}
                                <li>
                                    <a class="dropdown-item" href="#" onclick="viewFileInfo('${item.name}'); event.stopPropagation();">
                                        <i class="ri-information-line me-2 text-info"></i>
                                        File Info
                                    </a>
                                </li>
                                ${window.permissions && window.permissions.canShareFolder ? `
                                <li>
                                    <a class="dropdown-item" href="#" onclick="openShareFileModal('${item.id}', '${item.name.replace(/'/g, "\\'")}'); event.stopPropagation();">
                                        <i class="ri-share-line me-2 text-warning"></i>
                                        Share File
                                    </a>
                                </li>` : ''}
                                <li><hr class="dropdown-divider"></li>
                                <li>
                                    <button type="button" class="dropdown-item text-danger"
                                            onclick="if(confirm('Are you sure you want to delete this file?')) { deleteFile(${item.id}, '${item.name.replace(/'/g, "\\'")}'); } event.stopPropagation();">
                                        <i class="ri-delete-bin-line me-2"></i>
                                        Delete File
                                    </button>
                                </li>
                            </ul>
                        </div>
                    </td>
                </tr>
            `;
        }
    });
    tableBody.innerHTML = tableHTML;
}
// Add event delegation for view-file-btn to open document viewer modal (like my_folder.blade.php)
document.addEventListener('DOMContentLoaded', function() {
    document.body.addEventListener('click', function(e) {
        if (e.target && (e.target.classList.contains('view-file-btn') || (e.target.closest && e.target.closest('.view-file-btn')))) {
            var btn = e.target.classList.contains('view-file-btn') ? e.target : e.target.closest('.view-file-btn');
            var fileUrl = btn.getAttribute('data-file-url');
            var fileName = btn.getAttribute('data-file-name');
            if (typeof openDocumentViewer === 'function') {
                openDocumentViewer(fileUrl, fileName);
            } else {
                alert('Document viewer not available.');
            }
        }
    });
});

// Folder expand/collapse functions
function toggleSubfolders(folderId) {
    const subfoldersContainer = document.getElementById(`subfolders-${folderId}`);
    const arrow = document.getElementById(`arrow-${folderId}`);
    
    if (!subfoldersContainer || !arrow) return;
    
    const expandButton = arrow.parentElement;
    
    if (subfoldersContainer.style.display === 'none' || subfoldersContainer.style.display === '') {
        subfoldersContainer.style.display = 'block';
        arrow.style.transform = 'rotate(90deg)';
        expandButton.classList.add('expanded');
    } else {
        subfoldersContainer.style.display = 'none';
        arrow.style.transform = 'rotate(0deg)';
        expandButton.classList.remove('expanded');
    }
}

function expandAllFolders() {
    document.querySelectorAll('.subfolders-container').forEach(container => {
        const folderId = container.id.replace('subfolders-', '');
        const arrow = document.getElementById(`arrow-${folderId}`);
        if (arrow && container.style.display === 'none') {
            toggleSubfolders(folderId);
        }
    });
}

function collapseAllFolders() {
    document.querySelectorAll('.subfolders-container').forEach(container => {
        const folderId = container.id.replace('subfolders-', '');
        const arrow = document.getElementById(`arrow-${folderId}`);
        if (arrow && container.style.display !== 'none') {
            toggleSubfolders(folderId);
        }
    });
}

// Share modal functions
function openShareModal(folderId, folderName) {
    const shareModal = document.getElementById('shareFolderModal');
    const shareFolderIdInput = document.getElementById('share_folder_id');

    activeShareFolderId = String(folderId);

    if (shareModal) {
        shareModal.dataset.folderId = activeShareFolderId;
    }

    if (shareFolderIdInput) {
        shareFolderIdInput.value = activeShareFolderId;
    }

    document.getElementById('shareFolderName').textContent = folderName;
    
    // Properly destroy existing selectpickers to prevent duplicates
    try {
        if ($('#shareUsersSelect').hasClass('selectpicker')) {
            $('#shareUsersSelect').selectpicker('destroy');
        }
        if ($('#shareRolesSelect').hasClass('selectpicker')) {
            $('#shareRolesSelect').selectpicker('destroy');
        }
    } catch (e) {
        console.log('Error destroying selectpickers:', e);
    }
    
    // Clear selections first
    $('#shareUsersSelect option').prop('selected', false);
    $('#shareRolesSelect option').prop('selected', false);
    document.getElementById('shareUsersSelect').selectedIndex = -1;
    document.getElementById('shareRolesSelect').selectedIndex = -1;
    
    // Initialize selectpickers fresh
    $('#shareUsersSelect').selectpicker({
        actionsBox: true,
        selectAllText: 'Select All',
        deselectAllText: 'Deselect All',
        noneSelectedText: 'Select Users'
    });
    
    $('#shareRolesSelect').selectpicker({
        actionsBox: true,
        selectAllText: 'Select All',
        deselectAllText: 'Deselect All',
        noneSelectedText: 'Select Roles'
    });
    
    // Clear the table and show loading
    clearShareTable();
    
    // Load existing permissions
    setTimeout(() => {
        loadSavedPermissions(folderId);
    }, 300);
    
    $('#shareFolderModal').modal('show');
}

function clearShareTable() {
    let tableBody = document.getElementById('shareWithTable').querySelector('tbody');
    tableBody.innerHTML = `
        <tr>
            <td colspan="4" class="text-center text-muted py-3">
                <div class="spinner-border spinner-border-sm me-2" role="status"></div>
                Loading shared permissions...
            </td>
        </tr>
    `;
}

function loadSavedPermissions(folderId) {
    // Don't load if a table update is in progress
    if (tableUpdateInProgress) {
        console.log('Skipping loadSavedPermissions - table update in progress');
        return;
    }
    
    const tableBody = document.getElementById('shareWithTable').querySelector('tbody');
    
    // Show loading
    tableBody.innerHTML = `
        <tr>
            <td colspan="4" class="text-center text-muted py-3">
                <div class="spinner-border spinner-border-sm me-2" role="status"></div>
                Loading shared permissions...
            </td>
        </tr>
    `;
    
    // Get the base URL from window object
    const baseUrl = window.baseUrl || '';
    const url = `${baseUrl}/folders/${folderId}/shared-access`;
    
    fetch(url, {
        headers: {
            'Accept': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('Shared permissions data:', data); // Debug log
        console.log('Users data:', data.users); // Debug individual arrays
        console.log('Roles data:', data.roles); // Debug individual arrays
        displaySavedPermissions(data);
    })
    .catch(error => {
        console.error('Error loading permissions:', error);
        
        // Show error in table
        tableBody.innerHTML = `
            <tr>
                <td colspan="4" class="text-center text-muted py-3">
                    <i class="ri-error-warning-line me-1 text-danger"></i>
                    Error loading permissions. 
                    <button type="button" class="btn btn-link btn-sm p-0 ms-1" onclick="loadSavedPermissions(${folderId})">
                        Try again
                    </button>
                </td>
            </tr>
        `;
    });
}

function displaySavedPermissions(data) {
    let tableBody = document.getElementById('shareWithTable').querySelector('tbody');
    let hasData = false;
    let tableHTML = '';

    // Function to get permission level badge
    function getPermissionBadge(level) {
        // Debug log to see what we're receiving
        console.log('getPermissionBadge called with:', level, 'type:', typeof level);
        
        // Handle null, undefined, or empty values
        if (!level || level === null || level === undefined || level === '') {
            console.warn('Empty permission level received');
            return '<span class="badge bg-secondary">No Permission Set</span>';
        }
        
        // Handle both underscore and non-underscore formats
        const normalizedLevel = String(level).toLowerCase().trim();
        
        switch(normalizedLevel) {
            case 'read':
            case 'readonly':
                return '<span class="badge bg-info"><i class="ri-eye-line me-1"></i>Read</span>';
            case 'read_write':
            case 'readwrite':
                return '<span class="badge bg-warning"><i class="ri-edit-line me-1"></i>Read & Write</span>';
            case 'read_write_share':
            case 'readwriteshare':
            case 'full':
                return '<span class="badge bg-success"><i class="ri-share-forward-line me-1"></i>Full Access</span>';
            default:
                console.warn('Unknown permission level:', level, 'normalized:', normalizedLevel);
                return '<span class="badge bg-danger">Unknown: ' + String(level) + '</span>';
        }
    }

    // Add inheritance info header
    if (data.inheritance_info) {
        tableHTML += `
            <tr class="table-info">
                <td colspan="5" class="text-center py-2">
                    <small class="text-info">
                        <i class="ri-information-line me-1"></i>
                        ${data.inheritance_info}
                    </small>
                </td>
            </tr>
        `;
    }

    // Add existing users
    if (data.users && data.users.length > 0) {
        data.users.forEach(user => {
            hasData = true;
            tableHTML += `
                <tr>
                    <td><span class="badge bg-primary"><i class="ri-user-line me-1"></i>User</span></td>
                    <td>${user.first_name} ${user.last_name}</td>
                    <td><small class="text-muted">${user.email}<br><em>+ All subfolders</em></small></td>
                    <td>
                        <button type="button" class="btn btn-danger btn-sm" 
                                onclick="removeSavedPermission('user', ${user.id})"
                                title="Remove Access from Folder & Subfolders">
                            <i class="ri-delete-bin-line"></i>
                        </button>
                    </td>
                </tr>
            `;
        });
    }

    // Add existing roles
    if (data.roles && data.roles.length > 0) {
        data.roles.forEach(role => {
            hasData = true;
            tableHTML += `
                <tr>
                    <td><span class="badge bg-success"><i class="ri-shield-user-line me-1"></i>Role</span></td>
                    <td>${role.name}</td>
                    <td><small class="text-muted">All users with this role<br><em>+ All subfolders</em></small></td>
                    <td>
                        <button type="button" class="btn btn-danger btn-sm" 
                                onclick="removeSavedPermission('role', ${role.id})"
                                title="Remove Access from Folder & Subfolders">
                            <i class="ri-delete-bin-line"></i>
                        </button>
                    </td>
                </tr>
            `;
        });
    }

    if (hasData || data.inheritance_info) {
        tableBody.innerHTML = tableHTML;
    } else {
        displayEmptyTable();
    }
}

function displayEmptyTable() {
    let tableBody = document.getElementById('shareWithTable').querySelector('tbody');
    tableBody.innerHTML = `
        <tr>
            <td colspan="5" class="text-center text-muted py-3">
                <i class="ri-information-line me-1"></i>
                This folder is not shared with anyone yet
            </td>
        </tr>
    `;
}

function removeSavedPermission(type, id) {
    const folderId = document.getElementById('share_folder_id').value;
    
    if (!confirm(`Are you sure you want to remove this ${type}'s access?`)) {
        return;
    }
    
    // Get the base URL from window object
    const baseUrl = window.baseUrl || '';
    const endpoint = type === 'user' 
        ? `${baseUrl}/folders/${folderId}/remove-user-access` 
        : `${baseUrl}/folders/${folderId}/remove-role-access`;
    
    const payload = type === 'user' 
        ? { user_id: id } 
        : { role_id: id };
    
    fetch(endpoint, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        },
        body: JSON.stringify(payload)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast(`${type.charAt(0).toUpperCase() + type.slice(1)} access removed successfully`, 'error'); // Use red for removal
            loadSavedPermissions(folderId); // Reload the table
        } else {
            showToast('Error removing access: ' + (data.message || 'Unknown error'), 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('Error removing access', 'error');
    });
}

function clearAllSelections() {
    if (confirm('Are you sure you want to clear all selections?')) {
        try {
            if ($('#shareUsersSelect').hasClass('selectpicker')) {
                $('#shareUsersSelect').selectpicker('deselectAll');
            }
            if ($('#shareRolesSelect').hasClass('selectpicker')) {
                $('#shareRolesSelect').selectpicker('deselectAll');
            }
            
            // Also clear manually as backup
            $('#shareUsersSelect option').prop('selected', false);
            $('#shareRolesSelect option').prop('selected', false);
            document.getElementById('shareUsersSelect').selectedIndex = -1;
            document.getElementById('shareRolesSelect').selectedIndex = -1;
        } catch (e) {
            console.log('Error clearing selections:', e);
        }
    }
}

// ========================
// SEARCH AND FILTER FUNCTIONALITY
// ========================

// Global variables for search and filter
let allFolders = [];
let filteredFolders = [];
let currentView = 'grid';

// Initialize search functionality
document.addEventListener('DOMContentLoaded', function() {
    // Store original folders data
    initializeFoldersData();
    
    // Add event listeners for real-time search
    const searchInput = document.getElementById('folderSearchInput');
    if (searchInput) {
        searchInput.addEventListener('input', debounce(searchFolders, 300));
    }
});

// Initialize folders data from the page
function initializeFoldersData() {
    allFolders = [];
    const folderElements = document.querySelectorAll('.folder-grid-item');
    
    folderElements.forEach(element => {
        const folderName = element.querySelector('.folder-name')?.textContent?.trim() || '';
        const folderInfo = element.querySelector('.folder-info')?.textContent?.trim() || '';
        const folderId = element.dataset.folderId || '';
        const folderDate = element.dataset.folderDate || ''; // This should match data-folder-date
        
        // Parse date - make sure we have a valid date
        let dateObj;
        if (folderDate) {
            dateObj = new Date(folderDate);
            // Check if date is valid
            if (isNaN(dateObj.getTime())) {
                dateObj = new Date(); // fallback to current date
            }
        } else {
            dateObj = new Date(); // fallback to current date
        }
        
        console.log('Folder:', folderName, 'Date:', folderDate, 'Parsed:', dateObj); // Debug log
        
        allFolders.push({
            id: folderId,
            name: folderName,
            info: folderInfo,
            date: dateObj,
            element: element.parentElement, // Include the parent column div
            visible: true
        });
    });
    
    filteredFolders = [...allFolders];
}

// Search folders function
function searchFolders() {
    const searchInput = document.getElementById('folderSearchInput');
    if (!searchInput) return;

    const searchTerm = searchInput.value.toLowerCase().trim();
    const clearBtn = document.getElementById('clearSearchBtn');
    
    // Show/hide clear button
    if (clearBtn) {
        if (searchTerm) {
            clearBtn.classList.remove('initially-hidden');
        } else {
            clearBtn.classList.add('initially-hidden');
        }
    }

    if (isFolderTableActive()) {
        applyCurrentViewFilters();
        return;
    }
    
    // Filter folders based on search term
    if (searchTerm === '') {
        // Show all folders
        filteredFolders = [...allFolders];
    } else {
        // Filter folders that match search term
        filteredFolders = allFolders.filter(folder => 
            folder.name.toLowerCase().includes(searchTerm) ||
            folder.info.toLowerCase().includes(searchTerm)
        );
    }
    
    // Apply current sort order
    applySortOrder();
    
    // Update display
    displayFilteredFolders();
}

// Clear search function
function clearSearch() {
    const searchInput = document.getElementById('folderSearchInput');
    if (searchInput) {
        searchInput.value = '';
    }

    const clearBtn = document.getElementById('clearSearchBtn');
    if (clearBtn) {
        clearBtn.classList.add('initially-hidden');
    }

    if (isFolderTableActive()) {
        applyCurrentViewFilters();
        return;
    }

    filteredFolders = [...allFolders];
    applySortOrder();
    displayFilteredFolders();
    if (typeof updateFolderCount === 'function') {
        updateFolderCount();
    }
}

// Apply filters (sorting)
function applyFilters() {
    if (isFolderTableActive()) {
        applyCurrentViewFilters();
        return;
    }

    applySortOrder();
    displayFilteredFolders();
}

function isFolderTableActive() {
    const tableView = document.getElementById('tableView');
    return !!tableView && !tableView.classList.contains('d-none');
}

function parseFolderItemDate(item) {
    const parsed = Date.parse(item && item.updated_at ? item.updated_at : '');
    return Number.isNaN(parsed) ? 0 : parsed;
}

function applyCurrentViewFilters() {
    const tableBody = document.getElementById('folderTableBody');
    if (!tableBody) return;

    const searchInput = document.getElementById('folderSearchInput');
    const sortFilter = document.getElementById('folderSortFilter');
    const searchTerm = searchInput ? searchInput.value.toLowerCase().trim() : '';
    const sortValue = sortFilter ? sortFilter.value : 'name-asc';

    let tableItems = [...currentFolderContents];

    if (searchTerm) {
        tableItems = tableItems.filter(item => {
            const name = (item.name || '').toLowerCase();
            const type = (item.type || '').toLowerCase();
            const updatedAt = (item.updated_at || '').toLowerCase();
            const itemCount = String(item.items_count || '');

            return name.includes(searchTerm)
                || type.includes(searchTerm)
                || updatedAt.includes(searchTerm)
                || itemCount.includes(searchTerm);
        });
    }

    tableItems.sort((firstItem, secondItem) => {
        const firstName = (firstItem.name || '').toLowerCase();
        const secondName = (secondItem.name || '').toLowerCase();

        switch (sortValue) {
            case 'name-desc':
                return secondName.localeCompare(firstName);
            case 'date-newest':
                return parseFolderItemDate(secondItem) - parseFolderItemDate(firstItem);
            case 'date-oldest':
                return parseFolderItemDate(firstItem) - parseFolderItemDate(secondItem);
            case 'name-asc':
            default:
                return firstName.localeCompare(secondName);
        }
    });

    if (tableItems.length === 0 && currentFolderContents.length > 0 && searchTerm) {
        tableBody.innerHTML = `
            <tr>
                <td colspan="5" class="text-center text-muted py-4">
                    <i class="ri-search-line font-size-24 mb-2 d-block"></i>
                    No matching folders or files found
                </td>
            </tr>
        `;
        return;
    }

    displayFolderContents(tableItems, currentFolderInfo || { id: currentFolderId });
}

// Apply sort order to filtered folders
function applySortOrder() {
    const sortValue = document.getElementById('folderSortFilter').value;
    console.log('Applying sort order:', sortValue); // Debug log
    
    filteredFolders.sort((a, b) => {
        switch (sortValue) {
            case 'name-asc':
                return a.name.localeCompare(b.name);
            case 'name-desc':
                return b.name.localeCompare(a.name);
            case 'date-newest':
                console.log('Sorting newest first:', a.name, a.date, 'vs', b.name, b.date); // Debug log
                return b.date.getTime() - a.date.getTime(); // Use getTime() for more reliable comparison
            case 'date-oldest':
                console.log('Sorting oldest first:', a.name, a.date, 'vs', b.name, b.date); // Debug log
                return a.date.getTime() - b.date.getTime(); // Use getTime() for more reliable comparison
            default:
                return a.name.localeCompare(b.name);
        }
    });
    
    console.log('Sorted folders:', filteredFolders.map(f => ({ name: f.name, date: f.date }))); // Debug log
}

// Display filtered folders
function displayFilteredFolders() {
    const gridContainer = document.querySelector('.folder-grid-container .row');
    
    if (!gridContainer) {
        console.error('Grid container not found');
        return;
    }
    
    // Hide all folders first
    allFolders.forEach(folder => {
        folder.element.style.display = 'none';
        folder.visible = false;
    });
    
    // Show filtered folders in the correct order
    filteredFolders.forEach((folder, index) => {
        folder.element.style.display = 'block';
        folder.element.style.order = index; // Use CSS order property for proper ordering
        folder.visible = true;
    });
    
    console.log('Displayed folders in order:', filteredFolders.map(f => f.name)); // Debug log
    
    // Show "no results" message if no folders found
    showNoResultsMessage(filteredFolders.length === 0);
}

// Show or hide "no results" message
function showNoResultsMessage(show) {
    let noResultsElement = document.getElementById('noResultsMessage');
    
    if (show) {
        if (!noResultsElement) {
            const gridContainer = document.querySelector('.folder-grid-container .row');
            if (gridContainer) {
                noResultsElement = document.createElement('div');
                noResultsElement.id = 'noResultsMessage';
                noResultsElement.className = 'col-12 text-center py-5';
                noResultsElement.innerHTML = `
                    <div class="text-muted">
                        <i class="ri-search-line font-size-48 mb-3 d-block"></i>
                        <h5>No folders found</h5>
                        <p>Try adjusting your search criteria or filters</p>
                        <button type="button" class="btn btn-outline-primary btn-sm" onclick="clearSearch()">
                            <i class="ri-refresh-line me-1"></i> Clear Search
                        </button>
                    </div>
                `;
                gridContainer.appendChild(noResultsElement);
            }
        } else {
            noResultsElement.style.display = 'block';
        }
    } else {
        if (noResultsElement) {
            noResultsElement.style.display = 'none';
        }
    }
}

// Debounce function for search input
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// Re-initialize after dynamic content updates
function reinitializeSearch() {
    initializeFoldersData();
    clearSearch();
}

// Add permissions function for the Add button
function addPermissions() {
    console.log('=== addPermissions function called ===');

    const shareModal = document.getElementById('shareFolderModal');
    const shareFolderIdInput = document.getElementById('share_folder_id');
    const folderId = activeShareFolderId || shareModal?.dataset.folderId || shareFolderIdInput?.value || '';

    if (shareFolderIdInput) {
        shareFolderIdInput.value = folderId;
    }

    console.log('Folder ID:', folderId);
    
    // Get selected values using vanilla JavaScript
    const userSelect = document.getElementById('shareUsersSelect');
    const roleSelect = document.getElementById('shareRolesSelect');
    
    console.log('Elements found:', {
        userSelect: !!userSelect,
        roleSelect: !!roleSelect
    });
    
    if (!userSelect || !roleSelect) {
        console.error('Required select elements not found');
        showToast('Error: Cannot find user/role select elements', 'error');
        return;
    }

    if (!folderId) {
        console.error('Missing folder ID for share action');
        showToast('Error sharing folder: The folder location was not assigned. Please reopen Share Folder and try again.', 'error');
        return;
    }
    
    const selectedUsers = Array.from(userSelect.selectedOptions).map(option => option.value);
    const selectedRoles = Array.from(roleSelect.selectedOptions).map(option => option.value);
    
    console.log('Raw selections:', {
        userOptions: userSelect.selectedOptions.length,
        roleOptions: roleSelect.selectedOptions.length
    });
    
    console.log('Form data:', { folderId, selectedUsers, selectedRoles });
    
    // Validate selections
    if (selectedUsers.length === 0 && selectedRoles.length === 0) {
        showToast('Please select at least one user or role', 'warning');
        return;
    }
    
    console.log('Validation passed, sending request...');
    
    // Show loading state
    const addBtn = document.getElementById('addPermissionsBtn');
    const originalText = addBtn.innerHTML;
    addBtn.innerHTML = '<i class="ri-loader-4-line spinner me-1"></i>Adding...';
    addBtn.disabled = true;
    
    // Prepare form data
    const formData = new FormData();
    formData.append('folder_id', folderId);
    
    // Add selected users
    selectedUsers.forEach(userId => {
        formData.append('users[]', userId);
    });
    
    // Add selected roles
    selectedRoles.forEach(roleId => {
        formData.append('roles[]', roleId);
    });
    
    // Send request to share endpoint
    const shareUrl = `${window.baseUrl}/folders/share`;
    console.log('Sending request to:', shareUrl);
    
    fetch(shareUrl, {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
            'Accept': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: formData
    })
    .then(response => {
        console.log('Response status:', response.status);
        console.log('Response headers:', response.headers);
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        // Check if response is JSON
        const contentType = response.headers.get('content-type');
        if (!contentType || !contentType.includes('application/json')) {
            throw new Error('Response is not JSON');
        }
        
        return response.json();
    })
    .then(data => {
        console.log('Response received:', data);
        if (data.success) {
            console.log('Success response, updating table...');
            // Show success message
            showToast(data.message || 'Permissions added successfully!', 'success');
            
            // Clear the table update flag to allow reload
            tableUpdateInProgress = false;
            
            // Instead of manually adding to table, reload the saved permissions
            // This ensures the table shows exactly what's in the database
            const folderId = document.getElementById('share_folder_id').value;
            if (folderId) {
                setTimeout(() => {
                    loadSavedPermissions(folderId);
                }, 100); // Small delay to ensure response is fully processed
            }
            
            // Clear selections properly
            userSelect.selectedIndex = -1;
            roleSelect.selectedIndex = -1;
            
            // Clear selectpicker selections if they exist
            try {
                if ($('#shareUsersSelect').hasClass('selectpicker')) {
                    $('#shareUsersSelect').selectpicker('deselectAll');
                    $('#shareUsersSelect').selectpicker('refresh');
                }
                if ($('#shareRolesSelect').hasClass('selectpicker')) {
                    $('#shareRolesSelect').selectpicker('deselectAll');
                    $('#shareRolesSelect').selectpicker('refresh');
                }
            } catch (e) {
                console.log('Error clearing selectpicker selections:', e);
            }
            
            // Also clear manually as backup
            $('#shareUsersSelect option').prop('selected', false);
            $('#shareRolesSelect option').prop('selected', false);
        } else {
            console.log('Error response:', data.message);
            showToast(data.message || 'Error adding permissions', 'error');
        }
    })
    .catch(error => {
        console.error('Error adding permissions:', error);
        
        // If it's a JSON parsing error, let's try to get the raw response
        if (error.message.includes('JSON') || error.message.includes('Unexpected token')) {
            // Re-fetch to get the raw response for debugging
            fetch('/folders/share', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                },
                body: formData
            })
            .then(response => response.text())
            .then(html => {
                console.error('Raw HTML response:', html);
                showToast('Server returned an error page. Check console for details.', 'error');
            });
        } else {
            showToast('Network error adding permissions: ' + error.message, 'error');
        }
    })
    .finally(() => {
        // Restore button state
        addBtn.innerHTML = originalText;
        addBtn.disabled = false;
    });
}

// Make sure the function is available globally
window.addPermissions = addPermissions;

// Function to add new permissions directly to the table
function addNewPermissionsToTable(selectedUsers, selectedRoles) {
    console.log('addNewPermissionsToTable called with:', { selectedUsers, selectedRoles });
    
    // Set flag to prevent loadSavedPermissions from interfering
    tableUpdateInProgress = true;
    
    const tableBody = document.getElementById('shareWithTable')?.querySelector('tbody');
    if (!tableBody) {
        console.error('Table body not found');
        tableUpdateInProgress = false;
        return;
    }
    
    // Check if table is empty and remove empty message
    const emptyRow = tableBody.querySelector('tr td[colspan="4"]') || tableBody.querySelector('tr td[colspan="5"]');
    if (emptyRow) {
        console.log('Removing empty row');
        tableBody.innerHTML = '';
    }
    
    // Add selected users to table
    selectedUsers.forEach(userId => {
        console.log('Processing user:', userId);
        const userSelect = document.getElementById('shareUsersSelect');
        const userOption = userSelect?.querySelector(`option[value="${userId}"]`);
        if (userOption) {
            const userText = userOption.textContent.split(' - ');
            const userName = userText[0];
            const userEmail = userText[1] || 'No email';
            
            console.log('Adding user:', userName, userEmail);
            
            const newRow = document.createElement('tr');
            newRow.innerHTML = `
                <td><span class="badge bg-primary"><i class="ri-user-line me-1"></i>User</span></td>
                <td>${userName}</td>
                <td><small class="text-muted">${userEmail}<br><em>+ All subfolders</em></small></td>
                <td>
                    <button type="button" class="btn btn-danger btn-sm" 
                            onclick="removeSavedPermission('user', ${userId})"
                            title="Remove Access from Folder & Subfolders">
                        <i class="ri-delete-bin-line"></i>
                    </button>
                </td>
            `;
            tableBody.appendChild(newRow);
            console.log('User row added successfully');
        } else {
            console.error('User option not found for ID:', userId);
        }
    });
    
    // Add selected roles to table
    selectedRoles.forEach(roleId => {
        console.log('Processing role:', roleId);
        const roleSelect = document.getElementById('shareRolesSelect');
        const roleOption = roleSelect?.querySelector(`option[value="${roleId}"]`);
        if (roleOption) {
            const roleName = roleOption.textContent;
            
            console.log('Adding role:', roleName);
            
            const newRow = document.createElement('tr');
            newRow.innerHTML = `
                <td><span class="badge bg-success"><i class="ri-shield-user-line me-1"></i>Role</span></td>
                <td>${roleName}</td>
                <td><small class="text-muted">All users with this role<br><em>+ All subfolders</em></small></td>
                <td>
                    <button type="button" class="btn btn-danger btn-sm" 
                            onclick="removeSavedPermission('role', ${roleId})"
                            title="Remove Access from Folder & Subfolders">
                        <i class="ri-delete-bin-line"></i>
                    </button>
                </td>
            `;
            tableBody.appendChild(newRow);
            console.log('Role row added successfully');
        } else {
            console.error('Role option not found for ID:', roleId);
        }
    });
    
    console.log('addNewPermissionsToTable completed');
    
    // Clear the flag after a short delay to allow for any pending operations
    setTimeout(() => {
        tableUpdateInProgress = false;
    }, 1000);
}

// Debug: Confirm main function is defined
console.log('addPermissions function defined:', typeof window.addPermissions);

// Toast notification function (if not already defined)
function showToast(message, type = 'info') {
    // Create toast element if it doesn't exist
    let toastContainer = document.getElementById('toast-container');
    if (!toastContainer) {
        toastContainer = document.createElement('div');
        toastContainer.id = 'toast-container';
        toastContainer.className = 'position-fixed top-0 end-0 p-3';
        toastContainer.style.zIndex = '9999';
        document.body.appendChild(toastContainer);
    }
    
    // Map toast types to Bootstrap classes and icons
    const toastConfig = {
        'success': { bgClass: 'fm-toast-success', icon: 'ri-check-circle-line' },
        'error': { bgClass: 'fm-toast-error', icon: 'ri-error-warning-line' },
        'warning': { bgClass: 'fm-toast-warning', icon: 'ri-alert-line' },
        'info': { bgClass: 'fm-toast-info', icon: 'ri-information-line' }
    };
    
    const config = toastConfig[type] || toastConfig['info'];
    
    // Create toast
    const toastId = 'toast-' + Date.now();
    const toastHTML = `
        <div id="${toastId}" class="toast fm-toast align-items-center text-white ${config.bgClass} border-0" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="d-flex align-items-start">
                <div class="toast-body">
                    <i class="${config.icon} me-2"></i>
                    ${message}
                </div>
                <button type="button" class="btn-close btn-close-white fm-toast-close-btn" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
        </div>
    `;
    
    toastContainer.insertAdjacentHTML('beforeend', toastHTML);
    
    // Initialize and show toast
    const toastElement = document.getElementById(toastId);
    const bsToast = new bootstrap.Toast(toastElement, {
        autohide: true,
        delay: type === 'error' ? 5000 : 3000  // Show errors longer
    });
    bsToast.show();
    
    // Remove toast element after it's hidden
    toastElement.addEventListener('hidden.bs.toast', function () {
        toastElement.remove();
    });
}

// Delete folder function
function deleteFolder(folderId, folderName, folderType = 'normal') {
    // Validate inputs
    if (!folderId || !folderName) {
        showToast('Invalid folder information', 'error');
        return;
    }

    // Show confirmation dialog
    if (!confirm(`Are you sure you want to delete "${folderName}" and all its contents?`)) {
        return;
    }

    // Determine correct URL
    let url = `${window.baseUrl}/folders/${folderId}`;
    if (folderType === 'my') {
        url = `${window.baseUrl}/my-folders/${folderId}`;
    }

    // Make AJAX request to delete folder
    fetch(url, {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': window.csrfToken || document.querySelector('meta[name="csrf-token"]')?.getAttribute('content'),
            'Accept': 'application/json'
        }
    })
    .then(async response => {
        let data = null;
        try {
            data = await response.json();
        } catch (e) {
            data = null;
        }
        if (response.ok && data && data.success) {
            showToast(data.message || 'Folder deleted successfully!', 'success');
            // Refresh current folder contents instead of reloading page
            if (currentFolderId) {
                loadFolderContents(currentFolderId);
            } else {
                // If at root, reload to show updated grid
                setTimeout(() => {
                    window.location.reload();
                }, 1500);
            }
        } else {
            // Show backend error message if present, otherwise generic
            let msg = (data && data.message) ? data.message : null;
            if (!msg && (response.status === 403 || response.status === 401)) {
                msg = 'No permission to delete this folder.';
            } else if (!msg && response.status >= 500) {
                msg = 'Server error occurred while deleting folder.';
            } else if (!msg) {
                msg = 'Unable to delete folder. Please try again.';
            }
            showToast(msg, 'error');
        }
    })
    .catch(error => {
        console.error('Error deleting folder:', error);
        showToast('Error deleting folder: ' + error.message, 'error');
    });
}

// Delete file function
function deleteFile(fileId, fileName) {
    // Validate inputs
    if (!fileId || !fileName) {
        showToast('Invalid file information', 'error');
        return;
    }

    // Make AJAX request to delete file
    const url = `${window.baseUrl}/files/${fileId}`;
    
    fetch(url, {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': window.csrfToken || document.querySelector('meta[name="csrf-token"]')?.getAttribute('content'),
            'Accept': 'application/json'
        }
    })
    .then(async response => {
        let data = null;
        try {
            data = await response.json();
        } catch (e) {
            data = null;
        }
        if (response.ok && data && data.success) {
            showToast(data.message || 'File deleted successfully!', 'success');
            // Refresh current folder contents instead of reloading page
            if (currentFolderId) {
                loadFolderContents(currentFolderId);
            }
        } else {
            // Show backend error message if present, otherwise generic
            let msg = (data && data.message) ? data.message : null;
            if (!msg && (response.status === 403 || response.status === 401)) {
                msg = 'No permission to delete this file.';
            } else if (!msg && response.status >= 500) {
                msg = 'Server error occurred while deleting file.';
            } else if (!msg) {
                msg = 'Unable to delete file. Please try again.';
            }
            showToast(msg, 'error');
        }
    })
    .catch(error => {
        console.error('Error deleting file:', error);
        showToast('Error deleting file: ' + error.message, 'error');
    });
}

