document.addEventListener('DOMContentLoaded', function() {
    let currentDocumentId = null;
    let documentChanged = false;
    
    function initWorkspace() {
        loadPersonalDocuments();
        loadProjects();
        setupEventListeners();
    }
    
    function loadPersonalDocuments() {
        fetch('workspaces.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'action=get_documents'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success && data.documents) {
                renderPersonalDocuments(data.documents);
            }
        })
        .catch(error => console.error('Error loading documents:', error));
    }
    
    function renderPersonalDocuments(documents) {
        const container = document.getElementById('personal-documents-list');
        
        if (documents.length === 0) {
            container.innerHTML = '<div class="text-center text-gray-500 p-4">No documents</div>';
            return;
        }
        
        let html = '';
        documents.forEach(doc => {
            html += `
                <div class="document-item p-2 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg cursor-pointer flex items-center justify-between transition-colors"
                     data-id="${doc.id}" data-type="personal">
                    <div class="flex items-center space-x-2">
                        <i class="fas fa-file-alt text-blue-500"></i>
                        <span class="truncate max-w-[180px]">${doc.title || 'Untitled'}</span>
                    </div>
                    <div class="text-xs text-gray-500">
                        ${formatDate(doc.updated_at)}
                    </div>
                </div>
            `;
        });
        
        container.innerHTML = html;
        
        document.querySelectorAll('.document-item[data-type="personal"]').forEach(item => {
            item.addEventListener('click', function() {
                const docId = this.getAttribute('data-id');
                loadDocument(docId);
            });
        });
    }
    
    function loadProjects() {
        fetch('workspaces.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'action=get_projects'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success && data.projects) {
                renderProjects(data.projects);
                updateProjectSelect(data.projects);
            }
        })
        .catch(error => console.error('Error loading projects:', error));
    }
    
    function renderProjects(projects) {
        const container = document.getElementById('projects-list');
        
        if (projects.length === 0) {
            container.innerHTML = '<div class="text-center text-gray-500 p-4">No projects</div>';
            return;
        }
        
        let html = '';
        projects.forEach(project => {
            html += `
                <div class="project-container mb-3">
                    <div class="project-header p-2 bg-gray-200 dark:bg-gray-700 rounded-lg flex items-center justify-between mb-1">
                        <div class="flex items-center space-x-2">
                            <i class="fas fa-folder text-purple-500"></i>
                            <span class="font-medium">${project.name}</span>
                        </div>
                        <span class="text-xs text-gray-500">${project.logs ? project.logs.length : 0} logs</span>
                    </div>
                    <div class="project-logs pl-4 space-y-1">
            `;
            
            if (project.logs && project.logs.length > 0) {
                project.logs.forEach(log => {
                    html += `
                        <div class="log-item p-2 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg cursor-pointer flex items-center justify-between transition-colors"
                             data-id="${log.id}" data-type="log" data-project="${project.id}">
                            <div class="flex items-center space-x-2">
                                <i class="fas fa-file-alt text-purple-400"></i>
                                <span class="truncate max-w-[160px]">${log.title || 'Untitled'}</span>
                            </div>
                            <div class="text-xs text-gray-500">
                                ${formatDate(log.updated_at)}
                            </div>
                        </div>
                    `;
                });
            } else {
                html += '<div class="text-xs text-gray-500 p-2">No logs in this project</div>';
            }
            
            html += `
                    </div>
                </div>
            `;
        });
        
        container.innerHTML = html;
        
        document.querySelectorAll('.log-item').forEach(item => {
            item.addEventListener('click', function() {
                const docId = this.getAttribute('data-id');
                loadDocument(docId);
            });
        });
    }
    
    function updateProjectSelect(projects) {
        const select = document.getElementById('project-select');
        
        select.innerHTML = '<option value="">-- Select a project --</option>';
        
        projects.forEach(project => {
            const option = document.createElement('option');
            option.value = project.id;
            option.textContent = project.name;
            select.appendChild(option);
        });
    }
    
    function loadDocument(docId) {
        if (documentChanged) {
            if (!confirm("You have unsaved changes. Continue without saving?")) {
                return;
            }
        }
        
        fetch('workspaces.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `action=get_document&document_id=${docId}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success && data.document) {
                displayDocument(data.document);
            }
        })
        .catch(error => console.error('Error loading document:', error));
    }
    
    function displayDocument(document) {
        currentDocumentId = document.id;
        documentChanged = false;
        
        document.getElementById('document-title').value = document.title || 'Untitled';
        
        document.getElementById('document-editor').innerHTML = document.content || '';
        
        if (document.project_id) {
            document.getElementById('document-type').textContent = 'Project log';
            document.getElementById('document-icon-container').innerHTML = '<i class="fas fa-file-alt text-purple-500 text-xl"></i>';
            document.getElementById('convert-to-project-btn').classList.add('hidden');
        } else {
            document.getElementById('document-type').textContent = 'Personal document';
            document.getElementById('document-icon-container').innerHTML = '<i class="fas fa-file-alt text-blue-500 text-xl"></i>';
            document.getElementById('convert-to-project-btn').classList.remove('hidden');
        }
        
        document.getElementById('document-date').textContent = `Last modified: ${formatDate(document.updated_at)}`;
    }
    
    function formatDate(dateString) {
        if (!dateString) return '';
        
        const date = new Date(dateString);
        return date.toLocaleDateString('en-UK', { day: '2-digit', month: '2-digit', year: 'numeric' });
    }
    
    function setupEventListeners() {
        document.getElementById('new-document-btn').addEventListener('click', createNewDocument);
        
        document.getElementById('new-project-btn').addEventListener('click', () => {
            document.getElementById('project-modal').classList.remove('hidden');
        });
        
        document.querySelectorAll('.close-project-modal').forEach(button => {
            button.addEventListener('click', () => {
                document.getElementById('project-modal').classList.add('hidden');
            });
        });
        
        document.getElementById('project-form').addEventListener('submit', function(e) {
            e.preventDefault();
            createNewProject();
        });
        
        document.getElementById('document-title').addEventListener('input', function() {
            documentChanged = true;
        });
        
        document.getElementById('document-editor').addEventListener('input', function() {
            documentChanged = true;
        });
        
        document.getElementById('save-document-btn').addEventListener('click', saveDocument);
        
        document.querySelectorAll('[data-format]').forEach(button => {
            button.addEventListener('click', function() {
                const format = this.getAttribute('data-format');
                formatText(format);
            });
        });
        
        document.getElementById('convert-to-project-btn').addEventListener('click', () => {
            if (currentDocumentId) {
                document.getElementById('document-to-associate').value = currentDocumentId;
                document.getElementById('associate-project-modal').classList.remove('hidden');
            }
        });
        
        document.querySelectorAll('.close-associate-modal').forEach(button => {
            button.addEventListener('click', () => {
                document.getElementById('associate-project-modal').classList.add('hidden');
            });
        });
        
        document.getElementById('associate-project-form').addEventListener('submit', function(e) {
            e.preventDefault();
            associateToProject();
        });
        
        document.querySelector('#document-actions button').addEventListener('click', function() {
            document.getElementById('document-actions-dropdown').classList.toggle('hidden');
        });
        
        document.getElementById('search-workspace').addEventListener('input', function() {
            searchWorkspace(this.value.toLowerCase());
        });
    }
    
    function createNewDocument() {
        if (documentChanged && currentDocumentId) {
            if (!confirm("You have unsaved changes. Continue without saving?")) {
                return;
            }
        }
        
        currentDocumentId = null;
        documentChanged = false;
        
        document.getElementById('document-title').value = 'Untitled';
        document.getElementById('document-editor').innerHTML = '';
        document.getElementById('document-type').textContent = 'Personal document';
        document.getElementById('document-date').textContent = 'Last modified: (Not saved yet)';
        document.getElementById('document-icon-container').innerHTML = '<i class="fas fa-file-alt text-blue-500 text-xl"></i>';
        document.getElementById('convert-to-project-btn').classList.remove('hidden');
    }
    
    function saveDocument() {
        const title = document.getElementById('document-title').value || 'Untitled';
        const content = document.getElementById('document-editor').innerHTML;
        
        const formData = new FormData();
        formData.append('action', 'save_document');
        formData.append('title', title);
        formData.append('content', content);
        
        if (currentDocumentId) {
            formData.append('document_id', currentDocumentId);
        }
        
        fetch('workspaces.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                documentChanged = false;
                
                if (!currentDocumentId) {
                    currentDocumentId = data.document_id;
                }
                
                showNotification('Document saved successfully', 'success');
                
                loadPersonalDocuments();
                
                document.getElementById('document-date').textContent = `Last modified: ${formatDate(new Date())}`;
            } else {
                showNotification('Error saving document', 'error');
            }
        })
        .catch(error => {
            console.error('Error saving document:', error);
            showNotification('Error saving document', 'error');
        });
    }
    
    function createNewProject() {
        const name = document.getElementById('project-name').value;
        const description = document.getElementById('project-description').value;
        
        if (!name) {
            showNotification('Project name is required', 'error');
            return;
        }
        
        const formData = new FormData();
        formData.append('action', 'create_project');
        formData.append('name', name);
        formData.append('description', description);
        
        fetch('workspaces.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('project-name').value = '';
                document.getElementById('project-description').value = '';
                
                document.getElementById('project-modal').classList.add('hidden');
                
                showNotification('Project created successfully', 'success');
                
                loadProjects();
            } else {
                showNotification('Error creating project', 'error');
            }
        })
        .catch(error => {
            console.error('Error creating project:', error);
            showNotification('Error creating project', 'error');
        });
    }
    
    function associateToProject() {
        const documentId = document.getElementById('document-to-associate').value;
        const projectId = document.getElementById('project-select').value;
        
        if (!documentId || !projectId) {
            showNotification('Please select a project', 'error');
            return;
        }
        
        const formData = new FormData();
        formData.append('action', 'associate_to_project');
        formData.append('document_id', documentId);
        formData.append('project_id', projectId);
        
        fetch('workspaces.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('associate-project-modal').classList.add('hidden');
                
                showNotification('Document associated to project', 'success');
                
                loadPersonalDocuments();
                loadProjects();
                
                loadDocument(documentId);
            } else {
                showNotification('Error associating document to project', 'error');
            }
        })
        .catch(error => {
            console.error('Error associating document to project:', error);
            showNotification('Error associating document to project', 'error');
        });
    }
    
    function formatText(format) {
        const editor = document.getElementById('document-editor');
        const selection = window.getSelection();
        const range = selection.getRangeAt(0);
        
        switch(format) {
            case 'bold':
                document.execCommand('bold', false, null);
                break;
            case 'italic':
                document.execCommand('italic', false, null);
                break;
            case 'underline':
                document.execCommand('underline', false, null);
                break;
            case 'h1':
                document.execCommand('formatBlock', false, '<h1>');
                break;
            case 'h2':
                document.execCommand('formatBlock', false, '<h2>');
                break;
            case 'h3':
                document.execCommand('formatBlock', false, '<h3>');
                break;
            case 'link':
                const url = prompt('Enter the URL:');
                if (url) {
                    document.execCommand('createLink', false, url);
                }
                break;
            case 'list-ul':
                document.execCommand('insertUnorderedList', false, null);
                break;
            case 'list-ol':
                document.execCommand('insertOrderedList', false, null);
                break;
        }
        
        documentChanged = true;
    }
    
    function searchWorkspace(query) {
        const personalDocs = document.querySelectorAll('.document-item[data-type="personal"]');
        personalDocs.forEach(doc => {
            const text = doc.querySelector('span').textContent.toLowerCase();
            if (text.includes(query)) {
                doc.classList.remove('hidden');
            } else {
                doc.classList.add('hidden');
            }
        });
        
        const projects = document.querySelectorAll('.project-container');
        projects.forEach(project => {
            const projectName = project.querySelector('.project-header span').textContent.toLowerCase();
            const logs = project.querySelectorAll('.log-item');
            
            if (projectName.includes(query)) {
                project.classList.remove('hidden');
                logs.forEach(log => log.classList.remove('hidden'));
                return;
            }
            
            let hasVisibleLog = false;
            logs.forEach(log => {
                const logName = log.querySelector('span').textContent.toLowerCase();
                if (logName.includes(query)) {
                    log.classList.remove('hidden');
                    hasVisibleLog = true;
                } else {
                    log.classList.add('hidden');
                }
            });
            
            if (hasVisibleLog) {
                project.classList.remove('hidden');
            } else {
                project.classList.add('hidden');
            }
        });
    }
    
    function showNotification(message, type) {
        const notificationClass = type === 'success' ? 'success-notification' : 'error-notification';
        const iconClass = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';
        
        const notification = document.createElement('div');
        notification.className = `${notificationClass} fixed top-4 right-4 bg-${type === 'success' ? 'green' : 'red'}-500 dark:bg-${type === 'success' ? 'green' : 'red'}-600 text-white px-6 py-3 rounded-lg shadow-lg z-50`;
        notification.innerHTML = `
            <div class="flex items-center space-x-2">
                <i class="fas ${iconClass}"></i>
                <span>${message}</span>
            </div>
        `;
        
        document.body.appendChild(notification);
        
        setTimeout(() => {
            notification.classList.add('opacity-0', 'transition-opacity', 'duration-500');
            setTimeout(() => {
                notification.remove();
            }, 500);
        }, 3000);
    }
    
    document.querySelector('.workspace-tab').addEventListener('click', function() {
        setTimeout(initWorkspace, 100);
    });
});