// Authentication Manager
class AuthManager {
    constructor() {
        this.user = null;
        this.token = null;
        this.init();
    }

    init() {
        // Load saved session
        this.loadSession();

        const path = window.location.pathname;
        const isPublicPage = path.includes('login.html') || path.includes('offline.html');
        const isKitchenPage = path.includes('kitchen.html');

        // Check if user is logged in
        if (!this.isAuthenticated() && !isPublicPage) {
            if (isKitchenPage) {
                window.location.href = '/admin-login.html';
            } else {
                window.location.href = '/login.html';
            }
        }
    }

    loadSession() {
        const savedToken = localStorage.getItem('auth_token');
        const savedUser = localStorage.getItem('user_data');

        if (savedToken && savedUser) {
            this.token = savedToken;
            this.user = JSON.parse(savedUser);
            this.updateUI();
        }
    }

    saveSession(token, user) {
        this.token = token;
        this.user = user;
        localStorage.setItem('auth_token', token);
        localStorage.setItem('user_data', JSON.stringify(user));
        this.updateUI();
    }

    clearSession() {
        this.token = null;
        this.user = null;
        localStorage.removeItem('auth_token');
        localStorage.removeItem('user_data');
    }

    isAuthenticated() {
        return this.token !== null && this.user !== null;
    }

    getAuthHeaders() {
        return {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${this.token}`
        };
    }

    updateUI() {
        const userNameEl = document.getElementById('userName');
        if (userNameEl && this.user) {
            userNameEl.textContent = this.user.name || this.user.student_id;
        }
    }

    async login(studentId) {
        try {
            const response = await fetch('/api/auth/login', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ student_id: studentId })
            });

            const data = await response.json();

            if (!response.ok) {
                return {
                    success: false,
                    error: data.error || 'Login failed',
                    status: response.status
                };
            }

            // Save session
            if (data.token && data.user) {
                this.saveSession(data.token, data.user);
                return { success: true, user: data.user };
            }

            return { success: false, error: 'Invalid login response' };
        } catch (error) {
            console.error('Login error:', error);
            return { success: false, error: 'Network error occurred' };
        }
    }

    async logout() {
        try {
            await fetch('/api/auth/logout', {
                method: 'POST',
                headers: this.getAuthHeaders(),
                body: JSON.stringify({ token: this.token })
            });
        } catch (error) {
            console.error('Logout error:', error);
        } finally {
            this.clearSession();
            if (window.location.pathname.includes('kitchen.html')) {
                window.location.href = '/admin-login.html';
            } else {
                window.location.href = '/login.html';
            }
        }
    }

    async verifyToken() {
        try {
            const response = await fetch('/api/auth/verify', {
                method: 'POST',
                headers: this.getAuthHeaders(),
                body: JSON.stringify({ token: this.token })
            });

            if (!response.ok) {
                throw new Error('Token verification failed');
            }

            const data = await response.json();
            if (data.success) {
                this.user = data.user;
                localStorage.setItem('user_data', JSON.stringify(data.user));
                return true;
            }

            return false;
        } catch (error) {
            console.error('Token verification error:', error);
            this.clearSession();

            if (window.location.pathname.includes('kitchen.html')) {
                window.location.href = '/admin-login.html';
            } else {
                window.location.href = '/login.html';
            }
            return false;
        }
    }
}

// Initialize auth manager
const auth = new AuthManager();

// Setup logout button
document.addEventListener('DOMContentLoaded', () => {
    const logoutBtn = document.getElementById('logoutBtn');
    if (logoutBtn) {
        logoutBtn.addEventListener('click', () => auth.logout());
    }
});

// Export for use in other scripts
window.auth = auth;
