// Table sorting state
let tableSort = {
    column: 'name',
    direction: 'asc'
};

// Open Share File Modal from file actions menu
function openShareFileModal(fileId, fileName) {
    // fileId: file_metadata.id (numeric), fileName: string
    document.getElementById('share_file_id').value = fileId;
    document.getElementById('shareFileName').textContent = fileName;
    // Optionally, load current permissions for this file
    // loadSavedFilePermissions(fileId);
    var modal = new bootstrap.Modal(document.getElementById('shareFileModal'));
    modal.show();
}
// My Folders (Shared Folders) Management JavaScript

// Global variables for my folders navigation
let myCurrentFolderId = null;
let myNavigationHistory = [];

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

    // Grid view
    const gridView = document.getElementById('myGridView');
    if (gridView && !gridView.classList.contains('d-none')) {
        const foldersContainer = document.querySelector('.row.g-3');
        if (!foldersContainer) return;

        let folders = Array.from(foldersContainer.children);

        folders.forEach(folder => {
            const folderName = folder.querySelector('.folder-name');
            if (folderName) {
                const name = folderName.textContent.toLowerCase();
                folder.style.display = searchTerm === '' || name.includes(searchTerm) ? 'block' : 'none';
            }
        });

        folders = folders.filter(f => f.style.display !== 'none');
        folders.sort((a, b) => {
            const aName = a.querySelector('.folder-name')?.textContent || '';
            const bName = b.querySelector('.folder-name')?.textContent || '';
            const aDate = new Date(a.querySelector('small.text-muted')?.textContent || '');
            const bDate = new Date(b.querySelector('small.text-muted')?.textContent || '');

            switch (sortValue) {
                case 'name-asc':
                    return aName.localeCompare(bName);
                case 'name-desc':
                    return bName.localeCompare(aName);
                case 'date-newest':
                    return bDate - aDate;
                case 'date-oldest':
                    return aDate - bDate;
                default:
                    return 0;
            }
        });

        folders.forEach(folder => {
            foldersContainer.appendChild(folder);
        });
    }

    // Table view
    const tableView = document.getElementById('myTableView');
    if (tableView && !tableView.classList.contains('d-none')) {
        const tableBody = document.getElementById('myFolderTableBody');
        if (!tableBody) return;

        let rows = Array.from(tableBody.querySelectorAll('tr'));

        rows.forEach(row => {
            const nameCell = row.querySelector('td .fw-medium');
            if (nameCell) {
                const name = nameCell.textContent.toLowerCase();
                row.style.display = searchTerm === '' || name.includes(searchTerm) ? '' : 'none';
            } else {
                row.style.display = '';
            }
        });

        const sortableRows = rows.filter(row => row.querySelector('td .fw-medium') && row.style.display !== 'none');
        const otherRows = rows.filter(row => !row.querySelector('td .fw-medium') || row.style.display === 'none');

        sortableRows.sort((a, b) => {
            const aName = a.querySelector('td .fw-medium')?.textContent.trim() || '';
            const bName = b.querySelector('td .fw-medium')?.textContent.trim() || '';
            const aDate = new Date(a.querySelector('td small.text-muted')?.textContent || '');
            const bDate = new Date(b.querySelector('td small.text-muted')?.textContent || '');

            switch (sortValue) {
                case 'name-asc':
                    return aName.localeCompare(bName);
                case 'name-desc':
                    return bName.localeCompare(aName);
                case 'date-newest':
                    return bDate - aDate;
                case 'date-oldest':
                    return aDate - bDate;
                default:
                    return 0;
            }
        });

        tableBody.innerHTML = '';
        sortableRows.forEach(row => tableBody.appendChild(row));
        otherRows.forEach(row => tableBody.appendChild(row));
    }
}

document.addEventListener('DOMContentLoaded', function() {
        // Sorting dropdown event
        const sortFilter = document.getElementById('folderSortFilter');
        if (sortFilter) {
            sortFilter.addEventListener('change', function() {
                applyMyFiltersAndSearch();
            });
        }
        // Search input event
        const searchInput = document.getElementById('folderSearchInput');
        if (searchInput) {
            searchInput.addEventListener('input', function() {
                applyMyFiltersAndSearch();
            });
        }

    // Keep inline handlers working on this page too.
    window.searchFolders = applyMyFiltersAndSearch;
    window.applyFilters = applyMyFiltersAndSearch;
    // Initialize tooltips
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
    
    // Test toast function
    console.log('my-folder-management.js loaded successfully');
    
    // Add a test button functionality if it exists
    const testButton = document.getElementById('testToastBtn');
    if (testButton) {
        testButton.addEventListener('click', function() {
            showToast('Test toast notification!', 'success');
        });
    }


});

// Navigation functions for my folders
function openMyFolder(folderId, folderName) {
    myNavigationHistory.push({
        id: myCurrentFolderId,
        view: myCurrentFolderId ? 'table' : 'grid'
    });
    
    myCurrentFolderId = folderId;
    updateMyBreadcrumb(folderName);
    document.getElementById('myBackBtn').classList.remove('initially-hidden');
    
    // Only show buttons if user has permissions
    if (window.permissions && window.permissions.canCreateFolder) {
        document.getElementById('myAddFolderBtn').classList.remove('initially-hidden');
    }
    if (window.permissions && window.permissions.canUploadFile) {
        document.getElementById('myAddFileBtn').classList.remove('initially-hidden');
    }
    
    document.getElementById('myGridView').classList.add('d-none');
    document.getElementById('myTableView').classList.remove('d-none');
    loadMyFolderContents(folderId);
}

function navigateMyBack() {
    if (myNavigationHistory.length > 0) {
        const previousState = myNavigationHistory.pop();
        myCurrentFolderId = previousState.id;
        
        if (previousState.view === 'grid') {
            document.getElementById('myTableView').classList.add('d-none');
            document.getElementById('myGridView').classList.remove('d-none');
            document.getElementById('myBackBtn').classList.add('initially-hidden');
            document.getElementById('myAddFolderBtn').classList.add('initially-hidden');
            document.getElementById('myAddFileBtn').classList.add('initially-hidden');
            updateMyBreadcrumb();
        } else {
            loadMyFolderContents(myCurrentFolderId);
        }
    }
}

function navigateToMyRoot() {
    myNavigationHistory = [];
    myCurrentFolderId = null;
    document.getElementById('myTableView').classList.add('d-none');
    document.getElementById('myGridView').classList.remove('d-none');
    document.getElementById('myBackBtn').classList.add('initially-hidden');
    document.getElementById('myAddFolderBtn').classList.add('initially-hidden');
    document.getElementById('myAddFileBtn').classList.add('initially-hidden');
    updateMyBreadcrumb();
}

function updateMyBreadcrumb(folderName = null) {
    const breadcrumb = document.getElementById('myFolderBreadcrumb');
    
    if (!folderName) {
        breadcrumb.innerHTML = `
            <li class="breadcrumb-item active">
                <i class="ri-folder-shared-line me-1"></i>Shared with Me
            </li>
        `;
    } else {
        breadcrumb.innerHTML = `
            <li class="breadcrumb-item">
                <a href="#" onclick="navigateToMyRoot()" class="text-info">
                    <i class="ri-folder-shared-line me-1"></i>Shared with Me
                </a>
            </li>
            <li class="breadcrumb-item active">${folderName}</li>
        `;
    }
}

function loadMyFolderContents(folderId) {
    console.log('loadMyFolderContents called with folderId:', folderId);
    const tableBody = document.getElementById('myFolderTableBody');
    
    if (!tableBody) {
        console.error('Table body not found');
        return;
    }

    // Show loading state
    tableBody.innerHTML = `
        <tr>
            <td colspan="6" class="text-center text-muted py-4">
                <i class="ri-loader-4-line font-size-24 mb-2 d-block"></i>
                Loading folder contents...
            </td>
        </tr>
    `;

    const url = `${window.baseUrl}/folders/${folderId}/contents`;
    console.log('Fetching from URL:', url);

    // Fetch real folder contents from the API
    fetch(url, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': window.csrfToken,
            'Accept': 'application/json'
        }
    })
    .then(response => {
        console.log('Folder contents response status:', response.status);
        if (!response.ok) {
            if (response.status === 403) {
                throw new Error('PERMISSION_DENIED');
            }
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('Folder contents data:', data);
        if (data.success) {
            console.log('Displaying folder contents:', data.contents.length, 'items');
            displayMyFolderContents(data.contents, data.folder);
            applyMyFiltersAndSearch();
        } else {
            throw new Error(data.message || 'Failed to load folder contents');
        }
    })
    .catch(error => {
        console.error('Error loading folder contents:', error);
        
        let errorMessage = '';
        let errorIcon = 'ri-error-warning-line';
        let showRetryButton = true;
        
        if (error.message === 'PERMISSION_DENIED') {
            errorMessage = `
                <div class="text-center">
                    <i class="ri-lock-line font-size-24 mb-2 d-block text-warning"></i>
                    <h6 class="text-warning mb-2">Access Denied</h6>
                    <small class="text-muted">You don't have permission to view the contents of this folder.</small>
                </div>
            `;
            showRetryButton = false;
        } else {
            errorMessage = `
                <div class="text-center">
                    <i class="ri-error-warning-line font-size-24 mb-2 d-block text-danger"></i>
                    <h6 class="text-danger mb-2">Error Loading Folder</h6>
                    <p class="text-muted mb-0">${error.message}</p>
                </div>
            `;
        }
        
        tableBody.innerHTML = `
            <tr>
                <td colspan="6" class="text-center py-4">
                    ${errorMessage}
                    ${showRetryButton ? `
                    <div class="mt-3">
                        <button class="btn btn-sm btn-outline-primary" onclick="loadMyFolderContents(${folderId})">
                            <i class="ri-refresh-line me-1"></i> Retry
                        </button>
                    </div>` : ''}
                </td>
            </tr>
        `;
    });
}

function displayMyFolderContents(contents, folderInfo) {
    const tableBody = document.getElementById('myFolderTableBody');
    
    // Debug permissions and function calls
    console.log('displayMyFolderContents called with:', contents.length, 'items');
    
    if (contents.length === 0) {
        tableBody.innerHTML = `
            <tr>
                <td colspan="6" 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">
                        <small class="text-muted">No subfolders or files found</small>
                    </div>
                </td>
            </tr>
        `;
        return;
    }
    
    let tableHTML = '';
    contents.forEach(item => {
        const itemIcon = item.type === 'folder' ? 'ri-folder-fill folder-icon-table' : 'ri-file-line';
        const itemBadge = item.type === 'folder' ? 
            '<span class="badge bg-warning-subtle text-warning"><i class="ri-folder-line me-1"></i>Folder</span>' : 
            '<span class="badge bg-info-subtle text-info"><i class="ri-file-line me-1"></i>File</span>';
        
        const itemCount = item.type === 'folder' ? 
            `<span class="text-muted">${item.items_count} ${item.items_count === 1 ? 'item' : 'items'}</span>` : 
            '<span class="text-muted">-</span>';
            
        // ...no metadata display...
            
        const actions = item.type === 'folder' ? 
            `<div class="dropdown">
                <button class="btn btn-sm btn-outline-secondary" 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="openMyFolder(${item.id}, '${item.name.replace(/'/g, "\\'")}'); event.stopPropagation();">
                            <i class="ri-folder-open-line me-2 text-primary"></i>
                            Open Folder
                        </a>
                    </li>
                    ${window.permissions && window.permissions.canEditFolder ? `
                    <li>
                        <a class="dropdown-item" href="#" onclick="showRenameFolderModal(${item.id}, '${item.name.replace(/'/g, "\\'")}'); event.stopPropagation();">
                            <i class="ri-edit-line me-2 text-info"></i>
                            Rename Folder
                        </a>
                    </li>` : ''}
                    <li><hr class="dropdown-divider"></li>
                    ${window.permissions && window.permissions.canShareFolder ? `
                    <li>
                        <a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#shareFolderModal" onclick="openShareModal(${item.id}, '${item.name.replace(/'/g, "\\'")}'); event.stopPropagation();">
                            <i class="ri-share-line me-2 text-warning"></i>
                            Share Folder
                        </a>
                    </li>` : ''}
                    ${window.permissions && window.permissions.canDeleteFolder && item.can_delete ? `
                    <li>
                        <a class="dropdown-item text-danger" href="javascript:void(0);" onclick="deleteFolder(${item.id}, '${item.name.replace(/'/g, "\\'")}'); event.stopPropagation(); return false;">
                            <i class="ri-delete-bin-line me-2"></i>
                            Delete Folder
                        </a>
                    </li>` : ''}
                </ul>
            </div>` :
            `<div class="dropdown">
                <button class="btn btn-sm btn-outline-secondary" 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" href="#" onclick="viewFile('${item.name}'); event.stopPropagation();">
                            <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 Files
                                        </a>
                                    </li> -->` : ''}
            
                    
                    ${window.permissions && window.permissions.canDeleteFile && item.can_delete ? `
                    <li><hr class="dropdown-divider"></li>
                    <li>
                        <a class="dropdown-item text-danger" href="javascript:void(0);" onclick="deleteFile('${item.name}'); event.stopPropagation(); return false;">
                            <i class="ri-delete-bin-line me-2"></i>
                            Delete File
                        </a>
                    </li>` : ''}
                </ul>
            </div>`;
        
        const clickAction = item.type === 'folder' ? 
            `onclick="openMyFolder(${item.id}, '${item.name.replace(/'/g, "\\'")}')" style="cursor: pointer;"` : 
            `style="cursor: default;"`;
            
        tableHTML += `
            <tr ${clickAction}>
                <td>
                    <div class="d-flex align-items-center">
                        <i class="${itemIcon} me-2"></i>
                        <span class="fw-medium">${item.name}</span>
                    </div>
                </td>
                <td>${itemBadge}</td>
                <td>${itemCount}</td>
                <td><small class="text-muted">${item.updated_at}</small></td>
                <td>
                    ${actions}
                </td>
            </tr>
        `;
    });
    
    tableBody.innerHTML = tableHTML;
    
    // Debug final HTML
    console.log('Final table HTML length:', tableHTML.length);
    console.log('Table body children count:', tableBody.children.length);
}

function clearMySearch() {
    const searchInput = document.getElementById('folderSearchInput');
    const clearBtn = document.getElementById('myClearSearchBtn');
    searchInput.value = '';
    clearBtn.classList.add('initially-hidden');
    applyMyFiltersAndSearch();
}



function toggleMySubfolders(folderId) {
    const subfoldersContainer = document.getElementById(`mySubfolders-${folderId}`);
    const expandButton = document.querySelector(`[onclick*="toggleMySubfolders(${folderId})"]`);
    
    if (subfoldersContainer && expandButton) {
        if (subfoldersContainer.classList.contains('initially-hidden')) {
            subfoldersContainer.classList.remove('initially-hidden');
            expandButton.classList.add('expanded');
        } else {
            subfoldersContainer.classList.add('initially-hidden');
            expandButton.classList.remove('expanded');
        }
    }
}

function viewFolderInfo(folderId) {
        // Try /folders/{id}/info first, then fallback to /my-folders/{id}/info if forbidden
        fetch(`${window.baseUrl}/folders/${folderId}/info`)
            .then(response => {
                if (response.status === 403) {
                    // Try my-folders route if forbidden
                    return fetch(`${window.baseUrl}/my-folders/${folderId}/info`);
                }
                return response;
            })
            function loadMyFolderContents(folderId) {
                console.log('loadMyFolderContents called with folderId:', folderId);
                const tableBody = document.getElementById('myFolderTableBody');
                if (!tableBody) {
                    console.error('Table body not found');
                    return;
                }
                // Show loading state
                tableBody.innerHTML = `
                    <tr>
                        <td colspan="6" class="text-center text-muted py-4">
                            <i class="ri-loader-4-line font-size-24 mb-2 d-block"></i>
                            Loading folder contents...
                        </td>
                    </tr>
                `;
                const url = `${window.baseUrl}/folders/${folderId}/contents`;
                console.log('Fetching from URL:', url);
                // Fetch real folder contents from the API
                fetch(url, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': window.csrfToken,
                        'Accept': 'application/json'
                    }
                })
                .then(response => {
                    console.log('Folder contents response status:', response.status);
                    if (!response.ok) {
                        if (response.status === 403) {
                            throw new Error('PERMISSION_DENIED');
                        }
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('Folder contents data:', data);
                    if (data.success) {
                        console.log('Displaying folder contents:', data.contents.length, 'items');
                        displayMyFolderContents(data.contents, data.folder);
                        applyMyFiltersAndSearch();
                    } else {
                        throw new Error(data.message || 'Failed to load folder contents');
                    }
                })
                .catch(error => {
                    console.error('Error loading folder contents:', error);
                    let errorMessage = '';
                    let errorIcon = 'ri-error-warning-line';
                    let showRetryButton = true;
                    if (error.message === 'PERMISSION_DENIED') {
                        errorMessage = `
                            <div class="text-center">
                                <i class="ri-lock-line font-size-24 mb-2 d-block text-warning"></i>
                                <h6 class="text-warning mb-2">Access Denied</h6>
                                <small class="text-muted">You don't have permission to view the contents of this folder.</small>
                            </div>
                        `;
                        showRetryButton = false;
                    } else {
                        errorMessage = `
                            <div class="text-center">
                                <i class="ri-error-warning-line font-size-24 mb-2 d-block text-danger"></i>
                                <h6 class="text-danger mb-2">Error Loading Folder</h6>
                                <p class="text-muted mb-0">${error.message}</p>
                            </div>
                        `;
                    }
                    tableBody.innerHTML = `
                        <tr>
                            <td colspan="6" class="text-center py-4">
                                ${errorMessage}
                                ${showRetryButton ? `
                                <div class="mt-3">
                                    <button class="btn btn-sm btn-outline-primary" onclick="loadMyFolderContents(${folderId})">
                                        <i class="ri-refresh-line me-1"></i> Retry
                                    </button>
                                </div>` : ''}
                            </td>
                        </tr>
                    `;
                });
            }
    
    // Add folder ID
    const folderIdInput = document.createElement('input');
    folderIdInput.type = 'hidden';
    folderIdInput.name = 'folder_id';
    folderIdInput.value = myCurrentFolderId;
    form.appendChild(folderIdInput);
    
    // Add form to body and submit
    document.body.appendChild(form);
    
    try {
        form.submit();
        
        // Show success message after a short delay
        setTimeout(() => {
            showToast(`Download started for: ${fileName}`, 'success');
        }, 1000);
        
    } catch (error) {
        console.error('Download form submission error:', error);
        showToast('Error initiating download', 'error');
    }
    
    // Clean up form after submission
    setTimeout(() => {
        if (document.body.contains(form)) {
            document.body.removeChild(form);
        }
    }, 2000);
}

function viewFile(fileName) {
    if (!myCurrentFolderId) {
        showToast('Unable to view file: folder context not found', 'error');
        return;
    }
    // Validate filename
    if (!fileName || fileName.trim() === '') {
        showToast('Invalid file name', 'error');
        return;
    }
    // Show loading toast
    showToast('Opening file...', 'info');
    // Determine file extension
    var ext = fileName.split('.').pop().toLowerCase();
    let fileUrl = '';
    if (ext === 'pdf') {
        // Always use backend AJAX preview route for PDFs
        fileUrl = window.baseUrl + '/files/ajax-preview-pdf?file_name=' + encodeURIComponent(fileName) + '&folder_id=' + encodeURIComponent(myCurrentFolderId);
    } else if (["doc", "docx", "xls", "xlsx", "ppt", "pptx"].includes(ext)) {
        // Use backend route for Office preview
        fileUrl = window.baseUrl + '/files/stream-office?file_name=' + encodeURIComponent(fileName) + '&folder_id=' + encodeURIComponent(myCurrentFolderId);
    } else {
        // Fallback to backend view route for other types
        fileUrl = window.baseUrl + '/files/view?file_name=' + encodeURIComponent(fileName) + '&folder_id=' + encodeURIComponent(myCurrentFolderId) + '&view_mode=inline';
    }
    // Open the document viewer with the correct backend URL
    if (typeof openDocumentViewer === 'function') {
        openDocumentViewer(fileUrl, fileName);
    } else {
        alert('Document viewer not available.');
    }
}

function viewFileInfo(fileName) {
    // Get file metadata
    fetch(`${window.baseUrl}/files/metadata`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'X-CSRF-TOKEN': window.csrfToken
        },
        body: JSON.stringify({
            file_name: fileName,
            folder_id: myCurrentFolderId
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showFileMetadataModal(fileName, data.metadata);
        } else {
            showFileMetadataModal(fileName, []); // Show modal with no metadata
        }
    })
    .catch(error => {
        console.error('Error loading file metadata:', error);
        showFileMetadataModal(fileName, []); // Show modal with no metadata
    });
}

function deleteFile(fileName) {
    if (!myCurrentFolderId) {
        showToast('Unable to delete file: folder context not found', 'error');
        return;
    }
    
    // Validate filename
    if (!fileName || fileName.trim() === '') {
        showToast('Invalid file name', 'error');
        return;
    }
    
    // Confirm deletion
    if (!confirm(`Are you sure you want to delete "${fileName}"?\n\nThis action cannot be undone.`)) {
        return;
    }
    
    // Show loading toast
    showToast('Deleting file...', 'info');
    
    // Send delete request
    fetch(`${window.baseUrl}/files/delete`, {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'X-CSRF-TOKEN': window.csrfToken
        },
        body: JSON.stringify({
            file_name: fileName,
            folder_id: myCurrentFolderId
        })
    })
    .then(response => response.json())
    .then(data => {
        console.log('Delete file response:', data); // Debug log
        
        if (data.success) {
            // Show user-friendly success message
            const successMessage = data.message || `File "${fileName}" has been deleted successfully!`;
            showToast(successMessage, 'success');
            
            // Refresh the folder contents to remove the deleted file
            setTimeout(() => {
                loadMyFolderContents(myCurrentFolderId);
            }, 1000);
        } else {
            // Show user-friendly error message
            const errorMessage = data.message || 'Unable to delete file. Please try again.';
            showToast(errorMessage, 'error');
        }
    })
    .catch(error => {
        console.error('Error deleting file:', error);
        showToast('Network error deleting file', 'error');
    });
}

function deleteFolder(folderId, folderName) {
    // 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?\n\nThis action cannot be undone.`)) {
        return;
    }

    // Make AJAX request to delete folder
    fetch(`${window.baseUrl}/my-folders/${folderId}`, {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': window.csrfToken || document.querySelector('meta[name="csrf-token"]')?.getAttribute('content'),
            'Accept': 'application/json'
        }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('Delete folder response:', data);
        
        if (data.success) {
            showToast(data.message || 'Folder deleted successfully!', 'success');
            // Refresh the folder contents
            setTimeout(() => {
                if (myCurrentFolderId) {
                    loadMyFolderContents(myCurrentFolderId);
                } else {
                    // If we're at root level, reload the page to show updated folders
                    location.reload();
                }
            }, 1500);
        } else {
            const errorMessage = data.message || 'Unable to delete folder. Please try again.';
            showToast(errorMessage, 'error');
        }
    })
    .catch(error => {
        console.error('Error deleting folder:', error);
        showToast('Network error occurred while deleting folder', 'error');
    });
}

function showFileMetadataModal(fileName, metadata) {
    let metadataHtml = '';
    let commentHtml = '';
    if (metadata && metadata.length > 0) {
        metadataHtml = metadata.map(meta => `
            <div class="row mb-2">
                <div class="col-4"><strong>${meta.meta_tag}:</strong></div>
                <div class="col-8">${meta.meta_value}</div>
            </div>
        `).join('');
        // Show comment if present in the first metadata record (since comment is per file, not per tag)
        if (metadata[0].comment) {
            commentHtml = `<h6><i class='ri-chat-1-line me-1'></i>Comment</h6><p class='mb-3'>${metadata[0].comment}</p>`;
        }
    } else {
        metadataHtml = '<p class="text-muted">No metadata available for this file.</p>';
    }

    const modalHtml = `
        <div class="modal fade" id="fileInfoModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">
                            <i class="ri-file-info-line me-2"></i>File Information
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <h6><i class="ri-file-line me-1"></i>File Name</h6>
                        <p class="mb-3">${fileName}</p>
                        ${commentHtml}
                        <h6><i class="ri-price-tag-3-line me-1"></i>Metadata</h6>
                        ${metadataHtml}
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    `;

    // Remove existing modal if any
    const existingModal = document.getElementById('fileInfoModal');
    if (existingModal) {
        existingModal.remove();
    }

    // Add new modal to body
    document.body.insertAdjacentHTML('beforeend', modalHtml);

    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('fileInfoModal'));
    modal.show();

    // Clean up modal when hidden
    document.getElementById('fileInfoModal').addEventListener('hidden.bs.modal', function() {
        this.remove();
    });
}

// Modal functions for adding folders and files within shared folders
function showAddFolderModal() {
    if (!myCurrentFolderId) {
        showToast('Please navigate to a folder first before creating a subfolder', 'error');
        return;
    }
    
    const modal = new bootstrap.Modal(document.getElementById('addFolderModal'));
    document.getElementById('parentFolderId').value = myCurrentFolderId;
    modal.show();
}

function showAddFileModal() {
    if (!myCurrentFolderId) {
        showToast('Please navigate to a folder first before uploading files', 'error');
        return;
    }
    
    const modal = new bootstrap.Modal(document.getElementById('addFileModal'));
    document.getElementById('uploadFolderId').value = myCurrentFolderId;
    modal.show();
}

// Handle form submissions
document.addEventListener('DOMContentLoaded', function() {
    const addFolderForm = document.getElementById('addFolderForm');
    if (addFolderForm) {
        addFolderForm.addEventListener('submit', function(e) {
            e.preventDefault();
            handleAddFolder();
        });
    }
    
    const addFileForm = document.getElementById('addFileForm');
    if (addFileForm) {
        addFileForm.addEventListener('submit', function(e) {
            e.preventDefault();
            handleAddFile();
        });
    }
    
    // Handle share folder form submission
    const shareFolderForm = document.getElementById('shareFolderForm');
    if (shareFolderForm) {
        shareFolderForm.addEventListener('submit', function(e) {
            e.preventDefault();
            handleShareFolder();
        });
    }

    // Handle share file form submission
    const shareFileForm = document.getElementById('shareFileForm');
    if (shareFileForm) {
        shareFileForm.addEventListener('submit', function(e) {
            e.preventDefault();
            handleShareFile();
        });
    }
    
    // Handle rename folder form submission
    const renameFolderForm = document.getElementById('renameFolderForm');
    if (renameFolderForm) {
        renameFolderForm.addEventListener('submit', function(e) {
            e.preventDefault();
            console.log('Rename form submitted');
            handleRenameFolder();
        });
    }
    // Handle share file logic
    function handleShareFile() {
        const form = document.getElementById('shareFileForm');
        const formData = new FormData(form);
        const fileId = formData.get('file_id') || document.getElementById('share_file_id').value;
        if (!fileId) {
            showToast('File ID missing', 'error');
            return;
        }

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

        fetch(`${window.baseUrl}/files/share`, {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': window.csrfToken,
                'Accept': 'application/json'
            },
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Close modal
                const modal = bootstrap.Modal.getInstance(document.getElementById('shareFileModal'));
                if (modal) modal.hide();
                form.reset();
                showToast(data.message || 'File shared successfully!', 'success');
            } else {
                showToast(data.message || 'Error sharing file', 'error');
            }
        })
        .catch(error => {
            console.error('Error sharing file:', error);
            showToast('Network error sharing file. Please try again.', 'error');
        })
        .finally(() => {
            if (submitBtn) {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            }
        });
    }
    
    // Add cleanup for share folder modal
    const shareModalEl = document.getElementById('shareFolderModal');
    if (shareModalEl) {
        shareModalEl.addEventListener('hidden.bs.modal', function () {
            // Clear the share form
            document.getElementById('shareFolderForm').reset();
            
            // Clear selectpicker selections
            if ($('#shareUsersSelect').length) {
                $('#shareUsersSelect').selectpicker('deselectAll');
                $('#shareUsersSelect').selectpicker('refresh');
            }
            if ($('#shareRolesSelect').length) {
                $('#shareRolesSelect').selectpicker('deselectAll');
                $('#shareRolesSelect').selectpicker('refresh');
            }
            
            // Clear the share table
            clearShareTable();
        });
    }
});

function handleAddFolder() {
    const form = document.getElementById('addFolderForm');
    const formData = new FormData(form);
    
    // Debug: Log form data
    console.log('Form data being sent:');
    for (let [key, value] of formData.entries()) {
        console.log(key, value);
    }
    console.log('Current folder ID:', myCurrentFolderId);
    console.log('Base URL:', window.baseUrl);
    console.log('CSRF Token:', window.csrfToken);
    
    // Show loading state
    const submitBtn = form.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    submitBtn.innerHTML = '<i class="ri-loader-4-line me-1"></i>Creating...';
    submitBtn.disabled = true;
    
    fetch(`${window.baseUrl}/my-folders/create`, {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': window.csrfToken,
            'Accept': 'application/json'
        },
        body: formData
    })
    .then(response => {
        console.log('Response status:', response.status);
        console.log('Response headers:', response.headers);
        return response.json();
    })
    .then(data => {
        console.log('Response data:', data);
        if (data.success) {
            // Close modal
            const modal = bootstrap.Modal.getInstance(document.getElementById('addFolderModal'));
            modal.hide();
            
            // Reset form
            form.reset();
            
            // Show success message
            showToast('Subfolder created successfully!', 'success');
            
            // Refresh current folder view
            loadMyFolderContents(myCurrentFolderId);
        } else {
            showToast(data.message || 'Error creating subfolder', 'error');
        }
    })
    .catch(error => {
        console.error('Fetch error:', error);
        console.error('Error creating subfolder:', error);
        showToast('Network error creating subfolder. Please check the console and try again.', 'error');
    })
    .finally(() => {
        // Restore button state
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
    });
}

function handleAddFile() {
    const form = document.getElementById('addFileForm');
    const formData = new FormData(form);
    const fileInput = document.getElementById('fileUpload');
    
    console.log('handleAddFile called');
    console.log('Current folder ID:', myCurrentFolderId);
    console.log('Files selected:', fileInput.files.length);
    
    if (!fileInput.files.length) {
        showToast('Please select at least one file', 'error');
        return;
    }
    
    // Process metadata - handle both dropdown selections and custom inputs
    const metaTagSelects = document.querySelectorAll('select[name="meta_tags[]"]');
    const metaTagCustoms = document.querySelectorAll('input[name="custom_meta_tags[]"]');
    const metaValues = document.querySelectorAll('input[name="meta_values[]"]');
    
    // Clear existing metadata from FormData
    formData.delete('meta_tags[]');
    formData.delete('meta_values[]');
    formData.delete('custom_meta_tags[]');
    
    // Process each metadata row
    for (let i = 0; i < metaTagSelects.length; i++) {
        const selectValue = metaTagSelects[i].value;
        const customValue = metaTagCustoms[i] ? metaTagCustoms[i].value.trim() : '';
        const metaValue = metaValues[i] ? metaValues[i].value.trim() : '';
        
        if (metaValue) { // Only add if there's a value
            let finalTagName = '';
            
            if (selectValue === 'custom' && customValue) {
                finalTagName = customValue;
            } else if (selectValue && selectValue !== 'custom') {
                finalTagName = selectValue;
            }
            
            if (finalTagName) {
                formData.append('meta_tags[]', finalTagName);
                formData.append('meta_values[]', metaValue);
            }
        }
    }
    
    console.log('Processed metadata entries:');
    for (let [key, value] of formData.entries()) {
        console.log(key, value);
    }
    
    // Show loading state and progress
    const submitBtn = form.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    submitBtn.innerHTML = '<i class="ri-loader-4-line me-1"></i>Uploading...';
    submitBtn.disabled = true;
    
    const progressDiv = document.getElementById('uploadProgress');
    const progressBar = progressDiv.querySelector('.progress-bar');
    progressDiv.classList.remove('d-none');
    
    console.log('Sending request to:', `${window.baseUrl}/files/upload`);
    
    fetch(`${window.baseUrl}/files/upload`, {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': window.csrfToken,
            'Accept': 'application/json'
        },
        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}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('Response data:', data);
        if (data.success) {
            // Close modal
            const modal = bootstrap.Modal.getInstance(document.getElementById('addFileModal'));
            modal.hide();
            
            // Reset form and metadata
            form.reset();
            resetMetadataForm();
            progressDiv.classList.add('d-none');
            progressBar.style.width = '0%';
            
            // Show success message with metadata info
            let message = `${data.uploaded_count || 1} file(s) uploaded successfully!`;
            if (data.metadata_count > 0) {
                message += ` ${data.metadata_count} metadata tag(s) applied.`;
            }
            showToast(message, 'success');
            
            // Refresh current folder view
            console.log('Refreshing view after upload. Current folder ID:', myCurrentFolderId);
            console.log('Current view - Grid hidden:', document.getElementById('myGridView').classList.contains('d-none'));
            console.log('Current view - Table hidden:', document.getElementById('myTableView').classList.contains('d-none'));
            
            // Add a small delay before refreshing to ensure backend processing is complete
            setTimeout(() => {
                if (myCurrentFolderId) {
                    // If we're inside a folder, refresh the table view
                    console.log('Refreshing table view for folder:', myCurrentFolderId);
                    loadMyFolderContents(myCurrentFolderId);
                } else {
                    // If we're at root level, reload the page to show new files
                    console.log('Reloading page to refresh root view');
                    location.reload();
                }
            }, 1000); // 1 second delay
        } else {
            console.error('Upload failed:', data);
            showToast(data.message || 'Error uploading files', 'error');
        }
    })
    .catch(error => {
        console.error('Error uploading files:', error);
        showToast('Error uploading files. Please try again.', 'error');
    })
    .finally(() => {
        // Restore button state
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
        progressDiv.classList.add('d-none');
        progressBar.style.width = '0%';
    });
}

function showToast(message, type = 'info') {
    // Remove any existing toasts first
    const existingToasts = document.querySelectorAll('.custom-toast');
    existingToasts.forEach(toast => toast.remove());
    
    // Create toast with better styling and positioning
    const alertClass = type === 'success' ? 'alert-success' : 
                      type === 'error' ? 'alert-danger' : 'alert-info';
    
    const iconClass = type === 'success' ? 'ri-check-circle-line' : 
                     type === 'error' ? 'ri-error-warning-line' : 'ri-information-line';
    
    const toast = document.createElement('div');
    toast.className = `alert ${alertClass} alert-dismissible fade show position-fixed custom-toast`;
    
    // Ensure success toasts have proper green background
    let customStyle = 'top: 20px; right: 20px; z-index: 10000; min-width: 350px; max-width: 500px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); border: none; border-radius: 8px;';
    if (type === 'success') {
        customStyle += ' background-color: #198754 !important; color: #ffffff !important; border-color: #146c43 !important;';
    }
    
    toast.style.cssText = customStyle;
    toast.innerHTML = `
        <div class="d-flex align-items-center">
            <i class="${iconClass} me-2" style="font-size: 1.2em; color: ${type === 'success' ? '#ffffff' : 'inherit'};"></i>
            <div class="flex-grow-1">${message}</div>
            <button type="button" class="btn-close ${type === 'success' ? 'btn-close-white' : ''}" onclick="this.parentElement.parentElement.remove();" aria-label="Close"></button>
        </div>
    `;
    
    document.body.appendChild(toast);
    
    // Auto remove after 6 seconds for success, 8 seconds for errors
    const timeout = type === 'error' ? 8000 : 6000;
    setTimeout(() => {
        if (toast.parentNode) {
            toast.style.opacity = '0';
            setTimeout(() => {
                if (toast.parentNode) {
                    toast.parentNode.removeChild(toast);
                }
            }, 300);
        }
    }, timeout);
    
    // Also log to console for debugging
    console.log(`Toast (${type}): ${message}`);
}

// Metadata management functions
function addMetadataRow() {
    const container = document.getElementById('metadataContainer');
    const newRow = document.createElement('div');
    newRow.className = 'metadata-row mb-3';
    newRow.innerHTML = `
        <div class="row g-2">
            <div class="col-md-5">
                <label class="form-label">Meta Tag</label>
                <select class="form-select" name="meta_tags[]" onchange="updateMetaValuePlaceholder(this)">
                    <option value="">Select a metadata tag...</option>
                    <optgroup label="Document Categories">
                        <option value="Document Type">Document Type</option>
                        <option value="Category">Category</option>
                        <option value="Classification">Classification</option>
                        <option value="Content Type">Content Type</option>
                    </optgroup>
                    <optgroup label="Business Information">
                        <option value="Department">Department</option>
                        <option value="Project">Project</option>
                        <option value="Client">Client</option>
                        <option value="Budget Code">Budget Code</option>
                        <option value="Cost Center">Cost Center</option>
                        <option value="Division">Division</option>
                        <option value="Team">Team</option>
                    </optgroup>
                    <optgroup label="Status & Priority">
                        <option value="Status">Status</option>
                        <option value="Priority">Priority</option>
                        <option value="Approval Status">Approval Status</option>
                        <option value="Review Status">Review Status</option>
                        <option value="Confidentiality">Confidentiality</option>
                    </optgroup>
                    <optgroup label="People & Roles">
                        <option value="Author">Author</option>
                        <option value="Owner">Owner</option>
                        <option value="Reviewer">Reviewer</option>
                        <option value="Approver">Approver</option>
                        <option value="Stakeholder">Stakeholder</option>
                        <option value="Contact Person">Contact Person</option>
                    </optgroup>
                    <optgroup label="Dates & Timeline">
                        <option value="Due Date">Due Date</option>
                        <option value="Review Date">Review Date</option>
                        <option value="Expiry Date">Expiry Date</option>
                        <option value="Start Date">Start Date</option>
                        <option value="Completion Date">Completion Date</option>
                    </optgroup>
                    <optgroup label="Technical">
                        <option value="Version">Version</option>
                        <option value="Format">Format</option>
                        <option value="Language">Language</option>
                        <option value="Keywords">Keywords</option>
                        <option value="Tags">Tags</option>
                        <option value="Source">Source</option>
                    </optgroup>
                    <optgroup label="Custom">
                        <option value="custom">Enter Custom Tag...</option>
                    </optgroup>
                </select>
                <input type="text" class="form-control mt-2" name="custom_meta_tags[]" placeholder="Enter your custom tag" style="display: none;">
            </div>
            <div class="col-md-5">
                <label class="form-label">Meta Value</label>
                <input type="text" class="form-control" name="meta_values[]" placeholder="Enter value...">
            </div>
            <div class="col-md-2 d-flex align-items-end">
                <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeMetadataRow(this)">
                    <i class="ri-delete-bin-line"></i>
                </button>
            </div>
        </div>
    `;
    container.appendChild(newRow);
    
    // Show delete buttons for all rows if there's more than one
    updateMetadataDeleteButtons();
}

function updateMetaValuePlaceholder(selectElement) {
    const row = selectElement.closest('.metadata-row');
    const valueInput = row.querySelector('input[name="meta_values[]"]');
    const customInput = row.querySelector('input[name="custom_meta_tags[]"]');
    const selectedValue = selectElement.value;
    
    // Hide/show custom input
    if (selectedValue === 'custom') {
        customInput.style.display = 'block';
        customInput.required = true;
        valueInput.placeholder = 'Enter value for custom tag...';
    } else {
        customInput.style.display = 'none';
        customInput.required = false;
        customInput.value = '';
    }
    
    // Update placeholder based on selected tag
    const placeholders = {
        'Document Type': 'e.g., Report, Proposal, Contract, Manual',
        'Category': 'e.g., Financial, Legal, Marketing, Technical',
        'Classification': 'e.g., Public, Internal, Confidential, Restricted',
        'Content Type': 'e.g., Text, Image, Video, Spreadsheet',
        'Department': 'e.g., HR, Finance, IT, Marketing, Sales',
        'Project': 'e.g., Project Alpha, Website Redesign, Q4 Campaign',
        'Client': 'e.g., ABC Corp, John Smith, Internal',
        'Budget Code': 'e.g., BUD-2024-001, PROJ-456',
        'Cost Center': 'e.g., CC-1000, Marketing-2024',
        'Division': 'e.g., North America, Europe, Asia Pacific',
        'Team': 'e.g., Development Team, Design Team, QA Team',
        'Status': 'e.g., Draft, In Progress, Completed, Archived',
        'Priority': 'e.g., High, Medium, Low, Critical',
        'Approval Status': 'e.g., Pending, Approved, Rejected, Under Review',
        'Review Status': 'e.g., Not Started, In Review, Reviewed, Approved',
        'Confidentiality': 'e.g., Public, Internal Use Only, Confidential',
        'Author': 'e.g., John Doe, jane.smith@company.com',
        'Owner': 'e.g., Department Head, Project Manager',
        'Reviewer': 'e.g., Legal Team, Quality Assurance',
        'Approver': 'e.g., Director, Manager, C-Level',
        'Stakeholder': 'e.g., Client, End User, Business Owner',
        'Contact Person': 'e.g., John Doe (ext. 1234)',
        'Due Date': 'e.g., 2024-12-31, Q4 2024',
        'Review Date': 'e.g., 2024-06-30, Every 6 months',
        'Expiry Date': 'e.g., 2025-01-01, Never',
        'Start Date': 'e.g., 2024-01-01, Q1 2024',
        'Completion Date': 'e.g., 2024-03-31, TBD',
        'Version': 'e.g., 1.0, v2.3, Final',
        'Format': 'e.g., PDF, DOCX, XLSX, MP4',
        'Language': 'e.g., English, Spanish, French',
        'Keywords': 'e.g., budget, quarterly, analysis',
        'Tags': 'e.g., important, urgent, reference',
        'Source': 'e.g., Internal, External, Third Party'
    };
    
    valueInput.placeholder = placeholders[selectedValue] || 'Enter value...';
}

function removeMetadataRow(button) {
    const row = button.closest('.metadata-row');
    row.remove();
    updateMetadataDeleteButtons();
}

function updateMetadataDeleteButtons() {
    const rows = document.querySelectorAll('.metadata-row');
    rows.forEach((row, index) => {
        const deleteBtn = row.querySelector('.btn-outline-danger');
        if (rows.length > 1) {
            deleteBtn.style.display = 'block';
        } else {
            deleteBtn.style.display = 'none';
        }
    });
}

function resetMetadataForm() {
    const container = document.getElementById('metadataContainer');
    if (!container) return;
    
    // Remove all rows
    container.innerHTML = '';
    
    // Add back the first empty row
    const firstRow = document.createElement('div');
    firstRow.className = 'metadata-row mb-3';
    firstRow.innerHTML = `
        <div class="row g-2">
            <div class="col-md-5">
                <label class="form-label">Meta Tag</label>
                <select class="form-select" name="meta_tags[]" onchange="updateMetaValuePlaceholder(this)">
                    <option value="">Select a metadata tag...</option>
                    <optgroup label="Document Categories">
                        <option value="Document Type">Document Type</option>
                        <option value="Category">Category</option>
                        <option value="Classification">Classification</option>
                        <option value="Content Type">Content Type</option>
                    </optgroup>
                    <optgroup label="Business Information">
                        <option value="Department">Department</option>
                        <option value="Project">Project</option>
                        <option value="Client">Client</option>
                        <option value="Budget Code">Budget Code</option>
                        <option value="Cost Center">Cost Center</option>
                        <option value="Division">Division</option>
                        <option value="Team">Team</option>
                    </optgroup>
                    <optgroup label="Status & Priority">
                        <option value="Status">Status</option>
                        <option value="Priority">Priority</option>
                        <option value="Approval Status">Approval Status</option>
                        <option value="Review Status">Review Status</option>
                        <option value="Confidentiality">Confidentiality</option>
                    </optgroup>
                    <optgroup label="People & Roles">
                        <option value="Author">Author</option>
                        <option value="Owner">Owner</option>
                        <option value="Reviewer">Reviewer</option>
                        <option value="Approver">Approver</option>
                        <option value="Stakeholder">Stakeholder</option>
                        <option value="Contact Person">Contact Person</option>
                    </optgroup>
                    <optgroup label="Dates & Timeline">
                        <option value="Due Date">Due Date</option>
                        <option value="Review Date">Review Date</option>
                        <option value="Expiry Date">Expiry Date</option>
                        <option value="Start Date">Start Date</option>
                        <option value="Completion Date">Completion Date</option>
                    </optgroup>
                    <optgroup label="Technical">
                        <option value="Version">Version</option>
                        <option value="Format">Format</option>
                        <option value="Language">Language</option>
                        <option value="Keywords">Keywords</option>
                        <option value="Tags">Tags</option>
                        <option value="Source">Source</option>
                    </optgroup>
                    <optgroup label="Custom">
                        <option value="custom">Enter Custom Tag...</option>
                    </optgroup>
                </select>
                <input type="text" class="form-control mt-2" name="custom_meta_tags[]" placeholder="Enter your custom tag" style="display: none;">
            </div>
            <div class="col-md-5">
                <label class="form-label">Meta Value</label>
                <input type="text" class="form-control" name="meta_values[]" placeholder="Enter value...">
            </div>
            <div class="col-md-2 d-flex align-items-end">
                <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeMetadataRow(this)" style="display: none;">
                    <i class="ri-delete-bin-line"></i>
                </button>
            </div>
        </div>
    `;
    container.appendChild(firstRow);
}

// ================================
// Share Folder Functions
// ================================

function openShareModal(folderId, folderName) {
    document.getElementById('share_folder_id').value = folderId;
    document.getElementById('shareFolderName').textContent = folderName;
    
    // Clear selections and reinitialize selectpickers
    setTimeout(() => {
        // Remove any previously selected options
        $('#shareUsersSelect option').prop('selected', false);
        $('#shareRolesSelect option').prop('selected', false);
        
        // Reinitialize selectpickers
        $('#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'
        });
        
        // Refresh the selectpickers
        $('#shareUsersSelect').selectpicker('refresh');
        $('#shareRolesSelect').selectpicker('refresh');
    }, 100);
    
    // Clear the table and show loading
    clearShareTable();
    
    // Load existing permissions
    setTimeout(() => {
        loadSavedPermissions(folderId);
    }, 300);
}

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) {
    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);
        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) {
        switch(level) {
            case 'read':
                return '<span class="badge bg-info"><i class="ri-eye-line me-1"></i>Read</span>';
            case 'read_write':
                return '<span class="badge bg-warning"><i class="ri-edit-line me-1"></i>Read & Write</span>';
            case 'read_write_share':
                return '<span class="badge bg-success"><i class="ri-share-forward-line me-1"></i>Full Access</span>';
            default:
                return '<span class="badge bg-secondary">Unknown</span>';
        }
    }

    // Add inheritance info header
    if (data.inheritance_info) {
        tableHTML += `
            <tr class="table-info">
                <td colspan="4" 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="4" 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`, 'success');
            loadSavedPermissions(folderId); // Reload the table
        } else {
            showToast('Error removing access: ' + (data.message || 'Unknown error'), 'error');
        }
    })
    .catch(error => {
        console.error('Error removing permission:', error);
        showToast('Network error removing access', 'error');
    });
}

function handleShareFolder() {
    const form = document.getElementById('shareFolderForm');
    const formData = new FormData(form);
    
    // Show loading state
    const submitBtn = form.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    submitBtn.innerHTML = '<i class="ri-loader-4-line spinner me-1"></i>Sharing...';
    submitBtn.disabled = true;
    
    fetch(form.action, {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Close modal
            const modal = bootstrap.Modal.getInstance(document.getElementById('shareFolderModal'));
            modal.hide();
            
            // Show success message
            showToast(data.message || 'Folder shared successfully!', 'success');
            
            // Refresh current folder view if we're viewing content
            if (myCurrentFolderId) {
                loadMyFolderContents(myCurrentFolderId);
            }
        } else {
            showToast(data.message || 'Error sharing folder', 'error');
        }
    })
    .catch(error => {
        console.error('Error sharing folder:', error);
        showToast('Network error sharing folder', 'error');
    })
    .finally(() => {
        // Restore button state
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
    });
}

// Add permissions functionality for My Folders

// Attach addPermissions function to both addPermissionsBtn and myAddPermissionsBtn for compatibility
document.addEventListener('DOMContentLoaded', function() {
    const addPermissionsBtn = document.getElementById('addPermissionsBtn');
    if (addPermissionsBtn) {
        addPermissionsBtn.addEventListener('click', function() {
            console.log('Add permissions button clicked');
            addMyPermissions();
        });
    }
    const myAddPermissionsBtn = document.getElementById('myAddPermissionsBtn');
    if (myAddPermissionsBtn) {
        myAddPermissionsBtn.addEventListener('click', function() {
            console.log('Add permissions button clicked');
            addMyPermissions();
        });
    }
});

function addMyPermissions() {
    console.log('Starting addMyPermissions function');
    
    // Get selected users
    const selectedUsers = [];
    const userSelect = document.getElementById('shareUsersSelect');
    if (userSelect) {
        const selectedOptions = userSelect.querySelectorAll('option:checked');
        selectedOptions.forEach(option => {
            selectedUsers.push(option.value);
        });
    }
    console.log('Selected users:', selectedUsers);
    
    // Get selected roles
    const selectedRoles = [];
    const roleSelect = document.getElementById('shareRolesSelect');
    if (roleSelect) {
        const selectedOptions = roleSelect.querySelectorAll('option:checked');
        selectedOptions.forEach(option => {
            selectedRoles.push(option.value);
        });
    }
    console.log('Selected roles:', selectedRoles);
    
    // Check if anything is selected
    if (selectedUsers.length === 0 && selectedRoles.length === 0) {
        showToast('Please select at least one user or role to share with.', 'warning');
        return;
    }
    
    // Get folder ID
    const folderId = document.getElementById('share_folder_id').value;
    if (!folderId) {
        showToast('No folder selected for sharing.', 'error');
        return;
    }
    
    console.log('Sending share request for folder:', folderId);
    
    // Prepare form data
    const formData = new FormData();
    formData.append('_token', window.csrfToken || document.querySelector('meta[name="csrf-token"]').getAttribute('content'));
    formData.append('folder_id', folderId);
    
    // Add users
    selectedUsers.forEach(userId => {
        formData.append('users[]', userId);
    });
    
    // Add roles
    selectedRoles.forEach(roleId => {
        formData.append('roles[]', roleId);
    });
    
    // Show loading state
    const addBtn = document.getElementById('myAddPermissionsBtn');
    const originalText = addBtn.innerHTML;
    addBtn.innerHTML = '<i class="ri-loader-4-line spinner me-1"></i>Adding...';
    addBtn.disabled = true;
    
     // Get the base URL from window object
    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 => response.json())
    .then(data => {
        console.log('Share response:', data);
        
        if (data.success) {
            showToast(data.message || 'Permissions added successfully!', 'success');
            
            // Clear selections
            if (userSelect) {
                userSelect.querySelectorAll('option').forEach(option => option.selected = false);
                // Refresh selectpicker if it exists
                if (typeof $(userSelect).selectpicker === 'function') {
                    $(userSelect).selectpicker('refresh');
                }
            }
            if (roleSelect) {
                roleSelect.querySelectorAll('option').forEach(option => option.selected = false);
                // Refresh selectpicker if it exists
                if (typeof $(roleSelect).selectpicker === 'function') {
                    $(roleSelect).selectpicker('refresh');
                }
            }
            
            // Reload the permissions table
            setTimeout(() => {
                loadSavedPermissions(folderId);
            }, 500);
            
        } else {
            showToast(data.message || 'Error adding permissions', 'error');
        }
    })
    .catch(error => {
        console.error('Error adding permissions:', error);
        showToast('Network error adding permissions', 'error');
    })
    .finally(() => {
        // Restore button state
        addBtn.innerHTML = originalText;
        addBtn.disabled = false;
    });
}

// ================================
// Rename Folder Functions
// ================================

function showRenameFolderModal(folderId, currentName) {
    console.log('showRenameFolderModal called with:', { folderId, currentName });
    
    // Set the folder ID and current name
    document.getElementById('rename_folder_id').value = folderId;
    document.getElementById('currentFolderName').textContent = currentName;
    document.getElementById('newFolderName').value = currentName;
    
    console.log('Modal fields set:', {
        folderId: document.getElementById('rename_folder_id').value,
        currentName: document.getElementById('currentFolderName').textContent,
        newNameValue: document.getElementById('newFolderName').value
    });
    
    // Show the modal
    const modal = new bootstrap.Modal(document.getElementById('renameFolderModal'));
    modal.show();
    
    // Focus on the input field and select the text
    setTimeout(() => {
        const input = document.getElementById('newFolderName');
        input.focus();
        input.select();
    }, 300);
}

function handleRenameFolder() {
    console.log('handleRenameFolder called');
    
    const form = document.getElementById('renameFolderForm');
    const formData = new FormData(form);
    const folderId = document.getElementById('rename_folder_id').value;
    const newName = document.getElementById('newFolderName').value.trim();
    const currentName = document.getElementById('currentFolderName').textContent;
    
    console.log('Rename details:', { folderId, newName, currentName });
    
    // Validate input
    if (!newName) {
        showToast('Please enter a folder name', 'error');
        return;
    }
    
    if (newName === currentName) {
        showToast('The new name is the same as the current name', 'warning');
        return;
    }
    
    console.log('Sending rename request to:', `${window.baseUrl}/folders/${folderId}/rename`);
    
    // Show loading state
    const submitBtn = form.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    submitBtn.innerHTML = '<i class="ri-loader-4-line me-1"></i>Renaming...';
    submitBtn.disabled = true;
    
    // Send rename request
    fetch(`${window.baseUrl}/folders/${folderId}/rename`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': window.csrfToken,
            'Accept': 'application/json'
        },
        body: JSON.stringify({
            folder_name: newName
        })
    })
    .then(response => {
        console.log('Rename response status:', response.status);
        if (!response.ok) {
            if (response.status === 403) {
                throw new Error('You do not have permission to rename this folder');
            }
            if (response.status === 422) {
                throw new Error('A folder with this name already exists');
            }
            if (response.status === 404) {
                throw new Error('Folder not found');
            }
            throw new Error('Unable to rename folder. Please try again.');
        }
        return response.json();
    })
    .then(data => {
        console.log('Rename response data:', data);
        if (data.success) {
            // Close modal
            const modal = bootstrap.Modal.getInstance(document.getElementById('renameFolderModal'));
            modal.hide();
            
            // Show success message
            showToast(data.message || 'Folder renamed successfully!', 'success');
            
            // Refresh the current view
            if (myCurrentFolderId) {
                loadMyFolderContents(myCurrentFolderId);
            } else {
                // If we're at root level, reload the page to show renamed folders
                setTimeout(() => {
                    location.reload();
                }, 1000);
            }
        } else {
            // Show user-friendly error message
            const errorMessage = data.message || 'Unable to rename folder. Please try again.';
            showToast(errorMessage, 'error');
        }
    })
    .catch(error => {
        console.error('Error renaming folder:', error);
        showToast('Network error occurred while renaming folder', 'error');
    })
    .finally(() => {
        // Restore button state
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
    });
}

function viewFile(fileName) {
    if (!myCurrentFolderId) {
        showToast('Unable to view file: folder context not found', 'error');
        return;
    }
    if (!fileName || fileName.trim() === '') {
        showToast('Invalid file name', 'error');
        return;
    }
    // Always use backend preview route for file viewing
    var ext = fileName.split('.').pop().toLowerCase();
    if (ext === 'pdf') {
        let fileUrl = window.baseUrl + '/files/ajax-preview-pdf?file_name=' + encodeURIComponent(fileName) + '&folder_id=' + encodeURIComponent(myCurrentFolderId);
        if (typeof openDocumentViewer === 'function') {
            openDocumentViewer(fileUrl, fileName);
        } else {
            alert('Document viewer not available.');
        }
    } else if (["doc", "docx", "xls", "xlsx", "ppt", "pptx"].includes(ext)) {
        // Use POST for /files/view for Office files
        fetch(window.baseUrl + '/files/view', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': window.csrfToken,
                'Accept': 'application/octet-stream'
            },
            body: JSON.stringify({
                file_name: fileName,
                folder_id: myCurrentFolderId
            })
        })
        .then(response => {
            if (!response.ok) throw new Error('File preview failed');
            return response.blob();
        })
        .then(blob => {
            const blobUrl = URL.createObjectURL(blob);
            if (typeof openDocumentViewer === 'function') {
                openDocumentViewer(blobUrl, fileName);
            } else {
                window.open(blobUrl, '_blank');
            }
        })
        .catch(() => {
            showToast('Unable to preview this file.', 'error');
        });
    } else {
        let fileUrl = window.baseUrl + '/files/view?file_name=' + encodeURIComponent(fileName) + '&folder_id=' + encodeURIComponent(myCurrentFolderId) + '&view_mode=inline';
        if (typeof openDocumentViewer === 'function') {
            openDocumentViewer(fileUrl, fileName);
        } else {
            alert('Document viewer not available.');
        }
    }
}