// Dashboard JavaScript for KPI Analysis Application

class KPIDashboard {
    constructor() {
        this.apiBaseUrl = '/api';
        this.currentFile = null;
        this.analysisData = null;
        this.charts = {};
        this.authToken = localStorage.getItem('kpi_token');
        this.currentUser = JSON.parse(localStorage.getItem('kpi_user') || 'null');
        this.init();
    }

    init() {
        this.setupEventListeners();
        this.checkAuthentication();
        this.initializeDataTables();
    }

    checkAuthentication() {
        if (!this.authToken) {
            // Redirect to login page instead of showing modal
            window.location.href = '/login';
        } else {
            this.verifyToken();
        }
    }

    verifyToken() {
        fetch(`${this.apiBaseUrl}/auth/me`, {
            headers: {
                'Authorization': `Bearer ${this.authToken}`
            }
        })
        .then(response => {
            if (response.ok) {
                return response.json();
            } else {
                throw new Error('Invalid token');
            }
        })
        .then(data => {
            if (data.success) {
                this.currentUser = data.user;
                localStorage.setItem('kpi_user', JSON.stringify(this.currentUser));
                this.updateUserInterface();
                this.loadInitialData();
            } else {
                throw new Error('Authentication failed');
            }
        })
        .catch(error => {
            console.error('Token verification failed:', error);
            // Redirect to login page instead of showing modal
            localStorage.removeItem('kpi_token');
            localStorage.removeItem('kpi_user');
            window.location.href = '/login';
        });
    }

    showLoginForm() {
        const content = `
            <div class="container">
                <div class="row justify-content-center">
                    <div class="col-md-6">
                        <div class="card shadow">
                            <div class="card-header text-center">
                                <h4><i class="fas fa-sign-in-alt me-2"></i>Login Required</h4>
                            </div>
                            <div class="card-body">
                                <form id="loginForm">
                                    <div class="mb-3">
                                        <label for="username" class="form-label">Username</label>
                                        <input type="text" class="form-control" id="username" required>
                                    </div>
                                    <div class="mb-3">
                                        <label for="password" class="form-label">Password</label>
                                        <input type="password" class="form-control" id="password" required>
                                    </div>
                                    <button type="submit" class="btn btn-primary w-100">
                                        <i class="fas fa-sign-in-alt me-1"></i>
                                        Login
                                    </button>
                                </form>
                                <div id="loginError" class="alert alert-danger mt-3" style="display: none;"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        document.querySelector('.container-fluid').innerHTML = content;
        
        document.getElementById('loginForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleLogin();
        });
    }

    handleLogin() {
        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;
        
        fetch(`${this.apiBaseUrl}/auth/login`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                username,
                password
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                this.authToken = data.access_token;
                this.currentUser = data.user;
                localStorage.setItem('kpi_token', this.authToken);
                localStorage.setItem('kpi_user', JSON.stringify(this.currentUser));
                location.reload();
            } else {
                throw new Error(data.message || 'Login failed');
            }
        })
        .catch(error => {
            console.error('Login error:', error);
            const errorDiv = document.getElementById('loginError');
            errorDiv.textContent = error.message;
            errorDiv.style.display = 'block';
        });
    }

    logout() {
        localStorage.removeItem('kpi_token');
        localStorage.removeItem('kpi_user');
        this.authToken = null;
        this.currentUser = null;
        window.location.href = '/login';
    }

    updateUserInterface() {
        // Update user info in navbar
        const userNavItem = document.querySelector('.navbar-nav .dropdown-toggle');
        if (userNavItem && this.currentUser) {
            userNavItem.innerHTML = `
                <i class="fas fa-user me-1"></i>
                ${this.currentUser.full_name || this.currentUser.username}
            `;
        }
    }

    getAuthHeaders() {
        return this.authToken
            ? { 'Authorization': `Bearer ${this.authToken}` }
            : {};
    }

    async authFetch(url, options = {}) {
        const fetchOptions = {
            ...options,
            headers: {
                ...this.getAuthHeaders(),
                ...options.headers
            }
        };
        const response = await fetch(url, fetchOptions);
        if (response.status === 401) {
            this.logout();
            throw new Error('Authentication required');
        }
        return response;
    }

    setupEventListeners() {
        // File upload drag and drop
        const uploadArea = document.querySelector('#uploadModal .modal-body');
        if (uploadArea) {
            this.setupDragAndDrop(uploadArea);
        }

        // Tab navigation
        document.querySelectorAll('[data-bs-toggle="tab"]').forEach(tab => {
            tab.addEventListener('shown.bs.tab', (e) => {
                const targetId = e.target.getAttribute('href').substring(1);
                this.onTabChange(targetId);
            });
        });

        // Form submissions
        this.setupFormHandlers();
    }

    setupDragAndDrop(element) {
        element.addEventListener('dragover', (e) => {
            e.preventDefault();
            element.classList.add('dragover');
        });

        element.addEventListener('dragleave', () => {
            element.classList.remove('dragover');
        });

        element.addEventListener('drop', (e) => {
            e.preventDefault();
            element.classList.remove('dragover');
            
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                document.getElementById('fileInput').files = files;
            }
        });
    }

    setupFormHandlers() {
        // Upload form
        const uploadForm = document.getElementById('uploadForm');
        if (uploadForm) {
            uploadForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.uploadFile();
            });
        }
    }

    async loadInitialData() {
        try {
            await this.loadDashboardMetrics();
            await this.loadRecentActivity();
            await this.loadFilesList();
        } catch (error) {
            console.error('Error loading initial data:', error);
            this.showNotification('Error loading dashboard data', 'error');
        }
    }

    async loadDashboardMetrics() {
        try {
            // Load actual file list to get real metrics
            const response = await this.authFetch(`${this.apiBaseUrl}/files/list`);
            const data = await response.json();
            
            const files = data.files || [];
            const totalFiles = files.length;
            
            // Calculate real metrics from files
            let totalScore = 0;
            let scoreCount = 0;
            let processedFiles = 0;
            
            // For now, show 0 or "No Data" when empty
            // In future, we can fetch analysis results for each file
            const avgScore = totalFiles > 0 ? 0 : 0; // Will be calculated from actual analysis
            const achievementRate = totalFiles > 0 ? 0 : 0; // Will be calculated from actual analysis
            const reportsCount = 0; // Will be counted from actual reports
            
            this.updateMetrics({
                totalFiles: totalFiles,
                avgScore: avgScore,
                achievementRate: achievementRate,
                reportsCount: reportsCount
            });
        } catch (error) {
            console.error('Error loading metrics:', error);
            // Show zeros on error
            this.updateMetrics({
                totalFiles: 0,
                avgScore: 0,
                achievementRate: 0,
                reportsCount: 0
            });
        }
    }

    updateMetrics(metrics) {
        const elements = {
            totalFiles: document.getElementById('total-files'),
            avgScore: document.getElementById('avg-score'),
            achievementRate: document.getElementById('achievement-rate'),
            reportsCount: document.getElementById('reports-count')
        };

        if (elements.totalFiles) {
            elements.totalFiles.textContent = metrics.totalFiles;
        }
        
        if (elements.avgScore) {
            elements.avgScore.textContent = metrics.totalFiles === 0 || metrics.avgScore === 0 
                ? 'No Data' 
                : `${metrics.avgScore.toFixed(1)}%`;
        }
        
        if (elements.achievementRate) {
            elements.achievementRate.textContent = metrics.totalFiles === 0 || metrics.achievementRate === 0 
                ? 'No Data' 
                : `${metrics.achievementRate.toFixed(1)}%`;
        }
        
        if (elements.reportsCount) {
            elements.reportsCount.textContent = metrics.reportsCount;
        }
    }

    async loadRecentActivity() {
        try {
            // Try to load real activity from API
            // For now, show empty state if no data
            const activities = [];
            
            this.populateActivityTable(activities);
        } catch (error) {
            console.error('Error loading activity:', error);
            this.populateActivityTable([]);
        }
    }

    populateActivityTable(activities) {
        const tbody = document.getElementById('activity-tbody');
        if (!tbody) return;

        tbody.innerHTML = '';

        if (activities.length === 0) {
            // Show empty state
            const row = document.createElement('tr');
            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>
            `;
            tbody.appendChild(row);
            return;
        }

        activities.forEach(activity => {
            const row = document.createElement('tr');
            row.className = 'fade-in';
            
            const statusClass = this.getStatusClass(activity.status);
            
            row.innerHTML = `
                <td>${activity.date}</td>
                <td>${activity.action}</td>
                <td class="text-truncate" style="max-width: 200px;">${activity.file}</td>
                <td><span class="badge ${statusClass}">${activity.status}</span></td>
            `;
            
            tbody.appendChild(row);
        });
    }

    getStatusClass(status) {
        const statusMap = {
            'Completed': 'bg-success',
            'Success': 'bg-success',
            'Generated': 'bg-info',
            'Synced': 'bg-primary',
            'Processing': 'bg-warning',
            'Failed': 'bg-danger'
        };
        return statusMap[status] || 'bg-secondary';
    }

    async loadFilesList() {
        try {
            const response = await this.authFetch(`${this.apiBaseUrl}/files/list`);
            const data = await response.json();
            this.populateFilesTable(data.files || []);
        } catch (error) {
            console.error('Error loading files:', error);
        }
    }

    populateFilesTable(files) {
        const tbody = document.getElementById('files-tbody');
        if (!tbody) return;

        tbody.innerHTML = '';

        if (files.length === 0) {
            // Show empty state
            const row = document.createElement('tr');
            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>
            `;
            tbody.appendChild(row);
            return;
        }

        files.forEach((file, index) => {
            const row = document.createElement('tr');
            row.className = 'slide-in';
            
            row.innerHTML = `
                <td>
                    <i class="fas fa-file-excel text-success me-2"></i>
                    ${file.filename}
                </td>
                <td>${file.upload_date}</td>
                <td>${file.size}</td>
                <td>
                    <span class="badge ${file.processed ? 'bg-success' : 'bg-warning'}">
                        ${file.processed ? 'Processed' : 'Pending'}
                    </span>
                </td>
                <td>
                    ${file.processed 
                        ? `<div class="btn-group btn-group-sm" role="group">
                            <button class="btn btn-outline-primary" onclick="dashboard.viewAnalysisResults(${file.id})" title="View Analysis Results">
                                <i class="fas fa-chart-bar me-1"></i>
                                View Results
                            </button>
                            <button class="btn btn-outline-success" onclick="dashboard.downloadPDFReport(${file.id})" title="Download PDF Report">
                                <i class="fas fa-file-pdf me-1"></i>
                                PDF
                            </button>
                            <button class="btn btn-outline-danger" onclick="dashboard.deleteFile(${file.id})" title="Delete File">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>`
                        : `<div class="btn-group btn-group-sm" role="group">
                            <button class="btn btn-outline-secondary" disabled title="Processing...">
                                <span class="spinner-border spinner-border-sm me-1"></span>
                                Processing...
                            </button>
                            <button class="btn btn-outline-danger" onclick="dashboard.deleteFile(${file.id})" title="Delete File">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>`
                    }
                </td>
            `;
            
            tbody.appendChild(row);
        });
    }

    initializeDataTables() {
        // Initialize DataTables if needed
        if ($.fn.DataTable) {
            $('.table').DataTable({
                "pageLength": 25,
                "language": {
                    "search": "Search files:",
                    "lengthMenu": "Show _MENU_ files per page"
                }
            });
        }
    }

    async uploadFile() {
        const fileInput = document.getElementById('fileInput');
        const progressBar = document.querySelector('#uploadProgress .progress-bar');
        const progressContainer = document.getElementById('uploadProgress');
        const uploadBtn = document.querySelector('#uploadModal .btn-primary');

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

        // Validate file type
        const file = fileInput.files[0];
        if (!file.name.match(/\.(xlsx|xls)$/i)) {
            this.showNotification('Please select a valid Excel file (.xlsx or .xls)', 'error');
            return;
        }

        // Validate file size (50MB limit)
        if (file.size > 50 * 1024 * 1024) {
            this.showNotification('File size must be less than 50MB', 'error');
            return;
        }

        const formData = new FormData();
        formData.append('file', file);

        // Show progress
        progressContainer.style.display = 'block';
        uploadBtn.disabled = true;
        uploadBtn.innerHTML = '<span class="loading me-1"></span>Uploading...';

        try {
            const response = await this.authFetch(`${this.apiBaseUrl}/files/upload`, {
                method: 'POST',
                body: formData
            });

            const result = await response.json();

            if (result.success) {
                this.showNotification('File uploaded successfully! Analysis is running in the background.', 'success');
                $('#uploadModal').modal('hide');
                this.clearUploadForm();
                await this.loadFilesList();
                await this.loadDashboardMetrics();
                
                // Start polling to check when processing is complete
                if (result.file_id) {
                    this.startProcessingPoll(result.file_id);
                }
            } else {
                throw new Error(result.message || 'Upload failed');
            }
        } catch (error) {
            console.error('Upload error:', error);
            this.showNotification('Upload failed: ' + error.message, 'error');
        } finally {
            progressContainer.style.display = 'none';
            uploadBtn.disabled = false;
            uploadBtn.innerHTML = 'Upload';
        }
    }

    clearUploadForm() {
        document.getElementById('fileInput').value = '';
        document.getElementById('uploadProgress').style.display = 'none';
    }

    async viewAnalysisResults(fileId) {
        try {
            this.showNotification('Loading analysis results...', 'info');
            
            const response = await this.authFetch(`${this.apiBaseUrl}/analysis/${fileId}`);
            const result = await response.json();

            if (result.success) {
                // Switch to analysis tab
                document.querySelector('a[href="#analysis"]').click();
                
                // Display results
                this.displayAnalysisResults(result);
                
                // Load charts
                this.loadAnalysisCharts(fileId);
                
                this.showNotification('Analysis results loaded successfully', 'success');
            } else {
                throw new Error(result.message || 'Failed to load analysis results');
            }
        } catch (error) {
            console.error('Error loading analysis:', error);
            this.showNotification('Failed to load analysis: ' + error.message, 'error');
        }
    }

    async downloadPDFReport(fileId) {
        try {
            this.showNotification('Downloading PDF report...', 'info');
            
            // Open PDF in new tab
            const url = `${this.apiBaseUrl}/analysis/${fileId}/report`;
            const response = await this.authFetch(url);
            
            if (response.ok) {
                // Get the blob
                const blob = await response.blob();
                
                // Create download link
                const downloadUrl = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = downloadUrl;
                a.download = `kpi_report_${fileId}.pdf`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                window.URL.revokeObjectURL(downloadUrl);
                
                this.showNotification('PDF report downloaded successfully', 'success');
            } else {
                throw new Error('Report not found or not yet generated');
            }
        } catch (error) {
            console.error('Download error:', error);
            this.showNotification('Failed to download report: ' + error.message, 'error');
        }
    }

    async analyzeFile(fileId) {
        try {
            this.showNotification('Starting analysis...', 'info');
            
            const response = await this.authFetch(`${this.apiBaseUrl}/analysis/run/${fileId}`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' }
            });

            const result = await response.json();

            if (result.success) {
                this.showNotification('Analysis started! Results will be available shortly.', 'success');
                
                // Switch to analysis tab
                document.querySelector('a[href="#analysis"]').click();
                
                // Poll for results
                this.pollForResults(fileId);
            } else {
                throw new Error(result.message || 'Analysis failed to start');
            }
        } catch (error) {
            console.error('Analysis error:', error);
            this.showNotification('Analysis failed: ' + error.message, 'error');
        }
    }

    async pollForResults(fileId) {
        let attempts = 0;
        const maxAttempts = 20; // 10 minutes max
        
        const checkResults = async () => {
            try {
                const response = await this.authFetch(`${this.apiBaseUrl}/analysis/${fileId}`);
                const result = await response.json();
                
                if (result.total_score !== undefined) {
                    this.displayAnalysisResults(result);
                    this.loadAnalysisCharts(fileId);
                } else if (attempts < maxAttempts) {
                    attempts++;
                    setTimeout(checkResults, 30000); // Check every 30 seconds
                } else {
                    this.showNotification('Analysis timeout. Please try again.', 'error');
                }
            } catch (error) {
                console.error('Error checking results:', error);
                if (attempts < maxAttempts) {
                    attempts++;
                    setTimeout(checkResults, 30000);
                }
            }
        };
        
        setTimeout(checkResults, 5000); // Wait 5 seconds before first check
    }

    displayAnalysisResults(results) {
        const content = document.getElementById('analysis-content');
        if (!content) return;

        content.innerHTML = `
            <div class="row">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h6 class="m-0 font-weight-bold text-primary">Overall Performance</h6>
                        </div>
                        <div class="card-body">
                            <div class="text-center">
                                <h2 class="text-primary">${results.total_score.toFixed(2)}</h2>
                                <p class="text-muted">Total KPI Score (Points)</p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h6 class="m-0 font-weight-bold text-primary">Achievement Status</h6>
                        </div>
                        <div class="card-body">
                            <div class="row text-center">
                                <div class="col-4">
                                    <h5 class="text-success">${results.achievements.achieved}</h5>
                                    <small>Achieved</small>
                                </div>
                                <div class="col-4">
                                    <h5 class="text-danger">${results.achievements.not_achieved}</h5>
                                    <small>Not Achieved</small>
                                </div>
                                <div class="col-4">
                                    <h5 class="text-warning">${results.achievements.achievement_rate.toFixed(1)}%</h5>
                                    <small>Success Rate</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="row mt-4">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h6 class="m-0 font-weight-bold text-primary">Key Insights</h6>
                        </div>
                        <div class="card-body">
                            ${results.recommendations.map((rec, index) => {
                                // Clean up the recommendation text
                                let cleanRec = rec.trim();
                                // Remove leading numbers, bullets, or dashes
                                cleanRec = cleanRec.replace(/^[\d\.\-•\*]+\s*/, '');
                                
                                // Determine icon and color based on content
                                let icon = 'fa-lightbulb';
                                let color = 'warning';
                                
                                if (cleanRec.toLowerCase().includes('priority') || cleanRec.toLowerCase().includes('immediate')) {
                                    icon = 'fa-exclamation-triangle';
                                    color = 'danger';
                                } else if (cleanRec.toLowerCase().includes('improve') || cleanRec.toLowerCase().includes('increase')) {
                                    icon = 'fa-arrow-up';
                                    color = 'success';
                                } else if (cleanRec.toLowerCase().includes('strategic') || cleanRec.toLowerCase().includes('perspective')) {
                                    icon = 'fa-chess';
                                    color = 'info';
                                }
                                
                                return `
                                    <div class="recommendation-item mb-3 p-3 border-start border-${color} border-4 bg-light">
                                        <div class="d-flex align-items-start">
                                            <div class="me-3">
                                                <i class="fas ${icon} fa-lg text-${color}"></i>
                                            </div>
                                            <div class="flex-grow-1">
                                                <h6 class="mb-1 text-${color}">${index + 1}. ${cleanRec.split(':')[0]}</h6>
                                                ${cleanRec.includes(':') ? `<p class="mb-0 text-muted small">${cleanRec.split(':').slice(1).join(':').trim()}</p>` : ''}
                                            </div>
                                        </div>
                                    </div>
                                `;
                            }).join('')}
                        </div>
                    </div>
                </div>
            </div>
        `;

        content.classList.add('fade-in');
    }

    async loadAnalysisCharts(fileId) {
        try {
            const response = await this.authFetch(`${this.apiBaseUrl}/analysis/${fileId}/charts`);
            const result = await response.json();
            
            const chartsContent = document.getElementById('charts-content');
            if (!chartsContent) return;

            chartsContent.innerHTML = '';

            if (result.charts) {
                result.charts.forEach((chart, index) => {
                    const chartContainer = document.createElement('div');
                    chartContainer.className = 'chart-container mb-4';
                    chartContainer.innerHTML = `
                        <h6 class="mb-3">${chart.title}</h6>
                        <div id="chart-${index}" style="height: 400px;"></div>
                    `;
                    
                    chartsContent.appendChild(chartContainer);
                    
                    // Render chart based on type
                    this.renderChart(chart, index);
                });
            }
        } catch (error) {
            console.error('Error loading charts:', error);
        }
    }

    renderChart(chartData, index) {
        const container = document.getElementById(`chart-${index}`);
        if (!container) return;
        
        // Create canvas for Chart.js
        container.innerHTML = `<canvas id="canvas-${index}"></canvas>`;
        const canvas = document.getElementById(`canvas-${index}`);
        const ctx = canvas.getContext('2d');
        
        if (chartData.type === 'score_breakdown') {
            // Render perspective scores as bar chart
            const data = chartData.data;
            const labels = Object.keys(data);
            const values = Object.values(data);
            
            new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'Score (%)',
                        data: values,
                        backgroundColor: [
                            'rgba(255, 99, 132, 0.7)',
                            'rgba(54, 162, 235, 0.7)',
                            'rgba(255, 206, 86, 0.7)',
                            'rgba(75, 192, 192, 0.7)'
                        ],
                        borderColor: [
                            'rgba(255, 99, 132, 1)',
                            'rgba(54, 162, 235, 1)',
                            'rgba(255, 206, 86, 1)',
                            'rgba(75, 192, 192, 1)'
                        ],
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 100,
                            title: {
                                display: true,
                                text: 'Score (%)'
                            }
                        }
                    },
                    plugins: {
                        title: {
                            display: true,
                            text: chartData.title
                        },
                        legend: {
                            display: false
                        }
                    }
                }
            });
        } else if (chartData.type === 'achievement_status') {
            // Render achievement status as doughnut chart
            const data = chartData.data;
            
            new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: ['Achieved', 'Not Achieved', 'No Data'],
                    datasets: [{
                        data: [
                            data.achieved || 0,
                            data.not_achieved || 0,
                            data.no_data || 0
                        ],
                        backgroundColor: [
                            'rgba(40, 167, 69, 0.7)',
                            'rgba(220, 53, 69, 0.7)',
                            'rgba(255, 193, 7, 0.7)'
                        ],
                        borderColor: [
                            'rgba(40, 167, 69, 1)',
                            'rgba(220, 53, 69, 1)',
                            'rgba(255, 193, 7, 1)'
                        ],
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        title: {
                            display: true,
                            text: chartData.title
                        },
                        legend: {
                            position: 'bottom'
                        }
                    }
                }
            });
        }
    }



    async deleteFile(fileId) {
        if (!confirm('Are you sure you want to delete this file? This action cannot be undone.')) {
            return;
        }

        try {
            const response = await this.authFetch(`${this.apiBaseUrl}/files/delete/${fileId}`, {
                method: 'DELETE',
                headers: { 'Content-Type': 'application/json' }
            });

            const result = await response.json();

            if (result.success) {
                this.showNotification('File deleted successfully', 'success');
                await this.loadFilesList();
                await this.loadDashboardMetrics();
            } else {
                throw new Error(result.message || 'Delete failed');
            }
        } catch (error) {
            console.error('Delete error:', error);
            this.showNotification('Delete failed: ' + error.message, 'error');
        }
    }

    async connectNextcloud() {
        try {
            const response = await this.authFetch(`${this.apiBaseUrl}/auth/nextcloud`);
            const result = await response.json();
            
            if (result.auth_url) {
                window.location.href = result.auth_url;
            } else {
                this.showNotification('Failed to get Nextcloud authorization URL', 'error');
            }
        } catch (error) {
            console.error('Nextcloud connection error:', error);
            this.showNotification('Failed to connect to Nextcloud', 'error');
        }
    }

    onTabChange(targetId) {
        switch (targetId) {
            case 'files':
                this.loadFilesList();
                break;
            case 'nextcloud':
                this.loadNextcloudFiles();
                break;
        }
    }

    async loadNextcloudFiles() {
        try {
            const response = await this.authFetch(`${this.apiBaseUrl}/nextcloud/files`);
            const result = await response.json();
            
            const container = document.getElementById('nextcloud-files');
            if (!container) return;

            if (result.files && result.files.length > 0) {
                container.innerHTML = `
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>Filename</th>
                                    <th>Size</th>
                                    <th>Modified</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${result.files.map(file => `
                                    <tr>
                                        <td><i class="fas fa-file-excel text-success me-2"></i>${file.name}</td>
                                        <td>${this.formatFileSize(file.size)}</td>
                                        <td>${file.modified}</td>
                                        <td>
                                            <button class="btn btn-sm btn-primary" onclick="dashboard.downloadNextcloudFile('${file.id}')">
                                                <i class="fas fa-download"></i>
                                            </button>
                                        </td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>
                `;
            } else {
                container.innerHTML = '<p class="text-muted">No files found in Nextcloud KPI folder.</p>';
            }
        } catch (error) {
            console.error('Error loading Nextcloud files:', error);
            const container = document.getElementById('nextcloud-files');
            if (container) {
                container.innerHTML = '<p class="text-danger">Error loading Nextcloud files. Please check your connection.</p>';
            }
        }
    }

    async downloadNextcloudFile(fileId) {
        try {
            const response = await this.authFetch(`${this.apiBaseUrl}/nextcloud/download/${fileId}`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' }
            });

            const result = await response.json();

            if (result.success) {
                this.showNotification('File downloaded and queued for processing', 'success');
                await this.loadFilesList();
            } else {
                throw new Error(result.message || 'Download failed');
            }
        } catch (error) {
            console.error('Download error:', error);
            this.showNotification('Download failed: ' + error.message, 'error');
        }
    }



    formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    showNotification(message, type = 'info') {
        // Create notification element
        const notification = document.createElement('div');
        notification.className = `alert alert-${this.getAlertClass(type)} alert-dismissible fade show position-fixed`;
        notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
        
        notification.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        document.body.appendChild(notification);
        
        // Auto-dismiss after 5 seconds
        setTimeout(() => {
            if (notification.parentNode) {
                notification.remove();
            }
        }, 5000);
    }

    getAlertClass(type) {
        const typeMap = {
            'success': 'success',
            'error': 'danger',
            'warning': 'warning',
            'info': 'info'
        };
        return typeMap[type] || 'info';
    }

    startProcessingPoll(fileId) {
        // Poll every 5 seconds to check if file is processed
        const pollInterval = setInterval(async () => {
            try {
                const response = await this.authFetch(`${this.apiBaseUrl}/files/list`);
                const data = await response.json();
                
                if (data.files) {
                    const file = data.files.find(f => f.id === fileId);
                    
                    if (file && file.processed) {
                        // File is processed, stop polling and refresh
                        clearInterval(pollInterval);
                        this.showNotification('Analysis completed! You can now view the results.', 'success');
                        await this.loadFilesList();
                        await this.loadDashboardMetrics();
                    }
                }
            } catch (error) {
                console.error('Error polling file status:', error);
                // Stop polling after error
                clearInterval(pollInterval);
            }
        }, 5000); // Check every 5 seconds
        
        // Stop polling after 5 minutes (60 checks)
        setTimeout(() => {
            clearInterval(pollInterval);
        }, 300000);
    }
}

// Global dashboard instance
let dashboard;

// Initialize dashboard when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    dashboard = new KPIDashboard();
});

// Global functions for HTML onclick handlers
window.refreshData = () => dashboard.loadInitialData();
window.uploadFile = () => dashboard.uploadFile();
window.connectNextcloud = () => dashboard.connectNextcloud();
window.analyzeFile = (fileId) => dashboard.analyzeFile(fileId);
window.viewAnalysisResults = (fileId) => dashboard.viewAnalysisResults(fileId);
window.downloadPDFReport = (fileId) => dashboard.downloadPDFReport(fileId);
window.deleteFile = (fileId) => dashboard.deleteFile(fileId);
window.downloadNextcloudFile = (fileId) => dashboard.downloadNextcloudFile(fileId);