// NeuroConnect Therapy Management System - Online Version
// Main Application Module with API Integration

class NeuroConnectApp {
    constructor() {
        this.apiBase = '';  // Empty for same-origin requests
        this.token = localStorage.getItem('authToken');
        this.currentUser = null;
        this.cache = new Map();
        this.init();
    }

    async init() {
        // Check authentication
        if (this.token) {
            try {
                // Verify token is still valid by making a test request
                await this.makeApiRequest('/api/staff');
                this.initializeApp();
            } catch (error) {
                // Token invalid, redirect to login
                this.logout();
            }
        }
    }

    async makeApiRequest(endpoint, options = {}) {
        const defaultOptions = {
            headers: {
                'Content-Type': 'application/json',
                ...(this.token && { 'Authorization': `Bearer ${this.token}` })
            }
        };

        const response = await fetch(this.apiBase + endpoint, {
            ...defaultOptions,
            ...options,
            headers: { ...defaultOptions.headers, ...options.headers }
        });

        if (!response.ok) {
            if (response.status === 401) {
                this.logout();
                throw new Error('Authentication required');
            }
            throw new Error(`API request failed: ${response.statusText}`);
        }

        return response.json();
    }

    async login(username, password) {
        try {
            const response = await this.makeApiRequest('/api/login', {
                method: 'POST',
                body: JSON.stringify({ username, password })
            });

            this.token = response.token;
            this.currentUser = response.user;
            localStorage.setItem('authToken', this.token);
            localStorage.setItem('currentUser', JSON.stringify(this.currentUser));

            return response.user;
        } catch (error) {
            throw error;
        }
    }

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

    // Data management methods
    async getData(type) {
        try {
            // Check cache first
            if (this.cache.has(type)) {
                return this.cache.get(type);
            }

            const data = await this.makeApiRequest(`/api/${type}`);
            this.cache.set(type, data);
            return data;
        } catch (error) {
            console.error(`Failed to get ${type} data:`, error);
            return [];
        }
    }

    async saveData(type, data) {
        try {
            await this.makeApiRequest(`/api/${type}`, {
                method: 'POST',
                body: JSON.stringify(data)
            });

            // Update cache
            this.cache.set(type, data);
            return true;
        } catch (error) {
            console.error(`Failed to save ${type} data:`, error);
            throw error;
        }
    }

    // Utility methods
    generateId(type) {
        return Date.now() + Math.random().toString(36).substr(2, 9);
    }

    formatDate(dateString) {
        if (!dateString) return '';
        const date = new Date(dateString);
        return date.toLocaleDateString('en-US', {
            year: 'numeric',
            month: 'short',
            day: 'numeric'
        });
    }

    formatTime(timeString) {
        if (!timeString) return '';
        return new Date(`2000-01-01T${timeString}`).toLocaleTimeString('en-US', {
            hour: 'numeric',
            minute: '2-digit',
            hour12: true
        });
    }

    formatCurrency(amount) {
        return new Intl.NumberFormat('en-KE', {
            style: 'currency',
            currency: 'KES'
        }).format(amount || 0);
    }

    // Modal management
    showModal(modalContent) {
        const overlay = document.getElementById('modal-overlay');
        if (overlay) {
            overlay.innerHTML = modalContent;
            overlay.style.display = 'flex';
        }
    }

    closeModal() {
        const overlay = document.getElementById('modal-overlay');
        if (overlay) {
            overlay.style.display = 'none';
            overlay.innerHTML = '';
        }
    }

    // Notification system
    showNotification(message, type = 'info') {
        // Create notification element
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.innerHTML = `
            <div class="notification-content">
                <i class="fas fa-${this.getNotificationIcon(type)}"></i>
                <span>${message}</span>
                <button class="notification-close" onclick="this.parentElement.parentElement.remove()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `;

        // Add to page
        document.body.appendChild(notification);

        // Auto-remove after 5 seconds
        setTimeout(() => {
            if (notification.parentElement) {
                notification.remove();
            }
        }, 5000);
    }

    getNotificationIcon(type) {
        const icons = {
            success: 'check-circle',
            error: 'exclamation-circle',
            warning: 'exclamation-triangle',
            info: 'info-circle'
        };
        return icons[type] || 'info-circle';
    }

    // Export functionality
    exportToCSV(data, filename) {
        if (!data || data.length === 0) {
            this.showNotification('No data to export', 'warning');
            return;
        }

        const headers = Object.keys(data[0]);
        const csvContent = [
            headers.join(','),
            ...data.map(row => 
                headers.map(header => {
                    const value = row[header] || '';
                    return `"${String(value).replace(/"/g, '""')}"`;
                }).join(',')
            )
        ].join('\n');

        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);
        
        link.setAttribute('href', url);
        link.setAttribute('download', filename);
        link.style.visibility = 'hidden';
        
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        URL.revokeObjectURL(url);
    }

    // Initialize the application after authentication
    initializeApp() {
        this.updateStats();
        this.loadNavigationData();
        this.setupEventListeners();
    }

    async updateStats() {
        try {
            const [staff, patients, expenses] = await Promise.all([
                this.getData('staff'),
                this.getData('patients'),
                this.getData('expenses')
            ]);

            // Update dashboard stats
            const totalStaffEl = document.getElementById('total-staff');
            const totalPatientsEl = document.getElementById('total-patients');
            const monthlyExpensesEl = document.getElementById('monthly-expenses');

            if (totalStaffEl) totalStaffEl.textContent = staff.length;
            if (totalPatientsEl) totalPatientsEl.textContent = patients.length;
            
            if (monthlyExpensesEl) {
                const currentMonth = new Date().getMonth();
                const currentYear = new Date().getFullYear();
                const monthlyTotal = expenses
                    .filter(expense => {
                        const expenseDate = new Date(expense.date);
                        return expenseDate.getMonth() === currentMonth && 
                               expenseDate.getFullYear() === currentYear;
                    })
                    .reduce((total, expense) => total + (expense.amount || 0), 0);
                
                monthlyExpensesEl.textContent = this.formatCurrency(monthlyTotal);
            }
        } catch (error) {
            console.error('Failed to update stats:', error);
        }
    }

    loadNavigationData() {
        // Load data for each section when needed
        const navLinks = document.querySelectorAll('.nav-link');
        navLinks.forEach(link => {
            link.addEventListener('click', async (e) => {
                e.preventDefault();
                const section = link.getAttribute('data-section');
                await this.loadSection(section);
            });
        });
    }

    async loadSection(sectionName) {
        try {
            // Show loading state
            this.showNotification('Loading data...', 'info');

            // Clear cache for fresh data
            this.cache.delete(sectionName);

            // Load section-specific data
            switch (sectionName) {
                case 'staff':
                    if (window.loadStaffData) await window.loadStaffData();
                    break;
                case 'patients':
                    if (window.loadPatientData) await window.loadPatientData();
                    break;
                case 'schedule':
                    if (window.loadScheduleData) await window.loadScheduleData();
                    break;
                case 'expenses':
                    if (window.loadExpenseData) await window.loadExpenseData();
                    break;
                case 'stock':
                    if (window.loadStockData) await window.loadStockData();
                    break;
                case 'reports':
                    if (window.loadReportsData) await window.loadReportsData();
                    break;
            }

            // Update navigation
            this.showSection(sectionName);
        } catch (error) {
            this.showNotification('Failed to load section data', 'error');
            console.error('Section loading error:', error);
        }
    }

    showSection(sectionName) {
        // Hide all sections
        document.querySelectorAll('.content-section').forEach(section => {
            section.classList.remove('active');
        });

        // Show target section
        const targetSection = document.getElementById(sectionName);
        if (targetSection) {
            targetSection.classList.add('active');
        }

        // Update navigation
        document.querySelectorAll('.nav-link').forEach(link => {
            link.classList.remove('active');
        });

        const activeLink = document.querySelector(`[data-section="${sectionName}"]`);
        if (activeLink) {
            activeLink.classList.add('active');
        }

        // Update page title
        const pageTitle = document.getElementById('page-title');
        if (pageTitle) {
            const sectionTitles = {
                dashboard: 'Dashboard',
                staff: 'Staff Management',
                expenses: 'Office Expenses',
                patients: 'Patient Records',
                schedule: 'Therapy Schedule',
                stock: 'Stock Control',
                reports: 'Reports'
            };
            pageTitle.textContent = sectionTitles[sectionName] || 'Dashboard';
        }
    }

    setupEventListeners() {
        // Close modal on overlay click
        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('modal-overlay')) {
                this.closeModal();
            }
        });

        // Close modal with Escape key
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                this.closeModal();
            }
        });
    }
}

// Initialize the application
window.app = new NeuroConnectApp();

// Global functions for compatibility
function showAddStaffModal() {
    if (typeof showStaffModal === 'function') {
        showStaffModal();
    } else {
        window.app.showNotification('Staff modal not available', 'error');
    }
}

function logout() {
    window.app.logout();
}

function toggleUserDropdown() {
    const dropdown = document.getElementById('user-dropdown');
    if (dropdown) {
        dropdown.style.display = dropdown.style.display === 'block' ? 'none' : 'block';
    }
}

// Export for module usage
if (typeof module !== 'undefined' && module.exports) {
    module.exports = NeuroConnectApp;
}