<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>KPI Analysis Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="/static/css/dashboard.css" rel="stylesheet">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">
                <i class="fas fa-chart-line me-2"></i>
                KPI Analysis Dashboard
            </a>
            <div class="navbar-nav ms-auto" id="userSection" style="display: none;">
                <div class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown">
                        <i class="fas fa-user me-1"></i>
                        <span id="usernameDisplay">User</span>
                    </a>
                    <ul class="dropdown-menu">
                        <li><a class="dropdown-item" href="#"><i class="fas fa-cog me-2"></i>Settings</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="#" onclick="dashboard.logout()"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>
                    </ul>
                </div>
            </div>

        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2 sidebar">
                <div class="position-sticky pt-3">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link active" href="#overview" data-bs-toggle="tab">
                                <i class="fas fa-tachometer-alt me-2"></i>
                                Overview
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#files" data-bs-toggle="tab">
                                <i class="fas fa-file-excel me-2"></i>
                                Files
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#analysis" data-bs-toggle="tab">
                                <i class="fas fa-chart-bar me-2"></i>
                                Analysis
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#nextcloud" data-bs-toggle="tab">
                                <i class="fas fa-cloud me-2"></i>
                                Nextcloud
                            </a>
                        </li>

                    </ul>
                </div>
            </div>

            <!-- Main Content -->
            <div class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="tab-content pt-3">
                    
                    <!-- Overview Tab -->
                    <div class="tab-pane fade show active" id="overview">
                        <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom">
                            <h1 class="h2">Dashboard Overview</h1>
                            <div class="btn-toolbar mb-2 mb-md-0">
                                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="refreshData()">
                                    <i class="fas fa-sync-alt me-1"></i>
                                    Refresh
                                </button>
                            </div>
                        </div>

                        <!-- Key Metrics Cards -->
                        <div class="row mb-4">
                            <div class="col-xl-3 col-md-6 mb-4">
                                <div class="card border-left-primary shadow h-100 py-2">
                                    <div class="card-body">
                                        <div class="row no-gutters align-items-center">
                                            <div class="col mr-2">
                                                <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                                    Total Files
                                                </div>
                                                <div class="h5 mb-0 font-weight-bold text-gray-800" id="total-files">0</div>
                                            </div>
                                            <div class="col-auto">
                                                <i class="fas fa-file-excel fa-2x text-gray-300"></i>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-xl-3 col-md-6 mb-4">
                                <div class="card border-left-success shadow h-100 py-2">
                                    <div class="card-body">
                                        <div class="row no-gutters align-items-center">
                                            <div class="col mr-2">
                                                <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                                    Avg Score
                                                </div>
                                                <div class="h5 mb-0 font-weight-bold text-gray-800" id="avg-score">0%</div>
                                            </div>
                                            <div class="col-auto">
                                                <i class="fas fa-chart-line fa-2x text-gray-300"></i>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-xl-3 col-md-6 mb-4">
                                <div class="card border-left-info shadow h-100 py-2">
                                    <div class="card-body">
                                        <div class="row no-gutters align-items-center">
                                            <div class="col mr-2">
                                                <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                                    Achievement Rate
                                                </div>
                                                <div class="h5 mb-0 font-weight-bold text-gray-800" id="achievement-rate">0%</div>
                                            </div>
                                            <div class="col-auto">
                                                <i class="fas fa-trophy fa-2x text-gray-300"></i>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-xl-3 col-md-6 mb-4">
                                <div class="card border-left-warning shadow h-100 py-2">
                                    <div class="card-body">
                                        <div class="row no-gutters align-items-center">
                                            <div class="col mr-2">
                                                <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                                    Reports Generated
                                                </div>
                                                <div class="h5 mb-0 font-weight-bold text-gray-800" id="reports-count">0</div>
                                            </div>
                                            <div class="col-auto">
                                                <i class="fas fa-file-pdf fa-2x text-gray-300"></i>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Charts Row -->
                        <div class="row">
                            <div class="col-xl-8 col-lg-7">
                                <div class="card shadow mb-4">
                                    <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                                        <h6 class="m-0 font-weight-bold text-primary">Performance Overview</h6>
                                    </div>
                                    <div class="card-body">
                                        <div class="chart-area">
                                            <canvas id="performanceChart"></canvas>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-xl-4 col-lg-5">
                                <div class="card shadow mb-4">
                                    <div class="card-header py-3">
                                        <h6 class="m-0 font-weight-bold text-primary">Achievement Status</h6>
                                    </div>
                                    <div class="card-body">
                                        <div class="chart-pie">
                                            <canvas id="achievementChart"></canvas>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Recent Activity -->
                        <div class="row">
                            <div class="col-12">
                                <div class="card shadow mb-4">
                                    <div class="card-header py-3">
                                        <h6 class="m-0 font-weight-bold text-primary">Recent Activity</h6>
                                    </div>
                                    <div class="card-body">
                                        <div class="table-responsive">
                                            <table class="table table-bordered" id="activityTable" width="100%" cellspacing="0">
                                                <thead>
                                                    <tr>
                                                        <th>Date</th>
                                                        <th>Action</th>
                                                        <th>File</th>
                                                        <th>Status</th>
                                                    </tr>
                                                </thead>
                                                <tbody id="activity-tbody">
                                                    <!-- Activity data will be loaded here -->
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Files Tab -->
                    <div class="tab-pane fade" id="files">
                        <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom">
                            <h1 class="h2">File Management</h1>
                            <div class="btn-toolbar mb-2 mb-md-0">
                                <div class="btn-group me-2">
                                    <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#uploadModal">
                                        <i class="fas fa-upload me-1"></i>
                                        Upload File
                                    </button>
                                </div>
                            </div>
                        </div>

                        <div class="card shadow mb-4">
                            <div class="card-header py-3">
                                <h6 class="m-0 font-weight-bold text-primary">Uploaded KPI Files</h6>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-bordered" id="filesTable" width="100%" cellspacing="0">
                                        <thead>
                                            <tr>
                                                <th>Filename</th>
                                                <th>Upload Date</th>
                                                <th>Size</th>
                                                <th>Status</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody id="files-tbody">
                                            <!-- Files data will be loaded here -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Analysis Tab -->
                    <div class="tab-pane fade" id="analysis">
                        <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom">
                            <h1 class="h2">KPI Analysis</h1>
                        </div>

                        <div class="row">
                            <div class="col-12">
                                <div class="card shadow mb-4">
                                    <div class="card-header py-3">
                                        <h6 class="m-0 font-weight-bold text-primary">Analysis Results</h6>
                                    </div>
                                    <div class="card-body">
                                        <div id="analysis-content">
                                            <p class="text-muted">Select a file to view analysis results.</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-12">
                                <div class="card shadow mb-4">
                                    <div class="card-header py-3">
                                        <h6 class="m-0 font-weight-bold text-primary">Interactive Charts</h6>
                                    </div>
                                    <div class="card-body">
                                        <div id="charts-content">
                                            <p class="text-muted">Charts will appear here after analysis.</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Nextcloud Tab -->
                    <div class="tab-pane fade" id="nextcloud">
                        <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom">
                            <h1 class="h2">Nextcloud Integration</h1>
                            <div class="btn-toolbar mb-2 mb-md-0">
                                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="connectNextcloud()">
                                    <i class="fas fa-cloud me-1"></i>
                                    Connect
                                </button>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-12">
                                <div class="card shadow mb-4">
                                    <div class="card-header py-3">
                                        <h6 class="m-0 font-weight-bold text-primary">Nextcloud Files</h6>
                                    </div>
                                    <div class="card-body">
                                        <div id="nextcloud-files">
                                            <p class="text-muted">Connect to Nextcloud to view KPI files.</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>



                </div>
            </div>
        </div>
    </div>

    <!-- Upload Modal -->
    <div class="modal fade" id="uploadModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Upload KPI File</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="uploadForm">
                        <div class="mb-3">
                            <label for="fileInput" class="form-label">Select Excel File</label>
                            <input class="form-control" type="file" id="fileInput" accept=".xlsx,.xls">
                        </div>
                        <div class="progress" style="display: none;" id="uploadProgress">
                            <div class="progress-bar" role="progressbar" style="width: 0%"></div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="uploadFile()">Upload</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="/static/js/dashboard.js"></script>

    <script>
        // Dashboard object to manage functionality
        const dashboard = {
            isAuthenticated: false,
            currentUser: null,
            token: null,
            
            // Initialize dashboard when page loads
            initialize: function() {
                console.log('Initializing dashboard...');
                this.checkAuthentication();
            },
            
            // Check if user is authenticated
            checkAuthentication: function() {
                this.token = localStorage.getItem('kpi_token');
                console.log('Token found:', !!this.token);
                
                if (this.token) {
                    this.validateToken();
                } else {
                    // No token, redirect to login
                    window.location.href = '/login';
                }
            },
            
            // Validate the stored token
            async validateToken() {
                try {
                    const response = await fetch('/api/auth/me', {
                        headers: {
                            'Authorization': `Bearer ${this.token}`
                        }
                    });
                    
                    if (response.ok) {
                        const result = await response.json();
                        this.currentUser = result.user;
                        this.isAuthenticated = true;
                        this.updateUI();
                        this.loadDashboardData();
                        this.initializeCharts([]);
                    } else {
                        // Token invalid, redirect to login
                        localStorage.removeItem('kpi_token');
                        localStorage.removeItem('kpi_user');
                        window.location.href = '/login';
                    }
                } catch (error) {
                    console.error('Token validation error:', error);
                    localStorage.removeItem('kpi_token');
                    localStorage.removeItem('kpi_user');
                    window.location.href = '/login';
                }
            },
            
            // Update UI based on authentication status
            updateUI: function() {
                const userSection = document.getElementById('userSection');
                const usernameDisplay = document.getElementById('usernameDisplay');
                
                if (this.isAuthenticated && this.currentUser) {
                    userSection.style.display = 'block';
                    usernameDisplay.textContent = this.currentUser.username;
                }
            },
            
            // Authenticated fetch
            authFetch: async function(url, options = {}) {
                const headers = {
                    ...options.headers,
                    'Authorization': `Bearer ${this.token}`
                };
                
                const response = await fetch(url, {
                    ...options,
                    headers
                });
                
                if (response.status === 401) {
                    // Token expired, redirect to login
                    this.logout();
                    throw new Error('Authentication required');
                }
                
                return response;
            },
            
            // Logout function
            logout: function() {
                console.log('Logging out...');
                
                // Call logout API if token exists
                if (this.token) {
                    fetch('/api/auth/logout', {
                        method: 'POST',
                        headers: {
                            'Authorization': `Bearer ${this.token}`
                        }
                    }).catch(err => console.log('Logout API error:', err));
                }
                
                // Clear local storage
                this.token = null;
                this.currentUser = null;
                this.isAuthenticated = false;
                localStorage.removeItem('kpi_token');
                localStorage.removeItem('kpi_user');
                
                // Redirect to login
                window.location.href = '/login';
            },
            
            // Load dashboard data
            loadDashboardData: async function() {
                try {
                    // Load dashboard metrics from API
                    const response = await this.authFetch('/api/files/list');
                    const data = await response.json();
                    
                    // Update dashboard metrics with real data
                    const totalFiles = data.files ? data.files.length : 0;
                    document.getElementById('total-files').textContent = totalFiles;
                    
                    // Calculate real metrics if data exists
                    if (totalFiles > 0 && data.files) {
                        // Calculate average score from processed files
                        const processedFiles = data.files.filter(file => file.processed);
                        if (processedFiles.length > 0) {
                            // For now, show 0% until we implement real score calculation
                            document.getElementById('avg-score').textContent = '0%';
                            document.getElementById('achievement-rate').textContent = '0%';
                        } else {
                            document.getElementById('avg-score').textContent = 'No Data';
                            document.getElementById('achievement-rate').textContent = 'No Data';
                        }
                        document.getElementById('reports-count').textContent = '0'; // Will be updated when report generation is implemented
                    } else {
                        // No files - show appropriate empty state
                        document.getElementById('total-files').textContent = '0';
                        document.getElementById('avg-score').textContent = 'No Data';
                        document.getElementById('achievement-rate').textContent = 'No Data';
                        document.getElementById('reports-count').textContent = '0';
                    }
                    
                    // Load files table
                    this.loadFilesTable(data.files || []);
                    
                    // Load activity data
                    this.loadRecentActivity();
                    
                    // Initialize or update charts
                    this.initializeCharts(data.files || []);
                    
                } catch (error) {
                    console.error('Error loading dashboard data:', error);
                    // Show empty state if error
                    document.getElementById('total-files').textContent = '0';
                    document.getElementById('avg-score').textContent = 'Error';
                    document.getElementById('achievement-rate').textContent = 'Error';
                    document.getElementById('reports-count').textContent = '0';
                    this.loadFilesTable([]);
                    this.loadRecentActivity();
                }
            },
        
        // Initialize charts
        initializeCharts: function(files = []) {
            // Performance Chart
            const perfCtx = document.getElementById('performanceChart').getContext('2d');
            
            // Destroy existing chart if any
            if (this.performanceChart) {
                this.performanceChart.destroy();
            }
            
            const hasData = files.length > 0;
            
            // Only show empty state message, no fake data
            this.performanceChart = new Chart(perfCtx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: 'Performance Score',
                        data: [],
                        borderColor: 'rgb(75, 192, 192)',
                        backgroundColor: 'rgba(75, 192, 192, 0.2)',
                        tension: 0.1
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        title: {
                            display: true,
                            text: hasData ? 'Performance Trend Over Time' : 'No Data Available - Upload KPI Files'
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            min: 0,
                            max: 100
                        }
                    }
                }
            });

            // Achievement Chart
            const achieveCtx = document.getElementById('achievementChart').getContext('2d');
            
            // Destroy existing chart if any
            if (this.achievementChart) {
                this.achievementChart.destroy();
            }
            
            // Only show empty state message, no fake data
            this.achievementChart = new Chart(achieveCtx, {
                type: 'doughnut',
                data: {
                    labels: [],
                    datasets: [{
                        data: [],
                        backgroundColor: []
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        title: {
                            display: true,
                            text: hasData ? 'Achievement Status' : 'No Data Available'
                        },
                        legend: {
                            position: 'bottom'
                        }
                    }
                }
            });
        },
        
        // Load recent activity
        loadRecentActivity: function() {
            const tbody = document.getElementById('activity-tbody');
            tbody.innerHTML = '';
            
            // Show "no data" message
            const row = tbody.insertRow();
            row.innerHTML = `
                <td colspan="4" class="text-center text-muted py-4">
                    <i class="fas fa-info-circle me-2"></i>
                    No activity yet. Upload a KPI file to get started.
                </td>
            `;
        },
        
        // Load files table
        loadFilesTable: function(files) {
            const tbody = document.getElementById('files-tbody');
            tbody.innerHTML = '';
            
            if (files.length === 0) {
                const row = tbody.insertRow();
                row.innerHTML = `
                    <td colspan="5" class="text-center text-muted py-4">
                        <i class="fas fa-folder-open me-2"></i>
                        No files uploaded yet. Click "Upload File" to get started.
                    </td>
                `;
                return;
            }
            
            files.forEach(file => {
                const row = tbody.insertRow();
                row.innerHTML = `
                    <td>${file.filename}</td>
                    <td>${file.upload_date}</td>
                    <td>${file.size}</td>
                    <td>
                        ${file.processed 
                            ? '<span class="badge bg-success">Processed</span>' 
                            : '<span class="badge bg-warning">Processing...</span>'}
                    </td>
                    <td>
                        ${file.processed 
                            ? `<button class="btn btn-sm btn-primary" onclick="viewAnalysis(${file.id})">
                                <i class="fas fa-chart-bar me-1"></i>View Analysis
                               </button>
                               <button class="btn btn-sm btn-secondary" onclick="downloadReport(${file.id})">
                                <i class="fas fa-download me-1"></i>Report
                               </button>
                               <button class="btn btn-sm btn-danger" onclick="deleteFile(${file.id})">
                                <i class="fas fa-trash me-1"></i>Delete
                               </button>`
                            : `<span class="text-muted">Processing...</span>
                               <button class="btn btn-sm btn-danger" onclick="deleteFile(${file.id})">
                                <i class="fas fa-trash me-1"></i>Delete
                               </button>`}
                    </td>
                `;
            });
        },
        
        // Refresh data
        refreshData: function() {
            this.loadDashboardData();
        }
    };
    
    // Standalone functions
    async function uploadFile() {
        const fileInput = document.getElementById('fileInput');
        const progressBar = document.querySelector('#uploadProgress .progress-bar');
        const progressContainer = document.getElementById('uploadProgress');

        if (!fileInput.files[0]) {
            alert('Please select a file to upload');
            return;
        }

        const formData = new FormData();
        formData.append('file', fileInput.files[0]);

        progressContainer.style.display = 'block';
        progressBar.style.width = '50%';
        
        try {
            const response = await dashboard.authFetch('/api/files/upload', {
                method: 'POST',
                body: formData
            });

            const result = await response.json();

            if (result.success) {
                progressBar.style.width = '100%';
                alert('File uploaded successfully! Analysis is running in the background.');
                $('#uploadModal').modal('hide');
                fileInput.value = '';
                dashboard.loadDashboardData();
            } else {
                alert('Upload failed: ' + (result.message || 'Unknown error'));
            }
        } catch (error) {
            console.error('Upload error:', error);
            alert('Upload failed: ' + error.message);
        } finally {
            progressContainer.style.display = 'none';
            progressBar.style.width = '0%';
        }
    }
    
    async function viewAnalysis(fileId) {
        try {
            const response = await dashboard.authFetch(`/api/analysis/${fileId}`);
            const result = await response.json();
            
            if (result.success) {
                // Switch to analysis tab
                const analysisTab = document.querySelector('a[href="#analysis"]');
                analysisTab.click();
                
                // Display analysis results
                const analysisContent = document.getElementById('analysis-content');
                analysisContent.innerHTML = `
                    <div class="row">
                        <div class="col-md-6">
                            <h5>Overall Score</h5>
                            <h2 class="text-primary">${result.total_score.toFixed(1)}%</h2>
                        </div>
                        <div class="col-md-6">
                            <h5>Achievement Rate</h5>
                            <h2 class="text-success">${result.achievements.achievement_rate.toFixed(1)}%</h2>
                        </div>
                    </div>
                    <hr>
                    <h5>Perspective Scores</h5>
                    <div class="row">
                        ${Object.entries(result.perspective_scores).map(([key, value]) => `
                            <div class="col-md-3 mb-3">
                                <div class="card">
                                    <div class="card-body text-center">
                                        <h6>${key}</h6>
                                        <h4 class="text-info">${value.toFixed(1)}%</h4>
                                    </div>
                                </div>
                            </div>
                        `).join('')}
                    </div>
                    <hr>
                    <h5>Recommendations</h5>
                    <ul>
                        ${result.recommendations.map(rec => `<li>${rec}</li>`).join('')}
                    </ul>
                `;
            } else {
                alert('Analysis not available yet. Please wait for processing to complete.');
            }
        } catch (error) {
            console.error('Error loading analysis:', error);
            alert('Failed to load analysis results.');
        }
    }
    
    async function downloadReport(fileId) {
        window.location.href = `/api/analysis/${fileId}/report`;
    }

    async function deleteFile(fileId) {
        if (!confirm('Are you sure you want to delete this file? This action cannot be undone.')) {
            return;
        }
        
        try {
            const response = await dashboard.authFetch(`/api/files/delete/${fileId}`, {
                method: 'DELETE'
            });
            
            const result = await response.json();
            
            if (result.success) {
                alert('File deleted successfully');
                dashboard.loadDashboardData();
            } else {
                alert('Failed to delete file: ' + (result.message || 'Unknown error'));
            }
        } catch (error) {
            console.error('Delete error:', error);
            alert('Failed to delete file: ' + error.message);
        }
    }

    function connectNextcloud() {
        window.location.href = '/api/auth/nextcloud';
    }
    
    function refreshData() {
        dashboard.refreshData();
    }

    // Initialize dashboard when page loads
    $(document).ready(function() {
        dashboard.initialize();
    });
    </script>
</body>
</html>