/**
 * Admin Panel Client-Side JavaScript
 * Handles authentication, data fetching, chart rendering, and game management
 */

// Toast Notification System
function showToast(message, type = 'info', description = '') {
    const container = document.getElementById('toast-container');
    if (!container) return;

    const icons = {
        success: 'fa-circle-check',
        error: 'fa-circle-xmark',
        warning: 'fa-triangle-exclamation',
        info: 'fa-circle-info'
    };

    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.innerHTML = `
        <i class="fas ${icons[type]} toast-icon"></i>
        <div class="toast-content">
            <div class="toast-message">${message}</div>
            ${description ? `<p class="toast-description">${description}</p>` : ''}
        </div>
        <button class="toast-close" aria-label="Close">&times;</button>
    `;

    container.appendChild(toast);

    // Close button functionality
    const closeBtn = toast.querySelector('.toast-close');
    closeBtn.addEventListener('click', () => removeToast(toast));

    // Auto remove after 5 seconds
    setTimeout(() => removeToast(toast), 5000);
}

function removeToast(toast) {
    toast.classList.add('removing');
    setTimeout(() => toast.remove(), 300);
}

// State
let currentRange = 'week';
let trafficChart = null;
let gamesChart = null;
let comparisonChart = null;
let comparisonData = null;
let deviceTypeChart = null;
let osChart = null;
let browserChart = null;
let currentSection = 'overview';
let sidebarCollapsed = false;

// DOM Elements
const loginScreen = document.getElementById('login-screen');
const adminDashboard = document.getElementById('admin-dashboard');
const loginForm = document.getElementById('login-form');
const loginError = document.getElementById('login-error');
const logoutBtn = document.getElementById('logout-btn');
const refreshBtn = document.getElementById('refresh-data');
const editModal = document.getElementById('edit-modal');
const editForm = document.getElementById('edit-form');
const modalClose = document.getElementById('modal-close');
const cancelEdit = document.getElementById('cancel-edit');
const addUserModal = document.getElementById('add-user-modal');
const addUserForm = document.getElementById('add-user-form');
const addUserClose = document.getElementById('add-user-close');
const cancelAddUser = document.getElementById('cancel-add-user');
const btnAddUser = document.getElementById('btn-add-user');

const editUserModal = document.getElementById('edit-user-modal');
const editUserForm = document.getElementById('edit-user-form');
const editUserClose = document.getElementById('edit-user-close');
const cancelEditUser = document.getElementById('cancel-edit-user');

const maintenanceModal = document.getElementById('maintenance-modal');
const maintenanceForm = document.getElementById('maintenance-form');
const maintenanceClose = document.getElementById('maintenance-modal-close');
const cancelMaintenance = document.getElementById('cancel-maintenance');

// Current user info
let currentUser = null;

// Users State
const usersState = {
    allUsers: [],
    filteredUsers: [],
    searchQuery: '',
    roleFilter: 'all',
    statusFilter: 'all'
};

const testimonialsState = {
    allTestimonials: []
};

let usersPagination = null;

// ========================================
// Fullscreen Management (Initialize ASAP to prevent flicker)
// ========================================
(function initializeFullscreen() {
    const isFullscreenEnabled = localStorage.getItem('adminFullscreen') === 'true';
    
    if (isFullscreenEnabled && document.documentElement.requestFullscreen) {
        // Try to apply fullscreen immediately on page load
        // This might be blocked by browser security, so we'll retry after DOMContentLoaded
        const attemptFullscreen = () => {
            if (!document.fullscreenElement) {
                document.documentElement.requestFullscreen().catch(err => {
                    console.log('Initial fullscreen request blocked, will retry after user interaction');
                });
            }
        };
        
        // Try immediately
        attemptFullscreen();
        
        // Also try after DOM is ready with a small delay
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => {
                setTimeout(attemptFullscreen, 100);
            });
        } else {
            setTimeout(attemptFullscreen, 100);
        }
        
        // If still not in fullscreen after page load, wait for user interaction
        const enableFullscreenOnInteraction = () => {
            if (!document.fullscreenElement && localStorage.getItem('adminFullscreen') === 'true') {
                document.documentElement.requestFullscreen().catch(err => {
                    console.log('Fullscreen request failed:', err);
                });
                // Remove listener after first successful attempt
                document.removeEventListener('click', enableFullscreenOnInteraction);
                document.removeEventListener('keydown', enableFullscreenOnInteraction);
            }
        };
        
        // Add one-time listeners for user interaction
        setTimeout(() => {
            if (!document.fullscreenElement) {
                document.addEventListener('click', enableFullscreenOnInteraction, { once: false });
                document.addEventListener('keydown', enableFullscreenOnInteraction, { once: false });
            }
        }, 500);
    }
})();

document.addEventListener('DOMContentLoaded', async () => {
    // Determine current section based on URL or active content
    const path = window.location.pathname;
    if (path.includes('/games')) currentSection = 'games';
    else if (path.includes('/analytics')) currentSection = 'analytics';
    else if (path.includes('/users')) currentSection = 'users';
    else if (path.includes('/testimonials')) currentSection = 'testimonials';
    else if (path.includes('/settings')) currentSection = 'settings';
    else if (path.includes('/login')) currentSection = 'login';
    else currentSection = 'overview';

    // Wait for auth check to complete before loading data
    await checkAuth(); 
    setupEventListeners();
    
    // Load data for the current page (now currentUser is set)
    loadSectionData(currentSection);
});

// Removed handleInitialRoute as it's no longer needed

// Setup event listeners
function setupEventListeners() {
    if (loginForm) loginForm.addEventListener('submit', handleLogin);
    if (logoutBtn) {
        logoutBtn.addEventListener('click', (e) => {
            e.preventDefault();
            showConfirmation(
                'Logout',
                'Are you sure you want to logout?',
                handleLogout
            );
        });
    }
    if (refreshBtn) refreshBtn.addEventListener('click', loadDashboardData);
    if (modalClose) modalClose.addEventListener('click', closeEditModal);
    if (cancelEdit) cancelEdit.addEventListener('click', closeEditModal);
    if (editForm) editForm.addEventListener('submit', handleEditSave);

    // User profile dropdown
    const userProfileTrigger = document.getElementById('user-profile-trigger');
    const userDropdown = document.querySelector('.user-profile-dropdown');
    if (userProfileTrigger && userDropdown) {
        userProfileTrigger.addEventListener('click', (e) => {
            e.stopPropagation();
            userDropdown.classList.toggle('active');
        });

        // Close dropdown when clicking outside
        document.addEventListener('click', (e) => {
            if (!userDropdown.contains(e.target)) {
                userDropdown.classList.remove('active');
            }
        });
    }

    // Fullscreen Toggle
    const fullscreenToggle = document.getElementById('fullscreen-toggle');
    if (fullscreenToggle) {
        fullscreenToggle.addEventListener('click', toggleFullscreen);
        
        // Listen for fullscreen changes (including ESC key)
        document.addEventListener('fullscreenchange', updateFullscreenIcon);
        
        // Update icon on load based on current state
        updateFullscreenIcon();
    }

    // User management
    if (btnAddUser) btnAddUser.addEventListener('click', () => openModal(addUserModal));
    if (addUserClose) addUserClose.addEventListener('click', () => closeModal(addUserModal));
    if (cancelAddUser) cancelAddUser.addEventListener('click', () => closeModal(addUserModal));
    if (addUserForm) addUserForm.addEventListener('submit', handleAddUser);
    
    if (editUserClose) editUserClose.addEventListener('click', () => closeModal(editUserModal));
    if (cancelEditUser) cancelEditUser.addEventListener('click', () => closeModal(editUserModal));
    if (editUserForm) editUserForm.addEventListener('submit', handleSaveUser);

    // Maintenance Modal
    if (maintenanceClose) maintenanceClose.addEventListener('click', () => closeModal(maintenanceModal));
    if (cancelMaintenance) cancelMaintenance.addEventListener('click', () => closeModal(maintenanceModal));
    if (maintenanceForm) maintenanceForm.addEventListener('submit', (e) => {
        e.preventDefault();
        saveMaintenanceSettings();
    });

    // Testimonials Management
    const btnAddTestimonial = document.getElementById('btn-add-testimonial');
    const addTestimonialModal = document.getElementById('add-testimonial-modal');
    const closeAddTestimonial = document.getElementById('close-add-testimonial');
    const cancelAddTestimonial = document.getElementById('cancel-add-testimonial');
    const addTestimonialForm = document.getElementById('add-testimonial-form');

    if (btnAddTestimonial) btnAddTestimonial.addEventListener('click', () => openModal(addTestimonialModal));
    if (closeAddTestimonial) closeAddTestimonial.addEventListener('click', () => closeModal(addTestimonialModal));
    if (cancelAddTestimonial) cancelAddTestimonial.addEventListener('click', () => closeModal(addTestimonialModal));
    if (addTestimonialForm) addTestimonialForm.addEventListener('submit', handleAddTestimonial);

    const editTestimonialModal = document.getElementById('edit-testimonial-modal');
    const closeEditTestimonial = document.getElementById('close-edit-testimonial');
    const cancelEditTestimonial = document.getElementById('cancel-edit-testimonial');
    const editTestimonialForm = document.getElementById('edit-testimonial-form');

    if (closeEditTestimonial) closeEditTestimonial.addEventListener('click', () => closeModal(editTestimonialModal));
    if (cancelEditTestimonial) cancelEditTestimonial.addEventListener('click', () => closeModal(editTestimonialModal));
    if (editTestimonialForm) editTestimonialForm.addEventListener('submit', handleEditTestimonial);

    // Confirmation Modal
    const confirmationModal = document.getElementById('confirmation-modal');
    const confirmationClose = document.getElementById('confirmation-close');
    const cancelConfirmation = document.getElementById('cancel-confirmation');
    const confirmActionBtn = document.getElementById('confirm-action-btn');
    
    let pendingConfirmationAction = null;

    if (confirmationClose) confirmationClose.addEventListener('click', () => closeModal(confirmationModal));
    if (cancelConfirmation) cancelConfirmation.addEventListener('click', () => closeModal(confirmationModal));
    
    if (confirmActionBtn) {
        confirmActionBtn.addEventListener('click', () => {
            if (pendingConfirmationAction) {
                pendingConfirmationAction();
                pendingConfirmationAction = null;
            }
            closeModal(confirmationModal);
        });
    }

    window.showConfirmation = (title, message, onConfirm) => {
        const titleEl = document.getElementById('confirmation-title');
        const messageEl = document.getElementById('confirmation-message');
        
        if (titleEl) titleEl.textContent = title;
        if (messageEl) messageEl.textContent = message;
        
        pendingConfirmationAction = onConfirm;
        openModal(confirmationModal);
    };

    const userSearch = document.getElementById('user-search');
    if (userSearch) {
        userSearch.addEventListener('input', (e) => {
            usersState.searchQuery = e.target.value.toLowerCase();
            filterUsers();
        });
    }

    const roleFilter = document.getElementById('role-filter');
    if (roleFilter) {
        roleFilter.addEventListener('change', (e) => {
            usersState.roleFilter = e.target.value;
            filterUsers();
        });
    }

    const userStatusFilter = document.getElementById('status-filter');
    if (userStatusFilter) {
        userStatusFilter.addEventListener('change', (e) => {
            usersState.statusFilter = e.target.value;
            filterUsers();
        });
    }

    // Game filter event listeners
    const gameSearch = document.getElementById('game-search');
    if (gameSearch) {
        gameSearch.addEventListener('input', (e) => {
            gamesState.searchQuery = e.target.value.toLowerCase();
            filterGames();
        });
    }

    const categoryFilter = document.getElementById('category-filter');
    if (categoryFilter) {
        categoryFilter.addEventListener('change', (e) => {
            gamesState.categoryFilter = e.target.value;
            filterGames();
        });
    }

    const statusFilter = document.getElementById('status-filter');
    if (statusFilter) {
        statusFilter.addEventListener('change', (e) => {
            gamesState.statusFilter = e.target.value;
            filterGames();
        });
    }

    // Initialize users pagination
    usersPagination = new TablePagination({
        state: usersState,
        itemsKey: 'filteredUsers',
        renderCallback: renderUsers,
        idPrefix: 'users',
        itemsPerPage: 25
    });
    
    // Settings form
    const passwordForm = document.getElementById('password-form');
    if (passwordForm) passwordForm.addEventListener('submit', handlePasswordUpdate);

    // Profile forms
    const updateUsernameForm = document.getElementById('update-username-form');
    const changePasswordForm = document.getElementById('change-password-form');
    if (updateUsernameForm) updateUsernameForm.addEventListener('submit', handleUpdateUsername);
    if (changePasswordForm) changePasswordForm.addEventListener('submit', handleChangePassword);

    // Time range selector
    document.querySelectorAll('.range-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
            document.querySelectorAll('.range-btn').forEach(b => b.classList.remove('active'));
            e.target.classList.add('active');
            currentRange = e.target.dataset.range;
            loadTrafficChart();
        });
    });

    // Game and User Actions Delegation
    document.addEventListener('click', (e) => {
        // Check if click is within users-table only (games handled separately)
        if (!e.target.closest('#users-table-body')) return;
        
        const target = e.target.closest('button');
        if (!target) return;

        const action = target.dataset.action;
        const id = target.dataset.id;

        if (action === 'delete-user') {
            showConfirmation(
                'Delete User',
                'Are you sure you want to delete this user? This action cannot be undone.',
                () => deleteUser(id)
            );
        } else if (action === 'edit-user') {
            openEditUserModal(id);
        }
    });

    // Testimonials Actions Delegation
    const testimonialsTable = document.getElementById('testimonials-table-body');
    if (testimonialsTable) {
        testimonialsTable.addEventListener('click', (e) => {
            const button = e.target.closest('button[data-action]');
            if (!button) return;

            const action = button.dataset.action;
            const id = button.dataset.id;

            if (action === 'delete-testimonial') {
                showConfirmation(
                    'Delete Testimonial',
                    'Are you sure you want to delete this testimonial?',
                    () => deleteTestimonial(id)
                );
            } else if (action === 'edit-testimonial') {
                editTestimonial(id);
            }
        });
    }

    // Game comparison metric selector
    const comparisonMetric = document.getElementById('comparison-metric');
    if (comparisonMetric) {
        comparisonMetric.addEventListener('change', (e) => {
            renderComparisonChart(e.target.value);
        });
    }

    // Sidebar navigation - Standard links now, no JS interception needed
    // document.querySelectorAll('.nav-item').forEach(item => {
    //     item.addEventListener('click', (e) => {
    //         e.preventDefault();
    //         const section = item.dataset.section;
    //         navigateToSection(section, true);
    //     });
    // });
    
    // Sidebar toggle (mobile)
    const sidebarToggle = document.getElementById('sidebar-toggle');
    if (sidebarToggle) {
        sidebarToggle.addEventListener('click', toggleSidebar);
    }

    // Game actions - Event delegation for dynamically created buttons
    const gamesGrid = document.getElementById('games-grid');
    if (gamesGrid) {
        gamesGrid.addEventListener('click', (e) => {
            const button = e.target.closest('button[data-action]');
            if (!button) return;

            const action = button.dataset.action;
            const gameId = button.dataset.id;

            if (action === 'toggle') {
                const enabled = button.dataset.enabled === 'true';
                const actionText = enabled ? 'disable' : 'enable';
                showConfirmation(
                    `${actionText.charAt(0).toUpperCase() + actionText.slice(1)} Game`,
                    `Are you sure you want to ${actionText} this game?`,
                    () => toggleGame(gameId, enabled)
                );
            } else if (action === 'edit') {
                editGame(gameId);
            }
        });
    }
    
    // Collapse sidebar on desktop (double-click)
    const sidebar = document.getElementById('sidebar');
    if (sidebar) {
        sidebar.addEventListener('dblclick', () => {
            if (window.innerWidth > 768) {
                toggleSidebarCollapse();
            }
        });
    }

    // Auto-collapse on tablet resize
    window.addEventListener('resize', () => {
        if (window.innerWidth <= 1024 && window.innerWidth > 768) {
            document.getElementById('admin-dashboard').classList.add('sidebar-collapsed');
        } else if (window.innerWidth > 1024) {
            document.getElementById('admin-dashboard').classList.remove('sidebar-collapsed');
        }
    });
}

function navigateToSection(sectionName, updateHistory = true) {
    // Deprecated in MPA mode
    console.log('Navigating to', sectionName);
}

function loadSectionData(section) {
    // In MPA, we only load data for the current section
    // The section is determined by the URL in DOMContentLoaded
    
    if (section === 'overview') {
        loadOverview();
        // Charts are on the overview page
        if (document.getElementById('traffic-chart')) loadTrafficChart();
    } else if (section === 'analytics') {
        if (document.getElementById('game-comparison-chart')) loadGameComparison();
        if (document.getElementById('games-chart')) loadGamesChart();
        if (document.getElementById('device-type-chart')) loadDeviceAnalytics();
        if (document.getElementById('os-chart')) loadDeviceAnalytics();
        if (document.getElementById('browser-chart')) loadDeviceAnalytics();
    } else if (section === 'games') {
        loadGames();
    } else if (section === 'users') {
        loadUsers();
    } else if (section === 'settings') {
        loadSettings();
    } else if (section === 'testimonials') {
        loadTestimonials();
    }
}


function toggleSidebar() {
    const sidebar = document.getElementById('sidebar');
    sidebar.classList.toggle('mobile-open');
}

function toggleSidebarCollapse() {
    const dashboard = document.getElementById('admin-dashboard');
    dashboard.classList.toggle('sidebar-collapsed');
    sidebarCollapsed = !sidebarCollapsed;
}

// Check authentication status
async function checkAuth() {
    try {
        const response = await axios.get('/admin/api/auth-check');
        const data = response.data;

        if (data.authenticated) {
            // Update UI with user info FIRST
            if (data.user) {
                currentUser = data.user;
                // updateUserUI(data.user); // Handled by EJS now
            }

            // If we are at login page but authenticated, redirect to overview
            if (window.location.pathname.includes('/login')) {
                window.location.href = '/admin/';
            }
            
            // Data loading is handled by DOMContentLoaded -> loadSectionData
        } else {
            // If not authenticated and not on login page, redirect
            if (!window.location.pathname.includes('/login')) {
                window.location.href = '/admin/login';
            }
        }
    } catch (error) {
        console.error('Auth check failed:', error);
        if (!window.location.pathname.includes('/login')) {
            window.location.href = '/admin/login';
        }
    }
}

// Handle login
async function handleLogin(e) {
    e.preventDefault();
    
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    loginError.style.display = 'none';

    try {
        const response = await axios.post('/admin/api/login', { username, password });
        const data = response.data;

        if (data.success) {
            window.location.href = '/admin/dashboard';
        } else {
            showError(data.error || 'Invalid credentials');
        }
    } catch (error) {
        console.error('Login failed:', error);
        const msg = error.response?.data?.error || 'An error occurred during login';
        showError(msg);
    }
}

// Handle logout
async function handleLogout() {
    try {
        await axios.post('/admin/api/logout');
        window.location.href = '/admin/login';
    } catch (error) {
        console.error('Logout failed:', error);
    }
}

// Show/hide screens
function showLogin() {
    // MPA handles this via redirect
}

function showDashboard() {
    // MPA handles this via redirect
}

function showError(message) {
    loginError.textContent = message;
    loginError.style.display = 'block';
}

function updateUserUI(user) {
    // Handled by EJS
}

// User Management Functions
async function loadUsers() {
    try {
        const response = await axios.get('/admin/api/users');
        const users = response.data;
        usersState.allUsers = users;
        filterUsers();
        renderUserStats(users);
    } catch (error) {
        if (error.response?.status === 403) return; // Forbidden
        console.error('Failed to load users:', error);
    }
}

function renderUserStats(users) {
    const totalUsers = users.length;
    const admins = users.filter(u => u.role === 'admin').length;
    const superusers = users.filter(u => u.role === 'superuser').length;
    const regularUsers = users.filter(u => u.role === 'user').length;

    const totalEl = document.getElementById('stat-total-users');
    const adminsEl = document.getElementById('stat-admins');
    const superusersEl = document.getElementById('stat-superusers');
    const usersEl = document.getElementById('stat-users');

    if (totalEl) totalEl.textContent = totalUsers;
    if (adminsEl) adminsEl.textContent = admins;
    if (superusersEl) superusersEl.textContent = superusers;
    if (usersEl) usersEl.textContent = regularUsers;
}

function filterUsers() {
    let filtered = usersState.allUsers;
    
    // Apply role filter
    if (usersState.roleFilter !== 'all') {
        filtered = filtered.filter(user => user.role === usersState.roleFilter);
    }
    
    // Apply status filter
    if (usersState.statusFilter !== 'all') {
        filtered = filtered.filter(user => user.status === usersState.statusFilter);
    }
    
    // Apply search filter
    if (usersState.searchQuery) {
        filtered = filtered.filter(user =>
            user.username.toLowerCase().includes(usersState.searchQuery) ||
            user.role.toLowerCase().includes(usersState.searchQuery)
        );
    }
    
    usersState.filteredUsers = filtered;
    if (usersPagination) usersPagination.resetToFirstPage();
    renderUsers();
}



function renderUsers() {
    const grid = document.getElementById('users-grid');
    const emptyState = document.getElementById('users-empty-state');
    
    if (!grid) return;

    // Early return if currentUser is not loaded yet
    if (!currentUser) {
        console.log('Waiting for currentUser to load...');
        return;
    }

    const pageUsers = usersPagination ? usersPagination.getPaginatedItems() : usersState.filteredUsers;

    // Show empty state if no users
    if (pageUsers.length === 0) {
        grid.style.display = 'none';
        if (emptyState) emptyState.style.display = 'block';
    } else {
        grid.style.display = 'grid';
        if (emptyState) emptyState.style.display = 'none';
    }

    grid.innerHTML = pageUsers.map(user => {
        const isMe = String(user.id) === String(currentUser.id);
        const canManage = canManageUser(currentUser, user.role);
        const roleIcon = {
            superuser: 'fa-crown',
            admin: 'fa-user-shield',
            user: 'fa-user'
        }[user.role] || 'fa-user';
       
        const status = user.status || 'active';
        const statusBadge = {
            active: '<span class="user-status-badge status-active"><i class="fas fa-circle"></i> Active</span>',
            inactive: '<span class="user-status-badge status-inactive"><i class="fas fa-circle"></i> Inactive</span>',
            archived: '<span class="user-status-badge status-archived"><i class="fas fa-archive"></i> Archived</span>'
        }[status] || '';
        
        // Determine action buttons based on status
        let actionButtons = '';
        if (canManage && !isMe) {
            if (status === 'archived') {
                // Archived users: show Restore and Permanent Delete
                actionButtons = `
                    <button class="btn-icon btn-success" data-action="restore-user" data-id="${user.id}">
                        <i class="fas fa-undo"></i> Restore
                    </button>
                    <button class="btn-icon danger" data-action="permanent-delete-user" data-id="${user.id}">
                        <i class="fas fa-trash"></i> Delete
                    </button>
                `;
            } else if (status === 'inactive') {
                // Inactive users: show Activate and Archive
                actionButtons = `
                    <button class="btn-icon btn-success" data-action="activate-user" data-id="${user.id}">
                        <i class="fas fa-check-circle"></i> Activate
                    </button>
                    <button class="btn-icon danger" data-action="archive-user" data-id="${user.id}">
                        <i class="fas fa-archive"></i> Archive
                    </button>
                `;
            } else {
                // Active users: show Edit, Deactivate, and Archive
                actionButtons = `
                    <button class="btn-icon" data-action="edit-user" data-id="${user.id}">
                        <i class="fas fa-edit"></i> Edit
                    </button>
                    <button class="btn-icon btn-warning" data-action="deactivate-user" data-id="${user.id}">
                        <i class="fas fa-pause-circle"></i> Suspend
                    </button>
                    <button class="btn-icon danger" data-action="archive-user" data-id="${user.id}">
                        <i class="fas fa-archive"></i> Archive
                    </button>
                `;
            }
        } else if (canManage && isMe) {
            // Current user can edit themselves but not deactivate/archive
            actionButtons = `
                <button class="btn-icon" data-action="edit-user" data-id="${user.id}">
                    <i class="fas fa-edit"></i> Edit
                </button>
            `;
        }
        
        return `
            <div class="user-card">
                <div class="user-card-header">
                    <div class="user-card-avatar">
                        ${user.username.charAt(0).toUpperCase()}
                    </div>
                    <div class="user-card-info">
                        <div class="user-card-name">
                            ${user.username}
                            ${isMe ? '<span class="badge-me">You</span>' : ''}
                        </div>
                        <div class="user-card-role ${user.role}">
                            <i class="fas ${roleIcon}"></i>
                            ${user.role}
                        </div>
                        ${statusBadge}
                    </div>
                </div>
                <div class="user-card-meta">
                    <i class="fas fa-calendar-alt"></i>
                    Joined ${formatDate(user.created_at)}
                </div>
                ${actionButtons ? `<div class="user-card-actions">${actionButtons}</div>` : ''}
            </div>
        `;
    }).join('');

    // Update pagination controls
    if (usersPagination) usersPagination.render();
    
    // Set up event listeners for card actions
    setupCardEventListeners();
}

function setupCardEventListeners() {
    const grid = document.getElementById('users-grid');
    if (!grid) return;
    
    // Use event delegation on the grid
    const buttons = grid.querySelectorAll('[data-action]');
    buttons.forEach(button => {
        const action = button.dataset.action;
        const id = button.dataset.id;
        
        if (action === 'edit-user') {
            button.addEventListener('click', () => openEditUserModal(id));
        } else if (action === 'activate-user') {
            button.addEventListener('click', () => activateUser(id));
        } else if (action === 'deactivate-user') {
            button.addEventListener('click', () => {
                showConfirmation(
                    'Suspend User',
                    'Are you sure you want to suspend this user? They will be unable to log in until reactivated.',
                    () => deactivateUser(id)
                );
            });
        } else if (action === 'archive-user') {
            button.addEventListener('click', () => {
                showConfirmation(
                    'Archive User',
                    'Are you sure you want to archive this user? They will be hidden and unable to log in.',
                    () => archiveUser(id)
                );
            });
        } else if (action === 'restore-user') {
            button.addEventListener('click', () => restoreUser(id));
        } else if (action === 'permanent-delete-user') {
            button.addEventListener('click', () => {
                showConfirmation(
                   'Permanently Delete User',
                    'Are you sure you want to PERMANENTLY delete this user? This action cannot be undone!',
                    () => permanentlyDeleteUser(id)
                );
            });
        }
    });
}

function canManageUser(requestingUser, targetRole) {
    if (!requestingUser) return false;
    if (requestingUser.role === 'superuser') return true;
    if (requestingUser.role === 'admin' && targetRole === 'user') return true;
    return false;
}

function openEditUserModal(id) {
    const user = usersState.allUsers.find(u => String(u.id) === String(id));
    if (!user) return;

    const roleSelect = document.getElementById('edit-user-role');
    
    // Remove any existing superuser option
    const existingSuperuserOption = roleSelect.querySelector('option[value="superuser"]');
    if (existingSuperuserOption) {
        existingSuperuserOption.remove();
    }
    
    document.getElementById('edit-user-id').value = user.id;
    document.getElementById('edit-user-username').value = user.username;
    document.getElementById('edit-user-password').value = ''; // Reset password field
    
    // Handle superuser role specially
    if (user.role === 'superuser') {
        // Add superuser option temporarily
        const superuserOption = document.createElement('option');
        superuserOption.value = 'superuser';
        superuserOption.textContent = 'Superuser';
        roleSelect.appendChild(superuserOption);
        
        // Set and disable the role field
        roleSelect.value = 'superuser';
        roleSelect.disabled = true;
    } else {
        // Enable role field for non-superusers
        roleSelect.disabled = false;
        roleSelect.value = user.role;
    }
    
    openModal(editUserModal);
}

async function handleSaveUser(e) {
    e.preventDefault();
    
    const id = document.getElementById('edit-user-id').value;
    const username = document.getElementById('edit-user-username').value;
    const roleSelect = document.getElementById('edit-user-role');
    const role = roleSelect.value;
    const password = document.getElementById('edit-user-password').value;
    
    // Find the user being edited
    const user = usersState.allUsers.find(u => String(u.id) === String(id));
    
    // Build update payload
    const updateData = { username };
    
    // Only include role if it's changeable (not disabled)
    if (!roleSelect.disabled) {
        updateData.role = role;
    }
    
    // Only include password if provided
    if (password) {
        updateData.password = password;
    }
    
    try {
        const response = await axios.put(`/admin/api/users/${id}`, updateData);
        const data = response.data;
        
        if (data.success) {
            closeModal(editUserModal);
            loadUsers();
            showToast('User updated successfully', 'success');
        } else {
            showToast('Failed to update user', 'error', data.error || 'Please try again.');
        }
    } catch (error) {
        console.error('Error updating user:', error);
        const errorMessage = error.response?.data?.error || 'An error occurred. Please try again.';
        showToast('Failed to update user', 'error', errorMessage);
    }
}

async function handleAddUser(e) {
    e.preventDefault();
    
    const username = document.getElementById('new-username').value;
    const password = document.getElementById('new-password').value;
    const role = document.getElementById('new-role').value;
    
    try {
        const response = await axios.post('/admin/api/users', { username, password, role });
        const data = response.data;
        
        if (data.success) {
            closeModal(addUserModal);
            addUserForm.reset();
            loadUsers();
            showToast('User created successfully', 'success');
        } else {
            showToast('Failed to create user', 'error', data.error || 'Please try again.');
        }
    } catch (error) {
        console.error('Error creating user:', error);
        const errorMessage = error.response?.data?.error || 'An error occurred. Please try again.';
        showToast('Failed to create user', 'error', errorMessage);
    }
}

// Activate user (set status to active)
async function activateUser(id) {
    try {
        const response = await axios.post(`/admin/api/users/${id}/activate`);
        const data = response.data;
        
        if (data.success) {
            loadUsers();
            showToast('User activated successfully', 'success');
        } else {
            showToast('Failed to activate user', 'error', data.error || 'Please try again.');
        }
    } catch (error) {
        console.error('Error activating user:', error);
        const errorMessage = error.response?.data?.error || 'An error occurred. Please try again.';
        showToast('Failed to activate user', 'error', errorMessage);
    }
}

// Deactivate user (set status to inactive)
async function deactivateUser(id) {
    try {
        const response = await axios.post(`/admin/api/users/${id}/deactivate`);
        const data = response.data;
        
        if (data.success) {
            loadUsers();
            showToast('User suspended successfully', 'success');
        } else {
            showToast('Failed to suspend user', 'error', data.error || 'Please try again.');
        }
    } catch (error) {
        console.error('Error suspending user:', error);
        const errorMessage = error.response?.data?.error || 'An error occurred. Please try again.';
        showToast('Failed to suspend user', 'error', errorMessage);
    }
}

// Archive user (soft delete)
async function archiveUser(id) {
    // Find the user being archived
    const user = usersState.allUsers.find(u => String(u.id) === String(id));
    
    // Prevent archiving superuser
    if (user && user.role === 'superuser') {
        showToast(
            'Cannot archive superuser',
            'error',
            'The superuser account cannot be archived.'
        );
        return;
    }
    
    try {
        const response = await axios.delete(`/admin/api/users/${id}`);
        const data = response.data;
        
        if (data.success) {
            loadUsers();
            showToast('User archived successfully', 'success');
        } else {
            showToast('Failed to archive user', 'error', data.error || 'Please try again.');
        }
    } catch (error) {
        console.error('Error archiving user:', error);
        const errorMessage = error.response?.data?.error || 'An error occurred. Please try again.';
        showToast('Failed to archive user', 'error', errorMessage);
    }
}

// Restore archived user
async function restoreUser(id) {
    try {
        const response = await axios.post(`/admin/api/users/${id}/restore`);
        const data = response.data;
        
        if (data.success) {
            loadUsers();
            showToast('User restored successfully', 'success');
        } else {
            showToast('Failed to restore user', 'error', data.error || 'Please try again.');
        }
    } catch (error) {
        console.error('Error restoring user:', error);
        const errorMessage = error.response?.data?.error || 'An error occurred. Please try again.';
        showToast('Failed to restore user', 'error', errorMessage);
    }
}

// Permanently delete user (hard delete)
async function permanentlyDeleteUser(id) {
    try {
        const response = await axios.delete(`/admin/api/users/${id}/permanent`);
        const data = response.data;
        
        if (data.success) {
            loadUsers();
            showToast('User permanently deleted', 'success');
        } else {
            showToast('Failed to delete user', 'error', data.error || 'Please try again.');
        }
    } catch (error) {
        console.error('Error permanently deleting user:', error);
        const errorMessage = error.response?.data?.error || 'An error occurred. Please try again.';
        showToast('Failed to delete user', 'error', errorMessage);
    }
}

function openModal(modal) {
    modal.style.display = 'flex';
}

function closeModal(modal) {
    modal.style.display = 'none';
}

async function handlePasswordUpdate(e) {
    e.preventDefault();
    
    const currentPassword = e.target.querySelector('input[type="password"]:nth-of-type(1)').value;
    const newPassword = e.target.querySelector('input[type="password"]:nth-of-type(2)').value;
    const confirmPassword = e.target.querySelector('input[type="password"]:nth-of-type(3)').value;
    
    if (newPassword !== confirmPassword) {
        showToast('Passwords do not match', 'warning', 'New passwords must match.');
        return;
    }
    
    try {
        const response = await axios.post('/admin/api/settings/password', {
            currentPassword,
            newPassword
        });
        
        const data = response.data;
        
        if (data.success) {
            showToast('Password updated successfully', 'success');
            e.target.reset();
        } else {
            showToast('Failed to update password', 'error', data.error || 'Please try again.');
        }
    } catch (error) {
        console.error('Error updating password:', error);
        showToast('Failed to update password', 'error');
    }
}

// Profile page functions
async function handleUpdateUsername(e) {
    e.preventDefault();
    
    const newUsername = document.getElementById('new-username').value;
    
    if (!newUsername || newUsername.trim().length < 3) {
        showToast('Username too short', 'warning', 'Username must be at least 3 characters long.');
        return;
    }
    
    try {
        const response = await axios.post('/admin/api/profile/username', {
            username: newUsername
        });
        
        const data = response.data;
        
        if (data.success) {
            showToast('Username updated successfully', 'info', 'Please login again with your new username.');
            window.location.href = '/admin/login';
        } else {
            showToast('Failed to update username', 'error', data.error || 'Please try again.');
        }
    } catch (error) {
        console.error('Error updating username:', error);
        showToast('Failed to update username', 'error', error.response?.data?.error || 'Please try again.');
    }
}

async function handleChangePassword(e) {
    e.preventDefault();
    
    const currentPassword = document.getElementById('current-password').value;
    const newPassword = document.getElementById('new-password').value;
    const confirmPassword = document.getElementById('confirm-password').value;
    
    if (newPassword !== confirmPassword) {
        showToast('Passwords do not match', 'warning', 'New passwords must match.');
        return;
    }
    
    if (newPassword.length < 6) {
        showToast('Password too short', 'warning', 'Password must be at least 6 characters long.');
        return;
    }
    
    try {
        const response = await axios.post('/admin/api/profile/password', {
            currentPassword,
            newPassword
        });
        
        const data = response.data;
        
        if (data.success) {
            showToast('Password changed successfully', 'success');
            e.target.reset();
        } else {
            showToast('Failed to change password', 'error', data.error || 'Please try again.');
        }
    } catch (error) {
        console.error('Error changing password:', error);
        showToast('Failed to change password', 'error', error.response?.data?.error || 'Please try again.');
    }
}

function showDashboard() {
    loginScreen.style.display = 'none';
    adminDashboard.style.display = 'grid';
}

function showError(message) {
    loginError.textContent = message;
    loginError.style.display = 'block';
}

// Load all dashboard data
async function loadDashboardData() {
    // Refresh data for the current section
    loadSectionData(currentSection);
}

// Load analytics overview
async function loadOverview() {
    try {
        const response = await axios.get('/admin/api/analytics/overview');
        const data = response.data;

        // Update metrics with animation
        animateValue(document.getElementById('metric-today-visitors'), data.today.visitors);
        animateValue(document.getElementById('metric-today-unique'), data.today.uniqueUsers);
        animateValue(document.getElementById('metric-total-visitors'), data.allTime.totalVisitors);
        
        // Format playtime
        const hours = Math.floor(data.allTime.totalPlaytime / 3600);
        const totalPlaytimeElement = document.getElementById('metric-total-playtime');
        if (totalPlaytimeElement) {
            totalPlaytimeElement.textContent = `${hours}h`;
        }
    } catch (error) {
        console.error('Failed to load overview:', error);
    }
}

// Load traffic chart
async function loadTrafficChart() {
    const ctx = document.getElementById('traffic-chart');
    if (!ctx) return; // Null check

    try {
        const response = await axios.get(`/admin/api/analytics/traffic?range=${currentRange}`);
        const data = response.data;

        if (trafficChart) {
            trafficChart.destroy();
        }

        trafficChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: data.map(d => formatDate(d.date)),
                datasets: [
                    {
                        label: 'Visitors',
                        data: data.map(d => d.visitors),
                        borderColor: 'rgb(99, 102, 241)',
                        backgroundColor: 'rgba(99, 102, 241, 0.1)',
                        tension: 0.4,
                        fill: true
                    },
                    {
                        label: 'Unique Users',
                        data: data.map(d => d.uniqueUsers),
                        borderColor: 'rgb(139, 92, 246)',
                        backgroundColor: 'rgba(139, 92, 246, 0.1)',
                        tension: 0.4,
                        fill: true
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: {
                        labels: {
                            color: 'rgba(255, 255, 255, 0.8)'
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            color: 'rgba(255, 255, 255, 0.6)'
                        },
                        grid: {
                            color: 'rgba(255, 255, 255, 0.1)'
                        }
                    },
                    x: {
                        ticks: {
                            color: 'rgba(255, 255, 255, 0.6)'
                        },
                        grid: {
                            color: 'rgba(255, 255, 255, 0.1)'
                        }
                    }
                }
            }
        });
    } catch (error) {
        console.error('Failed to load traffic chart:', error);
    }
}

// Load games comparison chart
async function loadGamesChart() {
    const ctx = document.getElementById('games-chart');
    if (!ctx) return; // Null check

    try {
        const response = await axios.get('/admin/api/analytics/games');
        const data = response.data;
        
        if (gamesChart) {
            gamesChart.destroy();
        }
        
        gamesChart = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: data.labels,
                datasets: [{
                    data: data.plays,
                    backgroundColor: [
                        '#6366f1', '#ec4899', '#10b981', '#f59e0b', '#8b5cf6', '#ef4444'
                    ],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'right',
                        labels: { color: '#a0aec0' }
                    }
                }
            }
        });
    } catch (error) {
        console.error('Failed to load games chart:', error);
    }
}

// Load game comparison data
async function loadGameComparison() {
    try {
        const response = await axios.get('/admin/api/analytics/game-comparison');
        const data = response.data;
        comparisonData = data;
        
        // Initial render with default metric
        renderComparisonChart('totalSessions');
    } catch (error) {
        console.error('Error loading game comparison:', error);
    }
}

// Render comparison chart
function renderComparisonChart(metric) {
    if (!comparisonData || comparisonData.length === 0) {
        return;
    }

    const ctx = document.getElementById('game-comparison-chart');
    if (!ctx) return;

    // Destroy existing chart
    if (comparisonChart) {
        comparisonChart.destroy();
    }

    const metricLabels = {
        totalSessions: 'Total Sessions',
        uniquePlayers: 'Unique Players',
        totalPlaytime: 'Total Playtime (minutes)',
        avgSessionDuration: 'Avg Session Duration (minutes)',
        activeDays: 'Active Days'
    };

    // Sort data by selected metric
    const sortedData = [...comparisonData].sort((a, b) => b[metric] - a[metric]);

    comparisonChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: sortedData.map(d => d.gameName),
            datasets: [{
                label: metricLabels[metric],
                data: sortedData.map(d => d[metric]),
                backgroundColor: [
                    'rgba(99, 102, 241, 0.8)',
                    'rgba(139, 92, 246, 0.8)',
                    'rgba(236, 72, 153, 0.8)',
                    'rgba(245, 158, 11, 0.8)',
                    'rgba(16, 185, 129, 0.8)',
                    'rgba(59, 130, 246, 0.8)',
                    'rgba(239, 68, 68, 0.8)'
                ],
                borderColor: [
                    'rgba(99, 102, 241, 1)',
                    'rgba(139, 92, 246, 1)',
                    'rgba(236, 72, 153, 1)',
                    'rgba(245, 158, 11, 1)',
                    'rgba(16, 185, 129, 1)',
                    'rgba(59, 130, 246, 1)',
                    'rgba(239, 68, 68, 1)'
                ],
                borderWidth: 1,
                borderRadius: 8
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return `${metricLabels[metric]}: ${context.parsed.y}`;
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        precision: 0,
                        color: 'rgba(255, 255, 255, 0.6)'
                    },
                    grid: {
                        color: 'rgba(255, 255, 255, 0.1)'
                    }
                },
                x: {
                    ticks: {
                        color: 'rgba(255, 255, 255, 0.6)'
                    },
                    grid: {
                        display: false
                    }
                }
            }
        }
    });
}

// Load device analytics
async function loadDeviceAnalytics() {
    try {
        const response = await axios.get('/admin/api/analytics/devices');
        const data = response.data;
        
        renderDeviceTypeChart(data.devices);
        renderOSChart(data.os);
        renderBrowserChart(data.browsers);
    } catch (error) {
        console.error('Error loading device analytics:', error);
    }
}

function renderDeviceTypeChart(data) {
    const ctx = document.getElementById('device-type-chart');
    if (!ctx || !data || data.length === 0) return;

    if (deviceTypeChart) {
        deviceTypeChart.destroy();
    }

    const colors = {
        mobile: 'rgba(236, 72, 153, 0.8)',
        tablet: 'rgba(139, 92, 246, 0.8)',
        desktop: 'rgba(99, 102, 241, 0.8)',
        unknown: 'rgba(156, 163, 175, 0.8)'
    };

    deviceTypeChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: data.map(d => d.device_type.charAt(0).toUpperCase() + d.device_type.slice(1)),
            datasets: [{
                data: data.map(d => d.count),
                backgroundColor: data.map(d => colors[d.device_type] || colors.unknown),
                borderWidth: 2,
                borderColor: 'rgba(10, 14, 26, 1)'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        color: 'rgba(255, 255, 255, 0.8)',
                        padding: 15
                    }
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                            const percentage = ((context.parsed / total) * 100).toFixed(1);
                            return `${context.label}: ${context.parsed} (${percentage}%)`;
                        }
                    }
                }
            }
        }
    });
}

function renderOSChart(data) {
    const ctx = document.getElementById('os-chart');
    if (!ctx || !data || data.length === 0) return;

    if (osChart) {
        osChart.destroy();
    }

    const colors = {
        android: 'rgba(164, 198, 57, 0.8)',
        ios: 'rgba(0, 122, 255, 0.8)',
        windows: 'rgba(0, 120, 215, 0.8)',
        macos: 'rgba(128, 128, 128, 0.8)',
        linux: 'rgba(255, 190, 0, 0.8)',
        chromeos: 'rgba(66, 133, 244, 0.8)',
        other: 'rgba(156, 163, 175, 0.8)'
    };

    osChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: data.map(d => {
                const label = d.os.charAt(0).toUpperCase() + d.os.slice(1);
                return label === 'Macos' ? 'macOS' : (label === 'Ios' ? 'iOS' : label);
            }),
            datasets: [{
                data: data.map(d => d.count),
                backgroundColor: data.map(d => colors[d.os] || colors.other),
                borderWidth: 2,
                borderColor: 'rgba(10, 14, 26, 1)'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        color: 'rgba(255, 255, 255, 0.8)',
                        padding: 15
                    }
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                            const percentage = ((context.parsed / total) * 100).toFixed(1);
                            return `${context.label}: ${context.parsed} (${percentage}%)`;
                        }
                    }
                }
            }
        }
    });
}

function renderBrowserChart(data) {
    const ctx = document.getElementById('browser-chart');
    if (!ctx || !data || data.length === 0) return;

    if (browserChart) {
        browserChart.destroy();
    }

    const colors = {
        chrome: 'rgba(66, 133, 244, 0.8)',
        firefox: 'rgba(255, 95, 0, 0.8)',
        safari: 'rgba(0, 122, 255, 0.8)',
        edge: 'rgba(0, 120, 215, 0.8)',
        opera: 'rgba(255, 28, 47, 0.8)',
        other: 'rgba(156, 163, 175, 0.8)'
    };

    browserChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: data.map(d => d.browser.charAt(0).toUpperCase() + d.browser.slice(1)),
            datasets: [{
                data: data.map(d => d.count),
                backgroundColor: data.map(d => colors[d.browser] || colors.other),
                borderWidth: 2,
                borderColor: 'rgba(10, 14, 26, 1)'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        color: 'rgba(255, 255, 255, 0.8)',
                        padding: 15
                    }
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                            const percentage = ((context.parsed / total) * 100).toFixed(1);
                            return `${context.label}: ${context.parsed} (${percentage}%)`;
                        }
                    }
                }
            }
        }
    });
}

// Games State
const gamesState = {
    allGames: [],
    filteredGames: [],
    searchQuery: '',
    categoryFilter: 'all',
    statusFilter: 'all'
};

// Load games
async function loadGames() {
    try {
        const response = await axios.get('/admin/api/games');
        const games = response.data;
        gamesState.allGames = games;
        filterGames();
        renderGameStats(games);
    } catch (error) {
        console.error('Failed to load games:', error);
    }
}

function renderGameStats(games) {
    const total = games.length;
    const active = games.filter(g => g.enabled).length;
    const inactive = games.filter(g => !g.enabled).length;
    const featured = games.filter(g => g.featured).length;

    const totalEl = document.getElementById('stat-total-games');
    const activeEl = document.getElementById('stat-active-games');
    const inactiveEl = document.getElementById('stat-inactive-games');
    const featuredEl = document.getElementById('stat-featured-games');

    if (totalEl) totalEl.textContent = total;
    if (activeEl) activeEl.textContent = active;
    if (inactiveEl) inactiveEl.textContent = inactive;
    if (featuredEl) featuredEl.textContent = featured;
}

function filterGames() {
    let filtered = gamesState.allGames;

    // Apply category filter
    if (gamesState.categoryFilter !== 'all') {
        filtered = filtered.filter(game => game.category === gamesState.categoryFilter);
    }

    // Apply status filter
    if (gamesState.statusFilter === 'active') {
        filtered = filtered.filter(game => game.enabled);
    } else if (gamesState.statusFilter === 'inactive') {
        filtered = filtered.filter(game => !game.enabled);
    }

    // Apply search filter
    if (gamesState.searchQuery) {
        filtered = filtered.filter(game =>
            game.name.toLowerCase().includes(gamesState.searchQuery) ||
            game.category.toLowerCase().includes(gamesState.searchQuery)
        );
    }

    gamesState.filteredGames = filtered;
    renderGames(filtered);
}

// Render games grid
function renderGames(games) {
    const gamesGrid = document.getElementById('games-grid');
    const emptyState = document.getElementById('games-empty-state');
    
    if (!gamesGrid) return;

    // Show empty state if no games
    if (games.length === 0) {
        gamesGrid.style.display = 'none';
        if (emptyState) emptyState.style.display = 'block';
        return;
    } else {
        gamesGrid.style.display = 'grid';
        if (emptyState) emptyState.style.display = 'none';
    }
    
    gamesGrid.innerHTML = games.map(game => {
        const categoryIcon = {
            strategy: 'fa-chess',
            arcade: 'fa-rocket',
            puzzle: 'fa-puzzle-piece',
            board: 'fa-dice'
        }[game.category] || 'fa-gamepad';

        return `
            <div class="game-card">
                <div class="game-card-header">
                    <div class="game-icon-display">
                        ${game.icon}
                    </div>
                    <div class="game-card-info">
                        <div class="game-card-title">
                            ${game.name}
                            ${game.featured ? '<span class="game-badge featured"><i class="fas fa-star"></i> Featured</span>' : ''}
                        </div>
                        <div style="display: flex; gap: 0.5rem; flex-wrap: wrap;">
                            <span class="game-category-badge ${game.category}">
                                <i class="fas ${categoryIcon}"></i>
                                ${game.category}
                            </span>
                            <span class="game-badge status-${game.enabled ? 'active' : 'inactive'}">
                                ${game.enabled ? 'Active' : 'Inactive'}
                            </span>
                            ${game.maintenanceMode ? '<span class="game-badge status-maintenance"><i class="fas fa-tools"></i> Maintenance</span>' : ''}
                        </div>
                    </div>
                </div>
                <p class="game-card-description">${game.description}</p>
                <div class="game-card-meta">
                    <div class="game-meta-item">
                        <i class="fas fa-users"></i>
                        ${game.players}
                    </div>
                    <div class="game-meta-item">
                        <i class="fas fa-clock"></i>
                        ${game.estimatedTime}
                    </div>
                </div>
                <div class="game-card-actions">
                    <button class="btn-toggle ${game.enabled ? 'active' : ''}" 
                            data-action="toggle" 
                            data-id="${game.id}" 
                            data-enabled="${game.enabled}">
                        <i class="fas fa-toggle-${game.enabled ? 'on' : 'off'}"></i>
                        ${game.enabled ? 'Disable' : 'Enable'}
                    </button>
                    <button class="btn-edit" 
                            data-action="edit" 
                            data-id="${game.id}">
                        <i class="fas fa-edit"></i>
                        Edit
                    </button>
                    <button class="btn-maintenance" 
                            data-action="maintenance" 
                            data-id="${game.id}"
                            style="background: rgba(99, 102, 241, 0.1); color: #818cf8; border: 1px solid rgba(99, 102, 241, 0.2);">
                        <i class="fas fa-tools"></i>
                    </button>
                </div>
            </div>
        `;
    }).join('');
    
    // Setup event listeners for the new buttons
    setupGameCardListeners();
}

function setupGameCardListeners() {
    document.querySelectorAll('.btn-toggle').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const gameId = e.currentTarget.dataset.id;
            const enabled = e.currentTarget.dataset.enabled === 'true';
            
            showConfirmation(
                `${enabled ? 'Disable' : 'Enable'} Game`,
                `Are you sure you want to ${enabled ? 'disable' : 'enable'} this game?`,
                () => toggleGame(gameId, enabled)
            );
        });
    });

    document.querySelectorAll('.btn-edit').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const gameId = e.currentTarget.dataset.id;
            editGame(gameId);
        });
    });
    
    document.querySelectorAll('.btn-maintenance').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const gameId = e.currentTarget.dataset.id;
            openMaintenanceModal(gameId);
        });
    });
}

async function openMaintenanceModal(gameId) {
    try {
        const response = await axios.get(`/admin/api/games/${gameId}`);
        const game = response.data;
        
        if (!game) return;
        
        document.getElementById('maintenance-game-id').value = game.id;
        document.getElementById('maintenance-enabled').checked = game.maintenanceMode;
        document.getElementById('maintenance-message-input').value = game.maintenanceMessage || '';
        
        if (game.maintenanceEta) {
            const date = new Date(game.maintenanceEta);
            const localDateTime = new Date(date.getTime() - date.getTimezoneOffset() * 60000)
                .toISOString()
                .slice(0, 16);
            document.getElementById('maintenance-eta-input').value = localDateTime;
        } else {
            document.getElementById('maintenance-eta-input').value = '';
        }
        
        openModal(document.getElementById('maintenance-modal'));
    } catch (error) {
        console.error('Error opening maintenance modal:', error);
        showToast('Failed to load game details', 'error');
    }
}

async function saveMaintenanceSettings() {
    const gameId = document.getElementById('maintenance-game-id').value;
    const maintenanceMode = document.getElementById('maintenance-enabled').checked;
    const message = document.getElementById('maintenance-message-input').value;
    const etaInput = document.getElementById('maintenance-eta-input').value;
    const eta = etaInput ? new Date(etaInput).toISOString() : '';
    
    try {
        const response = await axios.post(`/admin/api/games/${gameId}/maintenance`, {
            maintenanceMode,
            message,
            eta
        });
        
        if (response.data.success) {
            showToast('Maintenance settings saved', 'success');
            closeModal(document.getElementById('maintenance-modal'));
            loadGames();
        }
    } catch (error) {
        console.error('Error saving maintenance settings:', error);
        showToast('Failed to save settings', 'error');
    }
}

// Toggle game enabled status
async function toggleGame(gameId, currentStatus) {
    try {
        const response = await axios.post(`/admin/api/games/${gameId}/toggle`, { enabled: !currentStatus });
        const data = response.data;

        if (data.success) {
            const action = !currentStatus ? 'enabled' : 'disabled';
            showToast(`Game ${action} successfully!`, 'success');
            loadGames(); // Reload games to update UI
        } else {
            showToast('Failed to toggle game', 'error', 'Please try again.');
        }
    } catch (error) {
        console.error('Failed to toggle game:', error);
        showToast('Failed to toggle game', 'error', 'Please try again.');
    }
}

// Edit game
async function editGame(gameId) {
    try {
        const response = await axios.get(`/admin/api/games/${gameId}`);
        const game = response.data;

        if (!game) return;

        // Populate form
        document.getElementById('edit-game-id').value = game.id;
        document.getElementById('edit-name').value = game.name;
        document.getElementById('edit-description').value = game.description;
        document.getElementById('edit-icon').value = game.icon;
        document.getElementById('edit-players').value = game.players;
        document.getElementById('edit-time').value = game.estimatedTime;
        document.getElementById('edit-category').value = game.category || 'strategy';
        document.getElementById('edit-featured').checked = game.featured || false;

        editModal.style.display = 'flex';
    } catch (error) {
        console.error('Failed to load game for editing:', error);
    }
}

// Handle edit save
async function handleEditSave(e) {
    e.preventDefault();

    const gameId = document.getElementById('edit-game-id').value;
    const updates = {
        name: document.getElementById('edit-name').value,
        description: document.getElementById('edit-description').value,
        icon: document.getElementById('edit-icon').value,
        players: document.getElementById('edit-players').value,
        estimatedTime: document.getElementById('edit-time').value,
        category: document.getElementById('edit-category').value,
        featured: document.getElementById('edit-featured').checked
    };

    try {
        const response = await axios.put(`/admin/api/games/${gameId}`, updates);
        const data = response.data;

        if (data.success) {
            showToast('Game updated successfully!', 'success');
            closeEditModal();
            loadGames();
        } else {
            showToast('Failed to update game', 'error', 'Please try again.');
        }
    } catch (error) {
        console.error('Failed to save game edits:', error);
        showToast('Failed to save changes', 'error', 'Please try again.');
    }
}

// Close edit modal
function closeEditModal() {
    editModal.style.display = 'none';
}

// Utility functions
function animateValue(element, value) {
    if (!element) return;
    const start = parseInt(element.textContent) || 0;
    const end = value;
    const duration = 1000;
    const increment = (end - start) / (duration / 16);

    let current = start;
    const timer = setInterval(() => {
        current += increment;
        if ((increment > 0 && current >= end) || (increment < 0 && current <= end)) {
            current = end;
            clearInterval(timer);
        }
        element.textContent = Math.floor(current);
    }, 16);
}

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

function formatDuration(seconds) {
    if (seconds < 60) return `${Math.floor(seconds)}s`;
    const minutes = Math.floor(seconds / 60);
    return `${minutes}m`;
}

function formatPlaytime(seconds) {
    if (seconds < 60) return `${Math.floor(seconds)}s`;
    if (seconds < 3600) {
        const minutes = Math.floor(seconds / 60);
        return `${minutes}m`;
    }
    const hours = Math.floor(seconds / 3600);
    return `${hours}h`;
}

// ========================================
// Settings Management
// ========================================

async function loadSettings() {
    try {
        const response = await axios.get('/admin/api/settings');
        const { settings } = response.data;
        
        // Update toggle switches
        if (settings.maintenance_mode !== undefined) {
            document.getElementById('maintenance-mode').checked = settings.maintenance_mode === 'true';
        }
        if (settings.debug_logging !== undefined) {
            document.getElementById('debug-logging').checked = settings.debug_logging === 'true';
        }
        if (settings.analytics_tracking !== undefined) {
            document.getElementById('analytics-tracking').checked = settings.analytics_tracking === 'true';
        }
        
        // Update form inputs
        if (settings.portal_title !== undefined) {
            document.getElementById('portal-title').value = settings.portal_title;
        }
        if (settings.max_games_displayed !== undefined) {
            document.getElementById('max-games').value = settings.max_games_displayed;
        }
        
        // Update maintenance settings
        if (settings.maintenance_message !== undefined) {
            document.getElementById('maintenance-message').value = settings.maintenance_message;
        }
        if (settings.maintenance_eta !== undefined && settings.maintenance_eta) {
            // Convert ISO string to datetime-local format
            const date = new Date(settings.maintenance_eta);
            const localDateTime = new Date(date.getTime() - date.getTimezoneOffset() * 60000)
                .toISOString()
                .slice(0, 16);
            document.getElementById('maintenance-eta').value = localDateTime;
        }
    } catch (error) {
        console.error('Error loading settings:', error);
        showToast('Failed to load settings', 'error');
    }
}

async function updateSetting(key, value, silent = false) {
    try {
        const response = await axios.post('/admin/api/settings', { key, value });
        
        if (response.data.success) {
            if (!silent) {
                showToast('Setting updated successfully', 'success');
            }
            return true;
        }
    } catch (error) {
        console.error('Error updating setting:', error);
        if (!silent) {
            showToast('Failed to update setting', 'error');
        }
        return false;
    }
}

// Settings event listeners
function setupSettingsListeners() {
    // Toggle switches
    const maintenanceToggle = document.getElementById('maintenance-mode');
    const debugToggle = document.getElementById('debug-logging');
    const analyticsToggle = document.getElementById('analytics-tracking');
    
    if (maintenanceToggle) {
        maintenanceToggle.addEventListener('change', async (e) => {
            const value = e.target.checked ? 'true' : 'false';
            const success = await updateSetting('maintenance_mode', value);
            if (!success) {
                e.target.checked = !e.target.checked; // Revert on failure
            }
        });
    }
    
    if (debugToggle) {
        debugToggle.addEventListener('change', async (e) => {
            const value = e.target.checked ? 'true' : 'false';
            await updateSetting('debug_logging', value);
        });
    }
    
    if (analyticsToggle) {
        analyticsToggle.addEventListener('change', async (e) => {
            const value = e.target.checked ? 'true' : 'false';
            await updateSetting('analytics_tracking', value);
        });
    }
    
    // Settings form
    const settingsForm = document.querySelector('.settings-form');
    if (settingsForm) {
        settingsForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const portalTitle = document.getElementById('portal-title').value;
            const maxGames = document.getElementById('max-games').value;
            
            await updateSetting('portal_title', portalTitle);
            await updateSetting('max_games_displayed', maxGames);
        });
    }
    
    // Maintenance form
    const maintenanceForm = document.querySelector('.maintenance-form');
    if (maintenanceForm) {
        maintenanceForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const message = document.getElementById('maintenance-message').value;
            const etaInput = document.getElementById('maintenance-eta').value;
            
            // Convert datetime-local to ISO string if provided
            const eta = etaInput ? new Date(etaInput).toISOString() : '';
            
            // Update both settings silently
            const success1 = await updateSetting('maintenance_message', message, true);
            const success2 = await updateSetting('maintenance_eta', eta, true);
            
            // Show single toast for the overall result
            if (success1 && success2) {
                showToast('Maintenance settings saved successfully', 'success');
            } else {
                showToast('Failed to save maintenance settings', 'error');
            }
        });
    }
}

// Initialize settings listeners when DOM is ready
if (document.querySelector('.settings-container')) {
    setupSettingsListeners();
}

// ========================================
// Reusable Pagination Module
// ========================================

class TablePagination {
    constructor(config) {
        this.state = config.state;
        this.itemsKey = config.itemsKey;
        this.renderCallback = config.renderCallback;
        this.idPrefix = config.idPrefix;
        this.itemsPerPage = config.itemsPerPage || 25;
        this.currentPage = 1;
        
        this.init();
    }
    
    init() {
        this.setupEventListeners();
    }
    
    setupEventListeners() {
        const prevBtn = document.getElementById(`${this.idPrefix}-prev-page`);
        const nextBtn = document.getElementById(`${this.idPrefix}-next-page`);
        const pageSizeSelect = document.getElementById(`${this.idPrefix}-page-size`);
        
        if (prevBtn) {
            prevBtn.addEventListener('click', () => this.changePage(this.currentPage - 1));
        }
        if (nextBtn) {
            nextBtn.addEventListener('click', () => this.changePage(this.currentPage + 1));
        }
        if (pageSizeSelect) {
            pageSizeSelect.addEventListener('change', (e) => this.changePageSize(e.target.value));
        }
    }
    
    changePage(newPage) {
        const totalPages = this.getTotalPages();
        if (newPage < 1 || newPage > totalPages) return;
        
        this.currentPage = newPage;
        this.renderCallback();
    }
    
    changePageSize(newSize) {
        this.itemsPerPage = parseInt(newSize);
        this.currentPage = 1;
        this.renderCallback();
    }
    
    resetToFirstPage() {
        this.currentPage = 1;
    }
    
    getTotalItems() {
        return this.state[this.itemsKey]?.length || 0;
    }
    
    getTotalPages() {
        return Math.ceil(this.getTotalItems() / this.itemsPerPage);
    }
    
    getPaginatedItems() {
        const start = (this.currentPage - 1) * this.itemsPerPage;
        const end = start + this.itemsPerPage;
        return this.state[this.itemsKey]?.slice(start, end) || [];
    }
    
    render() {
        const totalItems = this.getTotalItems();
        const totalPages = this.getTotalPages();
        const start = totalItems === 0 ? 0 : (this.currentPage - 1) * this.itemsPerPage + 1;
        const end = Math.min(start + this.itemsPerPage - 1, totalItems);
        
        // Update page info
        const pageInfo = document.getElementById(`${this.idPrefix}-page-info`);
        if (pageInfo) {
            pageInfo.textContent = `Showing ${start}-${end} of ${totalItems} items`;
        }
        
        // Update buttons
        const prevBtn = document.getElementById(`${this.idPrefix}-prev-page`);
        const nextBtn = document.getElementById(`${this.idPrefix}-next-page`);
        const paginationControls = document.getElementById(`${this.idPrefix}-pagination`);
        
        if (prevBtn) prevBtn.disabled = this.currentPage === 1 || totalPages === 0;
        if (nextBtn) nextBtn.disabled = this.currentPage === totalPages || totalPages === 0;
        
        // Show/hide pagination
        if (paginationControls) {
            paginationControls.style.display = totalItems > 0 ? 'flex' : 'none';
        }
        
        // Render page numbers
        this.renderPageNumbers(totalPages);
    }
    
    renderPageNumbers(totalPages) {
        const pageNumbersContainer = document.getElementById(`${this.idPrefix}-page-numbers`);
        if (!pageNumbersContainer) return;
        
        pageNumbersContainer.innerHTML = '';
        
        if (totalPages <= 1) return;
        
        let startPage = Math.max(1, this.currentPage - 2);
        let endPage = Math.min(totalPages, startPage + 4);
        
        if (endPage - startPage < 4) {
            startPage = Math.max(1, endPage - 4);
        }
        
        for (let i = startPage; i <= endPage; i++) {
            const pageBtn = document.createElement('button');
            pageBtn.className = `btn-sm ${i === this.currentPage ? 'btn-primary' : 'btn-secondary'}`;
            pageBtn.textContent = i;
            pageBtn.onclick = () => this.changePage(i);
            pageBtn.style.margin = '0 0.25rem';
            pageNumbersContainer.appendChild(pageBtn);
        }
    }
}

// ========================================
// Room Management
// ========================================

const roomsState = {
    allRooms: [],
    filteredRooms: [],
    roomCapableGames: [],
    activeGameFilter: 'all',
    searchQuery: '',
    typeFilter: '',
    statusFilter: ''
};

// Initialize rooms pagination
let roomsPagination = null;

// Room management elements
const addRoomModal = document.getElementById('add-room-modal');
const editRoomModal = document.getElementById('edit-room-modal');
const addRoomForm = document.getElementById('add-room-form');
const editRoomForm = document.getElementById('edit-room-form');

if (document.getElementById('rooms-section')) {
    // Ensure modals are closed on page load
    if (addRoomModal) addRoomModal.style.display = 'none';
    if (editRoomModal) editRoomModal.style.display = 'none';
    
    // Load room-capable games for dropdown and tabs
    loadRoomCapableGames();
    
    // Load rooms on page load
    loadRooms();
    
    // Event listeners for room management
    const btnAddRoom = document.getElementById('btn-add-room');
    const closeAddRoom = document.getElementById('close-add-room');
    const cancelAddRoom = document.getElementById('cancel-add-room');
    const closeEditRoom = document.getElementById('close-edit-room');
    const cancelEditRoom = document.getElementById('cancel-edit-room');
    
    if (btnAddRoom) btnAddRoom.addEventListener('click', () => openModal(addRoomModal));
    if (closeAddRoom) closeAddRoom.addEventListener('click', () => closeModal(addRoomModal));
    if (cancelAddRoom) cancelAddRoom.addEventListener('click', () => closeModal(addRoomModal));
    if (closeEditRoom) closeEditRoom.addEventListener('click', () => closeModal(editRoomModal));
    if (cancelEditRoom) cancelEditRoom.addEventListener('click', () => closeModal(editRoomModal));
    if (addRoomForm) addRoomForm.addEventListener('submit', handleAddRoom);
    if (editRoomForm) editRoomForm.addEventListener('submit', handleSaveRoom);
    
    // Search and filter event listeners
    const searchInput = document.getElementById('room-search');
    const typeFilterSelect = document.getElementById('filter-room-type');
    const statusFilterSelect = document.getElementById('filter-room-status');
    
    if (searchInput) {
        searchInput.addEventListener('input', (e) => {
            roomsState.searchQuery = e.target.value.toLowerCase();
            applyFilters();
        });
    }
    
    if (typeFilterSelect) {
        typeFilterSelect.addEventListener('change', (e) => {
            roomsState.typeFilter = e.target.value;
            applyFilters();
        });
    }
    
    if (statusFilterSelect) {
        statusFilterSelect.addEventListener('change', (e) => {
            roomsState.statusFilter = e.target.value;
            applyFilters();
        });
    }
    
    // Initialize pagination
    roomsPagination = new TablePagination({
        state: roomsState,
        itemsKey: 'filteredRooms',
        renderCallback: renderRoomsTable,
        idPrefix: 'rooms',
        itemsPerPage: 25
    });
}

async function loadRoomCapableGames() {
    try {
        const response = await axios.get('/admin/api/games/room-capable');
        const games = response.data;
        roomsState.roomCapableGames = games;
        
        // Populate game type dropdown in add modal
        const gameSelect = document.getElementById('new-game-type');
        if (gameSelect) {
            gameSelect.innerHTML = '<option value="">Select Game...</option>';
            games.forEach(game => {
                const option = document.createElement('option');
                option.value = game.id;
                option.textContent = game.name;
                gameSelect.appendChild(option);
            });
        }
        
        // Create filter tabs
        createGameFilterTabs(games);
    } catch (error) {
        console.error('Error loading room-capable games:', error);
        showToast('Failed to load games', 'error');
    }
}

function createGameFilterTabs(games) {
    const tabsContainer = document.getElementById('game-filter-tabs');
    if (!tabsContainer) return;
    
    // Keep the "All Games" tab
    const allTab = tabsContainer.querySelector('[data-game="all"]');
    if (allTab) {
        allTab.addEventListener('click', () => setGameFilter('all'));
    }
    
    // Add game-specific tabs
    games.forEach(game => {
        const tab = document.createElement('button');
        tab.className = 'filter-tab';
        tab.setAttribute('data-game', game.id);
        tab.innerHTML = `
            <i class="fas fa-${getGameIcon(game.id)}"></i>
            <span>${game.name}</span>
            <span class="filter-badge" id="badge-${game.id}">0</span>
        `;
        tab.addEventListener('click', () => setGameFilter(game.id));
        tabsContainer.appendChild(tab);
    });
}

function getGameIcon(gameId) {
    const icons = {
        'chess': 'chess',
        'bagh-chal': 'crow',
        'ludo': 'dice'
    };
    return icons[gameId] || 'gamepad';
}

function setGameFilter(gameId) {
    roomsState.activeGameFilter = gameId;
    
    // Update active tab
    const tabs = document.querySelectorAll('.filter-tab');
    tabs.forEach(tab => {
        if (tab.getAttribute('data-game') === gameId) {
            tab.classList.add('active');
        } else {
            tab.classList.remove('active');
        }
    });
    
    applyFilters();
}

function applyFilters() {
    let filtered = [...roomsState.allRooms];
    
    // Game filter
    if (roomsState.activeGameFilter !== 'all') {
        filtered = filtered.filter(room => room.game_type === roomsState.activeGameFilter);
    }
    
    // Search filter
    if (roomsState.searchQuery) {
        filtered = filtered.filter(room => 
            room.name.toLowerCase().includes(roomsState.searchQuery)
        );
    }
    
    // Type filter
    if (roomsState.typeFilter) {
        filtered = filtered.filter(room => room.type === roomsState.typeFilter);
    }
    
    // Status filter
    if (roomsState.statusFilter) {
        filtered = filtered.filter(room => room.status === roomsState.statusFilter);
    }
    
    roomsState.filteredRooms = filtered;
    if (roomsPagination) roomsPagination.resetToFirstPage();
    renderRoomsTable();
    updateRoomStats();
}

async function loadRooms() {
    try {
        showLoading(true);
        const response = await axios.get('/admin/api/rooms');
        roomsState.allRooms = response.data;
        roomsState.filteredRooms = response.data;
        
        renderRoomsTable();
        updateRoomStats();
        showLoading(false);
    } catch (error) {
        console.error('Error loading rooms:', error);
        showToast('Failed to load rooms', 'error');
        showLoading(false);
    }
}

function showLoading(show) {
    const loading = document.getElementById('rooms-loading');
    const table = document.getElementById('rooms-table');
    const emptyState = document.getElementById('rooms-empty-state');
    
    if (loading) loading.style.display = show ? 'flex' : 'none';
    if (table) table.style.display = show ? 'none' : 'table';
    if (emptyState) emptyState.style.display = 'none';
}

function renderRoomsTable() {
    const tbody = document.getElementById('rooms-table-body');
    const table = document.getElementById('rooms-table');
    const emptyState = document.getElementById('rooms-empty-state');
    
    if (!tbody) return;
    
    tbody.innerHTML = '';
    
    if (roomsState.filteredRooms.length === 0) {
        if (table) table.style.display = 'none';
        if (emptyState) emptyState.style.display = 'block';
        return;
    }
    
    if (table) table.style.display = 'table';
    if (emptyState) emptyState.style.display = 'none';
    
    // Get paginated rooms from pagination instance
    const paginatedRooms = roomsPagination ? roomsPagination.getPaginatedItems() : roomsState.filteredRooms;
    
    // Render only the paginated rooms
    paginatedRooms.forEach(room => {
        const row = document.createElement('tr');
        
        const gameTypeDisplay = {
            'chess': 'Chess',
            'bagh-chal': 'Bagh Chal',
            'ludo': 'Ludo'
        }[room.game_type] || room.game_type;
        
        row.innerHTML = `
            <td>${room.id}</td>
            <td><span class="badge badge-${room.game_type}">${gameTypeDisplay}</span></td>
            <td>${room.name}</td>
            <td><span class="badge badge-${room.type}">${room.type.charAt(0).toUpperCase() + room.type.slice(1)}</span></td>
            <td>${room.password ? '🔒 Protected' : '🔓 None'}</td>
            <td><span class="badge badge-status-${room.status}">${room.status.charAt(0).toUpperCase() + room.status.slice(1)}</span></td>
            <td class="action-buttons">
                ${room.status !== 'archived' ? `
                    <button class="btn-icon btn-edit" onclick="openEditRoomModal(${room.id})" title="Edit">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="btn-icon btn-delete" onclick="confirmArchiveRoom(${room.id}, '${room.name}')" title="Archive">
                        <i class="fas fa-archive"></i>
                    </button>
                ` : `
                    <button class="btn-icon btn-success" onclick="restoreRoom(${room.id})" title="Restore">
                        <i class="fas fa-undo"></i>
                    </button>
                    <button class="btn-icon btn-delete" onclick="confirmPermanentDeleteRoom(${room.id}, '${room.name}')" title="Delete Permanently">
                        <i class="fas fa-trash"></i>
                    </button>
                `}
            </td>
        `;
        
        tbody.appendChild(row);
    });
    
    // Render pagination controls
    if (roomsPagination) roomsPagination.render();
}

function updateRoomStats() {
    // Overall stats
    const totalRooms = roomsState.allRooms.length;
    const publicRooms = roomsState.allRooms.filter(r => r.type === 'public').length;
    const privateRooms = roomsState.allRooms.filter(r => r.type === 'private').length;
    const activeRooms = roomsState.allRooms.filter(r => r.status === 'active').length;
    
    document.getElementById('stat-total-rooms').textContent = totalRooms;
    document.getElementById('stat-public-rooms').textContent = publicRooms;
    document.getElementById('stat-private-rooms').textContent = privateRooms;
    document.getElementById('stat-active-rooms').textContent = activeRooms;
    
    // Update filter badges
    document.getElementById('badge-all').textContent = totalRooms;
    
    roomsState.roomCapableGames.forEach(game => {
        const gameRooms = roomsState.allRooms.filter(r => r.game_type === game.id).length;
        const badge = document.getElementById(`badge-${game.id}`);
        if (badge) badge.textContent = gameRooms;
    });
}

function openEditRoomModal(id) {
    const room = roomsState.allRooms.find(r => r.id === id);
    if (!room) return;
    
    document.getElementById('edit-room-id').value = room.id;
    document.getElementById('edit-game-type').value = room.game_type;
    document.getElementById('edit-room-name').value = room.name;
    document.getElementById('edit-room-password').value = room.password || '';
    document.getElementById('edit-room-type').value = room.type;
    document.getElementById('edit-room-status').value = room.status;
    
    openModal(editRoomModal);
}

async function handleAddRoom(e) {
    e.preventDefault();
    
    const gameType = document.getElementById('new-game-type').value;
    const name = document.getElementById('new-room-name').value;
    const password = document.getElementById('new-room-password').value;
    const type = document.getElementById('new-room-type').value;
    const status = document.getElementById('new-room-status').value;
    
    try {
        const response = await axios.post('/admin/api/rooms', {
            gameType,
            name,
            password: password || null,
            type,
            status
        });
        
        if (response.data.success) {
            closeModal(addRoomModal);
            addRoomForm.reset();
            loadRooms();
            showToast('Room created successfully', 'success');
        } else {
            showToast('Failed to create room', 'error', response.data.error);
        }
    } catch (error) {
        console.error('Error creating room:', error);
        showToast('Failed to create room', 'error', error.response?.data?.error || 'Please try again.');
    }
}

async function handleSaveRoom(e) {
    e.preventDefault();
    
    const id = document.getElementById('edit-room-id').value;
    const name = document.getElementById('edit-room-name').value;
    const password = document.getElementById('edit-room-password').value;
    const type = document.getElementById('edit-room-type').value;
    const status = document.getElementById('edit-room-status').value;
    
    try {
        const response = await axios.put(`/admin/api/rooms/${id}`, {
            name,
            password: password || null,
            type,
            status
        });
        
        if (response.data.success) {
            closeModal(editRoomModal);
            loadRooms();
            showToast('Room updated successfully', 'success');
        } else {
            showToast('Failed to update room', 'error', response.data.error);
        }
    } catch (error) {
        console.error('Error updating room:', error);
        showToast('Failed to update room', 'error', error.response?.data?.error || 'Please try again.');
    }
}


// Archive room (confirmation)
function confirmArchiveRoom(id, name) {
    showConfirmation(
        'Archive Room',
        `Are you sure you want to archive room "${name}"? It will be hidden but can be restored later.`,
        () => deleteRoom(id)
    );
}

// Archive room (soft delete)
async function deleteRoom(id) {
    try {
        const response = await axios.delete(`/admin/api/rooms/${id}`);
        
        if (response.data.success) {
            loadRooms();
            showToast('Room archived successfully', 'success');
        } else {
            showToast('Failed to archive room', 'error', response.data.error);
        }
    } catch (error) {
        console.error('Error archiving room:', error);
        showToast('Failed to archive room', 'error', error.response?.data?.error || 'Please try again.');
    }
}

// Restore room
async function restoreRoom(id) {
    try {
        const response = await axios.post(`/admin/api/rooms/${id}/restore`);
        
        if (response.data.success) {
            loadRooms();
            showToast('Room restored successfully', 'success');
        } else {
            showToast('Failed to restore room', 'error', response.data.error);
        }
    } catch (error) {
        console.error('Error restoring room:', error);
        showToast('Failed to restore room', 'error', error.response?.data?.error || 'Please try again.');
    }
}

// Permanently delete room (confirmation)
function confirmPermanentDeleteRoom(id, name) {
    showConfirmation(
        'Permanently Delete Room',
        `Are you sure you want to PERMANENTLY delete room "${name}"? This action cannot be undone!`,
        () => permanentlyDeleteRoom(id)
    );
}

// Permanently delete room (hard delete)
async function permanentlyDeleteRoom(id) {
    try {
        const response = await axios.delete(`/admin/api/rooms/${id}/permanent`);
        
        if (response.data.success) {
            loadRooms();
            showToast('Room permanently deleted', 'success');
        } else {
            showToast('Failed to permanently delete room', 'error', response.data.error);
        }
    } catch (error) {
        console.error('Error permanently deleting room:', error);
        showToast('Failed to permanently delete room', 'error', error.response?.data?.error || 'Please try again.');
    }
}


// ==========================================
// Testimonials Management
// ==========================================

async function loadTestimonials() {
    const tableBody = document.getElementById('testimonials-table-body');
    const loading = document.getElementById('testimonials-loading');
    const emptyState = document.getElementById('testimonials-empty-state');
    const table = document.getElementById('testimonials-table');

    if (!tableBody) return;

    // Show loading state
    loading.style.display = 'flex';
    table.style.display = 'none';
    emptyState.style.display = 'none';

    try {
        const response = await axios.get('/admin/api/testimonials');
        const testimonials = response.data;
        testimonialsState.allTestimonials = testimonials;

        loading.style.display = 'none';

        if (testimonials.length === 0) {
            emptyState.style.display = 'block';
            table.style.display = 'none';
        } else {
            emptyState.style.display = 'none';
            table.style.display = 'table';
            renderTestimonials(testimonials);
        }
    } catch (error) {
        console.error('Error loading testimonials:', error);
        loading.style.display = 'none';
        showToast('Failed to load testimonials', 'error');
    }
}

function renderTestimonials(testimonials) {
    const tableBody = document.getElementById('testimonials-table-body');
    if (!tableBody) return;

    tableBody.innerHTML = testimonials.map(t => {
        const rankClass = `rank-${t.player_rank.toLowerCase()}`;
        return `
        <tr>
            <td>
                <div class="user-info-cell">
                    <div class="user-avatar-small">${t.player_avatar || t.player_name.charAt(0)}</div>
                    <span class="user-name">${t.player_name}</span>
                </div>
            </td>
            <td><span class="badge badge-rank ${rankClass}">${t.player_rank}</span></td>
            <td class="message-cell" title="${t.message}">${t.message.length > 50 ? t.message.substring(0, 50) + '...' : t.message}</td>
            <td>
                <div class="rating-stars">
                    ${Array(5).fill(0).map((_, i) => 
                        `<i class="fas fa-star ${i < t.rating ? 'text-warning' : 'text-muted'}"></i>`
                    ).join('')}
                </div>
            </td>
            <td>${formatDate(t.created_at)}</td>
            <td>
                <div class="action-buttons">
                    <button class="btn-icon" data-action="edit-testimonial" data-id="${t.id}" title="Edit">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="btn-icon danger" data-action="delete-testimonial" data-id="${t.id}" title="Delete">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </td>
        </tr>
    `}).join('');
}

async function handleAddTestimonial(e) {
    e.preventDefault();

    const playerName = document.getElementById('new-player-name').value;
    const playerRank = document.getElementById('new-player-rank').value;
    const playerAvatar = document.getElementById('new-player-avatar').value;
    const message = document.getElementById('new-message').value;
    const rating = document.getElementById('new-rating').value;

    try {
        const response = await axios.post('/admin/api/testimonials', {
            playerName,
            playerRank,
            playerAvatar,
            message,
            rating: parseInt(rating)
        });

        if (response.data.success) {
            closeModal(document.getElementById('add-testimonial-modal'));
            document.getElementById('add-testimonial-form').reset();
            loadTestimonials();
            showToast('Testimonial added successfully', 'success');
        } else {
            showToast('Failed to add testimonial', 'error', response.data.error);
        }
    } catch (error) {
        console.error('Error adding testimonial:', error);
        showToast('Failed to add testimonial', 'error', error.response?.data?.error || 'Please try again.');
    }
}

function editTestimonial(id) {
    const testimonial = testimonialsState.allTestimonials.find(t => String(t.id) === String(id));
    if (!testimonial) return;

    document.getElementById('edit-testimonial-id').value = testimonial.id;
    document.getElementById('edit-player-name').value = testimonial.player_name;
    document.getElementById('edit-player-rank').value = testimonial.player_rank;
    document.getElementById('edit-player-avatar').value = testimonial.player_avatar;
    document.getElementById('edit-message').value = testimonial.message;
    document.getElementById('edit-rating').value = testimonial.rating;

    openModal(document.getElementById('edit-testimonial-modal'));
}

async function handleEditTestimonial(e) {
    e.preventDefault();

    const id = document.getElementById('edit-testimonial-id').value;
    const playerName = document.getElementById('edit-player-name').value;
    const playerRank = document.getElementById('edit-player-rank').value;
    const playerAvatar = document.getElementById('edit-player-avatar').value;
    const message = document.getElementById('edit-message').value;
    const rating = document.getElementById('edit-rating').value;

    try {
        const response = await axios.put(`/admin/api/testimonials/${id}`, {
            playerName,
            playerRank,
            playerAvatar,
            message,
            rating: parseInt(rating)
        });

        if (response.data.success) {
            closeModal(document.getElementById('edit-testimonial-modal'));
            loadTestimonials();
            showToast('Testimonial updated successfully', 'success');
        } else {
            showToast('Failed to update testimonial', 'error', response.data.error);
        }
    } catch (error) {
        console.error('Error updating testimonial:', error);
        showToast('Failed to update testimonial', 'error', error.response?.data?.error || 'Please try again.');
    }
}

async function deleteTestimonial(id) {
    try {
        const response = await axios.delete(`/admin/api/testimonials/${id}`);

        if (response.data.success) {
            loadTestimonials();
            showToast('Testimonial deleted successfully', 'success');
        } else {
            showToast('Failed to delete testimonial', 'error', response.data.error);
        }
    } catch (error) {
        console.error('Error deleting testimonial:', error);
        showToast('Failed to delete testimonial', 'error', error.response?.data?.error || 'Please try again.');
    }
}

// ========================================
// Fullscreen Functions
// ========================================
async function toggleFullscreen() {
    try {
        if (!document.fullscreenElement) {
            // Enter fullscreen
            await document.documentElement.requestFullscreen();
            localStorage.setItem('adminFullscreen', 'true');
        } else {
            // Exit fullscreen
            await document.exitFullscreen();
            localStorage.setItem('adminFullscreen', 'false');
        }
    } catch (error) {
        console.error('Fullscreen toggle error:', error);
        showToast('Fullscreen mode not available', 'error');
    }
}

function updateFullscreenIcon() {
    const fullscreenToggle = document.getElementById('fullscreen-toggle');
    if (!fullscreenToggle) return;
    
    const icon = fullscreenToggle.querySelector('i');
    if (!icon) return;
    
    if (document.fullscreenElement) {
        // Currently in fullscreen - show compress icon
        icon.className = 'fas fa-compress';
        fullscreenToggle.title = 'Exit Fullscreen';
        localStorage.setItem('adminFullscreen', 'true');
    } else {
        // Not in fullscreen - show expand icon
        icon.className = 'fas fa-expand';
        fullscreenToggle.title = 'Toggle Fullscreen';
        localStorage.setItem('adminFullscreen', 'false');
    }
}


// Auto-refresh every 30 seconds
setInterval(() => {
    if (adminDashboard.style.display !== 'none') {
        loadSectionData(currentSection);
    }
}, 30000);
