// Authentication Module - Online Version

// Check if user is already logged in
function checkAuth() {
    const currentUser = localStorage.getItem('currentUser');
    const authToken = localStorage.getItem('authToken');
    
    if (currentUser && authToken) {
        try {
            const userData = JSON.parse(currentUser);
            if (userData && userData.username) {
                return userData;
            }
        } catch (e) {
            // Invalid data, clear storage
            localStorage.removeItem('currentUser');
            localStorage.removeItem('authToken');
        }
    }
    return null;
}

// Login function for online system
async function login(username, password) {
    try {
        const response = await fetch('/api/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username, password })
        });

        if (!response.ok) {
            const error = await response.json();
            throw new Error(error.error || 'Login failed');
        }

        const data = await response.json();
        
        // Store authentication data
        localStorage.setItem('authToken', data.token);
        localStorage.setItem('currentUser', JSON.stringify(data.user));
        
        return data.user;
    } catch (error) {
        throw error;
    }
}

// Logout function
function logout() {
    localStorage.removeItem('authToken');
    localStorage.removeItem('currentUser');
    window.location.href = '/';
}

// Check if user has permission for a specific module
function hasPermission(module) {
    const currentUser = checkAuth();
    if (!currentUser) return false;
    return currentUser.permissions[module] === true;
}

// Redirect to login if not authenticated
function requireAuth() {
    const currentUser = checkAuth();
    if (!currentUser) {
        window.location.href = '/';
        return false;
    }
    return currentUser;
}

// Toggle password visibility
function togglePassword() {
    const passwordInput = document.getElementById('password');
    const passwordEye = document.getElementById('password-eye');
    
    if (passwordInput && passwordEye) {
        if (passwordInput.type === 'password') {
            passwordInput.type = 'text';
            passwordEye.className = 'fas fa-eye-slash';
        } else {
            passwordInput.type = 'password';
            passwordEye.className = 'fas fa-eye';
        }
    }
}

// Login form handler
if (document.getElementById('login-form')) {
    document.getElementById('login-form').addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const username = document.getElementById('username').value.trim();
        const password = document.getElementById('password').value;
        const errorMessage = document.getElementById('error-message');
        const submitButton = e.target.querySelector('button[type="submit"]');
        
        // Show loading state
        if (submitButton) {
            submitButton.disabled = true;
            submitButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Logging in...';
        }
        
        try {
            const userData = await login(username, password);
            
            // Show success message
            if (errorMessage) {
                errorMessage.style.display = 'block';
                errorMessage.style.color = '#4CAF50';
                errorMessage.textContent = `Welcome, ${userData.name}! Redirecting...`;
            }
            
            // Redirect to main application after a short delay
            setTimeout(() => {
                window.location.href = '/app';
            }, 1500);
            
        } catch (error) {
            if (errorMessage) {
                errorMessage.style.display = 'block';
                errorMessage.style.color = '#f44336';
                errorMessage.textContent = error.message;
                
                // Hide error after 5 seconds
                setTimeout(() => {
                    errorMessage.style.display = 'none';
                }, 5000);
            }
        } finally {
            // Reset button state
            if (submitButton) {
                submitButton.disabled = false;
                submitButton.innerHTML = '<i class="fas fa-sign-in-alt"></i> Login';
            }
        }
    });
}

// Initialize authentication on main app
function initializeAuth() {
    const currentUser = requireAuth();
    if (!currentUser) return;
    
    // Update user info display
    updateUserDisplay(currentUser);
    
    // Apply role-based access control
    applyRoleBasedAccess(currentUser);
}

// Update user display in header
function updateUserDisplay(userData) {
    const userWelcome = document.getElementById('user-welcome');
    const userRole = document.getElementById('user-role');
    
    if (userWelcome) {
        userWelcome.textContent = `Welcome, ${userData.name}`;
    }
    
    if (userRole) {
        userRole.innerHTML = `
            <i class="fas fa-id-badge"></i>
            <span>Role: ${userData.role.charAt(0).toUpperCase() + userData.role.slice(1)}</span>
        `;
    }
}

// Apply role-based access control
function applyRoleBasedAccess(userData) {
    const navLinks = document.querySelectorAll('.nav-link');
    
    navLinks.forEach(link => {
        const section = link.getAttribute('data-section');
        
        if (section && !userData.permissions[section]) {
            // Hide navigation item for sections without permission
            const listItem = link.parentElement;
            if (listItem) {
                listItem.style.display = 'none';
            }
            
            // Add click handler to show access denied message
            link.addEventListener('click', function(e) {
                e.preventDefault();
                showAccessDeniedMessage();
            });
        }
    });
    
    // Hide staff management actions in dashboard for non-admin users
    if (!userData.permissions.staff) {
        const staffActions = document.querySelectorAll('[data-section="staff"]');
        staffActions.forEach(action => {
            action.style.display = 'none';
        });
    }
}

// Show access denied message
function showAccessDeniedMessage() {
    if (window.app && window.app.showNotification) {
        window.app.showNotification('Access denied. You do not have permission to view this section.', 'error');
    } else {
        alert('Access denied. You do not have permission to view this section.');
    }
}

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

// Close dropdown when clicking outside
document.addEventListener('click', function(event) {
    const dropdown = document.getElementById('user-dropdown');
    const dropdownBtn = document.querySelector('.dropdown-btn');
    
    if (dropdown && dropdownBtn && !dropdown.contains(event.target) && !dropdownBtn.contains(event.target)) {
        dropdown.style.display = 'none';
    }
});

// Network status monitoring
function monitorNetworkStatus() {
    function updateNetworkStatus() {
        const isOnline = navigator.onLine;
        const statusIndicator = document.querySelector('.network-status');
        
        if (statusIndicator) {
            statusIndicator.className = `network-status ${isOnline ? 'online' : 'offline'}`;
            statusIndicator.textContent = isOnline ? 'Online' : 'Offline';
        }
        
        if (!isOnline && window.app) {
            window.app.showNotification('You are currently offline. Some features may not work properly.', 'warning');
        }
    }
    
    window.addEventListener('online', updateNetworkStatus);
    window.addEventListener('offline', updateNetworkStatus);
    updateNetworkStatus(); // Initial check
}

// Initialize network monitoring when DOM is ready
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', monitorNetworkStatus);
} else {
    monitorNetworkStatus();
}