const express = require('express');
const path = require('path');
const fs = require('fs').promises;
const session = require('express-session');
const rateLimit = require('express-rate-limit');
const analyticsCollector = require('./analytics-collector-sqlite');

const gamesDB = require('./games-db');
const usersDB = require('./users-db');
const settingsDB = require('./settings-db');
const roomsDB = require('./rooms-db');
const testimonialsDB = require('./testimonials-db');
const appEmitter = require('./events');


// Initialize users (create default admin if needed)
usersDB.init();


/**
 * Admin Panel Server Module
 * Provides authentication, game management, and analytics APIs
 */
module.exports = function(appInstance) {
    const router = express.Router();

    // Session configuration
    router.use(session({
        secret: process.env.SESSION_SECRET || 'admin-secret-key-change-in-production',
        resave: false,
        saveUninitialized: false,
        cookie: { 
            maxAge: 3600000, // 1 hour
            httpOnly: true,
            secure: false // Set to false to allow working on localhost (HTTP)
        }
    }));

    // Authentication middleware
    const requireAuth = (req, res, next) => {
        if (req.session && req.session.authenticated) {
            next();
        } else {
            if (req.accepts('html')) {
                res.status(403).sendFile(path.join(__dirname, '../../public/error/403.html'));
            } else {
                res.status(401).json({ error: 'Unauthorized' });
            }
        }
    };

    // View Engine Setup
    if (appInstance) {
        appInstance.set('views', path.join(__dirname, '../views/pages'));
        appInstance.set('view engine', 'ejs');
    }

    // Serve static files for admin panel
    router.use('/assets', express.static(path.join(__dirname, '../public')));

    // Admin Panel Routes (Page Rendering)
    router.get('/', (req, res) => {
        if (req.session && req.session.authenticated) {
            res.redirect('/admin/dashboard');
        } else {
            res.render('login', { title: 'Login' });
        }
    });

    router.get('/login', (req, res) => {
        if (req.session && req.session.authenticated) {
            res.redirect('/admin/dashboard');
        } else {
            res.render('login', { title: 'Login' });
        }
    });

    router.get('/dashboard', requireAuth, (req, res) => {
        res.render('dashboard', { 
            title: 'Dashboard', 
            user: req.session.user,
            path: '/admin/dashboard'
        });
    });

    router.get('/games', requireAuth, (req, res) => {
        res.render('games', { 
            title: 'Games', 
            user: req.session.user,
            path: '/admin/games'
        });
    });

    router.get('/users', requireAuth, (req, res) => {
        res.render('users', { 
            title: 'Users', 
            user: req.session.user,
            path: '/admin/users'
        });
    });

    router.get('/rooms', requireAuth, (req, res) => {
        res.render('rooms', { 
            user: req.session.user,
            path: '/admin/rooms',
            title: 'Room Management'
        });
    });

    router.get('/settings', requireAuth, (req, res) => {
        res.render('settings', { 
            title: 'Settings', 
            user: req.session.user,
            path: '/admin/settings'
        });
    });

    router.get('/profile', requireAuth, (req, res) => {
        res.render('profile', { 
            title: 'My Profile',
            user: req.session.user,
            path: '/admin/profile'
        });
    });

    router.get('/testimonials', requireAuth, (req, res) => {
        res.render('testimonials', { 
            title: 'Testimonials',
            user: req.session.user,
            path: '/admin/testimonials'
        });
    });

    // Rate limiter for login attempts
    const loginLimiter = rateLimit({
        windowMs: 24 * 60 * 60 * 1000, // 1 day
        max: 5, // Limit each IP to 5 requests per windowMs
        standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
        legacyHeaders: false, // Disable the `X-RateLimit-*` headers
        skipSuccessfulRequests: true, // Don't count successful logins
        handler: (req, res) => {
            res.status(429).json({
                success: false,
                error: 'Too many login attempts. Please try again after 24 hours.'
            });
        }
    });

    // Login endpoint
    router.post('/api/login', loginLimiter, (req, res) => {
        const { username, password } = req.body;

        try {
            const user = usersDB.getUser(username);

            if (!user) {
                return res.status(401).json({ 
                    success: false, 
                    error: 'Invalid username or password' 
                });
            }

            // Check if user is archived
            if (user.status === 'archived') {
                return res.status(403).json({ 
                    success: false, 
                    error: 'This account has been archived and cannot access the admin panel. Please contact a superuser for assistance.' 
                });
            }

            // Check if user is inactive
            if (user.status === 'inactive') {
                return res.status(403).json({ 
                    success: false, 
                    error: 'This account has been temporarily suspended. Please contact an administrator to reactivate your account.' 
                });
            }

            // Verify password
            const validPassword = usersDB.verifyPassword(password, user.password_hash);

            if (!validPassword) {
                return res.status(401).json({ 
                    success: false, 
                    error: 'Invalid username or password' 
                });
            }

            // Set session
            req.session.authenticated = true;
            req.session.user = {
                id: user.id,
                username: user.username,
                role: user.role
            };

            res.json({ success: true });
        } catch (error) {
            console.error('Login error:', error);
            res.status(500).json({ 
                success: false, 
                error: 'An error occurred during login' 
            });
        }
    });

    // Logout endpoint
    router.post('/api/logout', (req, res) => {
        req.session.destroy((err) => {
            if (err) {
                res.status(500).json({ error: 'Failed to logout' });
            } else {
                res.json({ success: true });
            }
        });
    });

    // Check authentication status
    router.get('/api/auth-check', (req, res) => {
        if (req.session && req.session.authenticated) {
            res.json({ 
                authenticated: true,
                user: req.session.user
            });
        } else {
            res.json({ authenticated: false });
        }
    });

    // User Management Endpoints

    // Helper to check permissions
    const canManageUser = (requestingUser, targetRole) => {
        if (requestingUser.role === 'superuser') return true;
        if (requestingUser.role === 'admin' && targetRole === 'user') return true;
        return false;
    };

    // Get all users (Admin/Superuser only)
    router.get('/api/users', requireAuth, (req, res) => {
        if (req.session.user.role === 'user') {
            return res.status(403).json({ error: 'Forbidden' });
        }
        
        try {
            const { status } = req.query;
            const users = usersDB.getAllUsers(status || 'all');
            res.json(users);
        } catch (error) {
            console.error('Error fetching users:', error);
            res.status(500).json({ error: 'Failed to fetch users' });
        }
    });

    // Create new user
    router.post('/api/users', requireAuth, (req, res) => {
        const { username, password, role } = req.body;
        const requestingUser = req.session.user;

        // Permission check
        if (!canManageUser(requestingUser, role)) {
            return res.status(403).json({ error: 'Insufficient permissions to create this role' });
        }

        if (!username || !password) {
            return res.status(400).json({ error: 'Username and password are required' });
        }

        try {
            usersDB.createUser(username, password, role);
            res.json({ success: true });
        } catch (error) {
            console.error('Error creating user:', error);
            // Return 409 Conflict for duplicate username, 500 for other errors
            const statusCode = error.message === 'Username already exists' ? 409 : 500;
            res.status(statusCode).json({ error: error.message || 'Failed to create user' });
        }
    });

    // Archive user (Soft Delete - Changed from hard delete)
    router.delete('/api/users/:id', requireAuth, (req, res) => {
        const { id } = req.params;
        const requestingUser = req.session.user;

        try {
            const target = usersDB.getById(id);

            if (!target) {
                return res.status(404).json({ error: 'User not found' });
            }

            if (target.role === 'superuser') {
                return res.status(403).json({ error: 'Cannot archive superuser account' });
            }

            if (target.id === requestingUser.id) {
                return res.status(400).json({ error: 'Cannot archive yourself' });
            }

            if (!canManageUser(requestingUser, target.role)) {
                return res.status(403).json({ error: 'Insufficient permissions to archive this user' });
            }

            // Soft delete: Set status to 'archived'
            usersDB.updateUserStatus(id, 'archived');
            res.json({ success: true });
        } catch (error) {
            console.error('Error archiving user:', error);
            res.status(500).json({ error: error.message || 'Failed to archive user' });
        }
    });

    // Restore archived user (Set status back to 'active')
    router.post('/api/users/:id/restore', requireAuth, (req, res) => {
        const { id } = req.params;
        const requestingUser = req.session.user;

        try {
            const target = usersDB.getById(id);

            if (!target) {
                return res.status(404).json({ error: 'User not found' });
            }

            if (!canManageUser(requestingUser, target.role)) {
                return res.status(403).json({ error: 'Insufficient permissions to restore this user' });
            }

            // Restore: Set status to 'active'
            usersDB.updateUserStatus(id, 'active');
            res.json({ success: true });
        } catch (error) {
            console.error('Error restoring user:', error);
            res.status(500).json({ error: error.message || 'Failed to restore user' });
        }
    });

    // Activate user (Set status to 'active')
    router.post('/api/users/:id/activate', requireAuth, (req, res) => {
        const { id } = req.params;
        const requestingUser = req.session.user;

        try {
            const target = usersDB.getById(id);

            if (!target) {
                return res.status(404).json({ error: 'User not found' });
            }

            if (!canManageUser(requestingUser, target.role)) {
                return res.status(403).json({ error: 'Insufficient permissions to activate this user' });
            }

            // Activate: Set status to 'active'
            usersDB.updateUserStatus(id, 'active');
            res.json({ success: true });
        } catch (error) {
            console.error('Error activating user:', error);
            res.status(500).json({ error: error.message || 'Failed to activate user' });
        }
    });

    // Deactivate user (Set status to 'inactive')
    router.post('/api/users/:id/deactivate', requireAuth, (req, res) => {
        const { id } = req.params;
        const requestingUser = req.session.user;

        try {
            const target = usersDB.getById(id);

            if (!target) {
                return res.status(404).json({ error: 'User not found' });
            }

            if (target.role === 'superuser') {
                return res.status(403).json({ error: 'Cannot deactivate superuser account' });
            }

            if (target.id === requestingUser.id) {
                return res.status(400).json({ error: 'Cannot deactivate yourself' });
            }

            if (!canManageUser(requestingUser, target.role)) {
                return res.status(403).json({ error: 'Insufficient permissions to deactivate this user' });
            }

            // Deactivate: Set status to 'inactive'
            usersDB.updateUserStatus(id, 'inactive');
            res.json({ success: true });
        } catch (error) {
            console.error('Error deactivating user:', error);
            res.status(500).json({ error: error.message || 'Failed to deactivate user' });
        }
    });

    // Permanently delete user (Only for archived users)
    router.delete('/api/users/:id/permanent', requireAuth, (req, res) => {
        const { id } = req.params;
        const requestingUser = req.session.user;

        try {
            const target = usersDB.getById(id);

            if (!target) {
                return res.status(404).json({ error: 'User not found' });
            }

            if (target.role === 'superuser') {
                return res.status(403).json({ error: 'Cannot delete superuser account' });
            }

            if (target.status !== 'archived') {
                return res.status(400).json({ error: 'Can only permanently delete archived users. Archive the user first.' });
            }

            if (target.id === requestingUser.id) {
                return res.status(400).json({ error: 'Cannot delete yourself' });
            }

            if (!canManageUser(requestingUser, target.role)) {
                return res.status(403).json({ error: 'Insufficient permissions to delete this user' });
            }

            // Hard delete from database
            usersDB.deleteUser(id);
            res.json({ success: true });
        } catch (error) {
            console.error('Error permanently deleting user:', error);
            res.status(500).json({ error: error.message || 'Failed to delete user' });
        }
    });

    // Update user
    router.put('/api/users/:id', requireAuth, (req, res) => {
        const { id } = req.params;
        const { username, role, password } = req.body;
        const requestingUser = req.session.user;

        try {
            // Get target user to check permissions
            const target = usersDB.getById(id);

            if (!target) {
                return res.status(404).json({ error: 'User not found' });
            }

            // Permission checks
            if (!canManageUser(requestingUser, target.role)) {
                return res.status(403).json({ error: 'Insufficient permissions to modify this user' });
            }

            // Prevent changing own role (to avoid lockout)
            if (target.id === requestingUser.id && role && role !== target.role) {
                return res.status(400).json({ error: 'Cannot change your own role' });
            }

            // If changing role to something higher than requester (impossible by logic but good safety)
            if (role && !canManageUser(requestingUser, role)) {
                return res.status(403).json({ error: 'Cannot promote user beyond your rank' });
            }

            usersDB.updateUser(id, { username, role, password });
            res.json({ success: true });
        } catch (error) {
            console.error('Error updating user:', error);
            const statusCode = error.message === 'Username already exists' ? 409 : 500;
            res.status(statusCode).json({ error: error.message || 'Failed to update user' });
        }
    });

    // Settings: Update password
    router.post('/api/settings/password', requireAuth, (req, res) => {
        const { currentPassword, newPassword } = req.body;
        const userId = req.session.user.id;

        try {
            const result = usersDB.updatePassword(userId, currentPassword, newPassword);
            if (result.success) {
                res.json({ success: true });
            } else {
                res.status(400).json({ error: result.error });
            }
        } catch (error) {
            console.error('Error updating password:', error);
            res.status(500).json({ error: 'Failed to update password' });
        }
    });

    // Profile: Update username
    router.post('/api/profile/username', requireAuth, (req, res) => {
        const { username } = req.body;
        const userId = req.session.user.id;

        try {
            if (!username || username.trim().length < 3) {
                return res.status(400).json({ error: 'Username must be at least 3 characters' });
            }

            // Check if username already exists
            const allUsers = usersDB.getAllUsers();
            const existingUser = allUsers.find(u => u.username === username && u.id !== userId);
            if (existingUser) {
                return res.status(400).json({ error: 'Username already taken' });
            }

            usersDB.updateUser(userId, { username });
            
            // Update session
            req.session.user.username = username;
            
            res.json({ success: true });
        } catch (error) {
            console.error('Error updating username:', error);
            res.status(500).json({ error: 'Failed to update username' });
        }
    });

    // Profile: Change password
    router.post('/api/profile/password', requireAuth, (req, res) => {
        const { currentPassword, newPassword } = req.body;
        const userId = req.session.user.id;

        try {
            if (!newPassword || newPassword.length < 6) {
                return res.status(400).json({ error: 'Password must be at least 6 characters' });
            }

            const result = usersDB.updatePassword(userId, currentPassword, newPassword);
            if (result.success) {
                res.json({ success: true });
            } else {
                res.status(400).json({ error: result.error });
            }
        } catch (error) {
            console.error('Error changing password:', error);
            res.status(500).json({ error: 'Failed to change password' });
        }
    });

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

    // Get all rooms
    router.get('/api/rooms', requireAuth, (req, res) => {
        try {
            const rooms = roomsDB.getAllRooms();
            res.json(rooms);
        } catch (error) {
            console.error('Error fetching rooms:', error);
            res.status(500).json({ error: 'Failed to fetch rooms' });
        }
    });

    // Create room
    router.post('/api/rooms', requireAuth, (req, res) => {
        try {
            const { gameType, name, password, type, status } = req.body;
            
            if (!gameType || !name || !type) {
                return res.status(400).json({ error: 'Missing required fields' });
            }

            roomsDB.createRoom(gameType, name, password || null, type, status || 'active');
            appEmitter.emit('room_update', { gameType });
            res.json({ success: true });
        } catch (error) {
            console.error('Error creating room:', error);
            res.status(500).json({ error: 'Failed to create room' });
        }
    });

    // Update room
    router.put('/api/rooms/:id', requireAuth, (req, res) => {
        try {
            const { name, password, type, status } = req.body;
            
            if (!name || !type) {
                return res.status(400).json({ error: 'Missing required fields' });
            }

            roomsDB.updateRoom(req.params.id, name, password || null, type, status || 'active');
            
            // We need to know the game type to notify the correct server.
            // Since updateRoom doesn't take gameType (it's immutable), we should fetch the room first or just emit a generic update.
            // Better: fetch the room to get its gameType.
            const room = roomsDB.getById(req.params.id);
            if (room) {
                appEmitter.emit('room_update', { gameType: room.game_type });
            }
            
            res.json({ success: true });
        } catch (error) {
            console.error('Error updating room:', error);
            res.status(500).json({ error: 'Failed to update room' });
        }
    });

    // Delete room (Soft Delete - Archive)
    router.delete('/api/rooms/:id', requireAuth, (req, res) => {
        try {
            const room = roomsDB.getById(req.params.id);
            if (!room) {
                return res.status(404).json({ error: 'Room not found' });
            }
            
            // Soft delete: Set status to 'archived'
            roomsDB.updateRoom(req.params.id, room.name, room.password, room.type, 'archived');
            
            appEmitter.emit('room_update', { gameType: room.game_type });
            res.json({ success: true });
        } catch (error) {
            console.error('Error archiving room:', error);
            res.status(500).json({ error: 'Failed to archive room' });
        }
    });

    // Restore room (Set status back to 'active')
    router.post('/api/rooms/:id/restore', requireAuth, (req, res) => {
        try {
            const room = roomsDB.getById(req.params.id);
            if (!room) {
                return res.status(404).json({ error: 'Room not found' });
            }
            
            // Restore: Set status to 'active'
            roomsDB.updateRoom(req.params.id, room.name, room.password, room.type, 'active');
            
            appEmitter.emit('room_update', { gameType: room.game_type });
            res.json({ success: true });
        } catch (error) {
            console.error('Error restoring room:', error);
            res.status(500).json({ error: 'Failed to restore room' });
        }
    });

    // Permanently delete room
    router.delete('/api/rooms/:id/permanent', requireAuth, (req, res) => {
        try {
            const room = roomsDB.getById(req.params.id);
            roomsDB.deleteRoom(req.params.id);
            if (room) {
                appEmitter.emit('room_update', { gameType: room.game_type });
            }
            res.json({ success: true });
        } catch (error) {
            console.error('Error permanently deleting room:', error);
            res.status(500).json({ error: 'Failed to permanently delete room' });
        }
    });

    // Get games that support rooms
    router.get('/api/games/room-capable', requireAuth, (req, res) => {
        try {
            const allGames = gamesDB.getAllGames();
            const roomCapableGames = allGames.filter(g => g.supports_rooms === 1);
            res.json(roomCapableGames);
        } catch (error) {
            console.error('Error fetching room-capable games:', error);
            res.status(500).json({ error: 'Failed to fetch games' });
        }
    });

    // Public API for game servers to fetch their rooms
    router.get('/api/games/:game/rooms', (req, res) => {
        try {
            const { game } = req.params;
            // Normalize game name (e.g. 'ludo' -> 'ludo')
            const rooms = roomsDB.getActiveRoomsByGame(game);
            res.json(rooms);
        } catch (error) {
            console.error(`Error fetching rooms for ${req.params.game}:`, error);
            res.status(500).json({ error: 'Failed to fetch rooms' });
        }
    });

    // Get all games (authenticated)
    router.get('/api/games', requireAuth, async (req, res) => {
        try {
            const games = gamesDB.formatGames(gamesDB.getAllGames());
            
            // Add analytics data to each game
            const gamesWithAnalytics = await Promise.all(
                games.map(async (game) => {
                    const analytics = await analyticsCollector.getGameAnalytics(game.id);
                    return {
                        ...game,
                        analytics: analytics || {
                            totalSessions: 0,
                            uniqueUsers: 0,
                            avgDuration: 0,
                            totalPlaytime: 0
                        }
                    };
                })
            );
            
            res.json(gamesWithAnalytics);
        } catch (error) {
            console.error('Error reading games:', error);
            res.status(500).json({ error: 'Failed to load games' });
        }
    });

    // Get single game by ID (authenticated)
    router.get('/api/games/:gameId', requireAuth, async (req, res) => {
        try {
            const { gameId } = req.params;
            const game = gamesDB.getGameById(gameId);
            
            if (!game) {
                return res.status(404).json({ error: 'Game not found' });
            }
            
            res.json(gamesDB.formatGame(game));
        } catch (error) {
            console.error('Error fetching game:', error);
            res.status(500).json({ error: 'Failed to load game' });
        }
    });

    // Update game details (authenticated)
    router.put('/api/games/:gameId', requireAuth, async (req, res) => {
        try {
            const { gameId } = req.params;
            const updates = req.body;

            gamesDB.updateGame(gameId, updates);
            const game = gamesDB.formatGame(gamesDB.getGameById(gameId));
            
            res.json({ success: true, game });
        } catch (error) {
            console.error('Error updating game:', error);
            res.status(500).json({ error: 'Failed to update game' });
        }
    });

    // Toggle game enabled status (authenticated)
    router.post('/api/games/:gameId/toggle', requireAuth, async (req, res) => {
        try {
            const { gameId } = req.params;

            const game = gamesDB.getGameById(gameId);
            if (!game) {
                return res.status(404).json({ error: 'Game not found' });
            }

            const newStatus = !game.enabled;
            gamesDB.toggleGame(gameId, newStatus);
            const updatedGame = gamesDB.formatGame(gamesDB.getGameById(gameId));

            res.json({ success: true, game: updatedGame });
        } catch (error) {
            console.error('Error toggling game:', error);
            res.status(500).json({ error: 'Failed to toggle game' });
        }
    });

    // Update game maintenance settings (authenticated)
    router.post('/api/games/:gameId/maintenance', requireAuth, async (req, res) => {
        try {
            const { gameId } = req.params;
            const { maintenanceMode, message, eta } = req.body;

            const game = gamesDB.getGameById(gameId);
            if (!game) {
                return res.status(404).json({ error: 'Game not found' });
            }

            gamesDB.updateGameMaintenance(gameId, maintenanceMode, message, eta);
            const updatedGame = gamesDB.formatGame(gamesDB.getGameById(gameId));

            res.json({ success: true, game: updatedGame });
        } catch (error) {
            console.error('Error updating game maintenance:', error);
            res.status(500).json({ error: 'Failed to update game maintenance' });
        }
    });

    // Analytics endpoints

    // Get analytics overview (authenticated)
    router.get('/api/analytics/overview', requireAuth, async (req, res) => {
        try {
            const overview = await analyticsCollector.getOverview();
            res.json(overview);
        } catch (error) {
            console.error('Error getting analytics overview:', error);
            res.status(500).json({ error: 'Failed to load analytics' });
        }
    });

    // Get all games analytics summary (authenticated)
    router.get('/api/analytics/games', requireAuth, async (req, res) => {
        try {
            const games = gamesDB.getAllGames();
            const labels = [];
            const plays = [];

            for (const game of games) {
                const analytics = await analyticsCollector.getGameAnalytics(game.id);
                labels.push(game.name);
                plays.push(analytics?.totalSessions || 0);
            }

            res.json({ labels, plays });
        } catch (error) {
            console.error('Error getting games analytics summary:', error);
            res.status(500).json({ error: 'Failed to load games analytics' });
        }
    });

    // Get game-specific analytics (authenticated)
    router.get('/api/analytics/games/:gameId', requireAuth, async (req, res) => {
        try {
            const { gameId } = req.params;
            const analytics = await analyticsCollector.getGameAnalytics(gameId);
            res.json(analytics);
        } catch (error) {
            console.error('Error getting game analytics:', error);
            res.status(500).json({ error: 'Failed to load game analytics' });
        }
    });

    // Get traffic data (authenticated)
    router.get('/api/analytics/traffic', requireAuth, async (req, res) => {
        try {
            const { range = 'week' } = req.query;
            const traffic = await analyticsCollector.getTrafficData(range);
            res.json(traffic);
        } catch (error) {
            console.error('Error getting traffic data:', error);
            res.status(500).json({ error: 'Failed to load traffic data' });
        }
    });

    // Get all games analytics for comparison (authenticated)
    router.get('/api/analytics/games-comparison', requireAuth, async (req, res) => {
        try {
            const games = gamesDB.getAllGames();
            
            const comparison = await Promise.all(
                games.map(async (game) => {
                    const analytics = await analyticsCollector.getGameAnalytics(game.id);
                    return {
                        id: game.id,
                        name: game.name,
                        ...analytics
                    };
                })
            );

            res.json(comparison);
        } catch (error) {
            console.error('Error getting games comparison:', error);
            res.status(500).json({ error: 'Failed to load comparison' });
        }
    });

    // Get game comparison data for chart (authenticated)
    router.get('/api/analytics/game-comparison', requireAuth, async (req, res) => {
        try {
            const comparison = await analyticsCollector.getGameComparison();
            res.json(comparison);
        } catch (error) {
            console.error('Error fetching game comparison:', error);
            res.status(500).json({ error: 'Failed to fetch comparison data' });
        }
    });

    // Get device analytics (authenticated)
    router.get('/api/analytics/devices', requireAuth, async (req, res) => {
        try {
            const deviceAnalytics = await analyticsCollector.getDeviceAnalytics();
            res.json(deviceAnalytics);
        } catch (error) {
            console.error('Error fetching device analytics:', error);
            res.status(500).json({ error: 'Failed to fetch device analytics' });
        }
    });

    router.get('/', requireAuth, (req, res) => {
        res.render('dashboard', { 
            title: 'Dashboard', 
            user: req.session.user,
            path: '/admin/dashboard' 
        });
    });

    router.get('/login', (req, res) => {
        if (req.session && req.session.authenticated) {
            return res.redirect('/admin/dashboard');
        }
        res.render('login', { title: 'Login' });
    });

    router.get('/games', requireAuth, (req, res) => {
        res.render('games', { 
            title: 'Games', 
            user: req.session.user,
            path: '/admin/games' 
        });
    });

    router.get('/analytics', requireAuth, (req, res) => {
        res.render('analytics', { 
            title: 'Analytics', 
            user: req.session.user,
            path: '/admin/analytics' 
        });
    });

    router.get('/users', requireAuth, (req, res) => {
        if (req.session.user.role === 'user') {
            return res.redirect('/admin/');
        }
        res.render('users', { 
            title: 'Users', 
            user: req.session.user,
            path: '/admin/users' 
        });
    });

    router.get('/settings', requireAuth, (req, res) => {
        res.render('settings', { 
            title: 'Settings', 
            user: req.session.user,
            path: '/admin/settings' 
        });
    });

    // Settings API endpoints
    
    // Get all settings (authenticated)
    router.get('/api/settings', requireAuth, (req, res) => {
        try {
            const settings = settingsDB.getAll();
            res.json({ success: true, settings });
        } catch (error) {
            console.error('Error getting settings:', error);
            res.status(500).json({ error: 'Failed to load settings' });
        }
    });

    // Update a setting (authenticated)
    router.post('/api/settings', requireAuth, (req, res) => {
        try {
            const { key, value } = req.body;
            
            if (!key) {
                return res.status(400).json({ error: 'Setting key is required' });
            }

            settingsDB.set(key, value);
            const updatedValue = settingsDB.get(key);
            
            res.json({ success: true, key, value: updatedValue });
        } catch (error) {
            console.error('Error updating setting:', error);
            res.status(500).json({ error: 'Failed to update setting' });
        }
    });

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

    // Get all testimonials (Public)
    router.get('/api/testimonials', (req, res) => {
        try {
            const testimonials = testimonialsDB.getAllTestimonials();
            res.json(testimonials);
        } catch (error) {
            console.error('Error fetching testimonials:', error);
            res.status(500).json({ error: 'Failed to fetch testimonials' });
        }
    });

    // Create new testimonial
    router.post('/api/testimonials', requireAuth, (req, res) => {
        try {
            const { playerName, playerRank, playerAvatar, message, rating } = req.body;
            
            if (!playerName || !message) {
                return res.status(400).json({ error: 'Player name and message are required' });
            }

            testimonialsDB.addTestimonial({
                playerName,
                playerRank: playerRank || 'Player',
                playerAvatar: playerAvatar || playerName.charAt(0).toUpperCase(),
                message,
                rating: rating || 5
            });

            res.json({ success: true });
        } catch (error) {
            console.error('Error creating testimonial:', error);
            res.status(500).json({ error: 'Failed to create testimonial' });
        }
    });

    // Update testimonial
    router.put('/api/testimonials/:id', requireAuth, (req, res) => {
        try {
            const { id } = req.params;
            const { playerName, playerRank, playerAvatar, message, rating } = req.body;
            
            if (!playerName || !message) {
                return res.status(400).json({ error: 'Player name and message are required' });
            }

            testimonialsDB.updateTestimonial(id, {
                playerName,
                playerRank: playerRank || 'Player',
                playerAvatar: playerAvatar || playerName.charAt(0).toUpperCase(),
                message,
                rating: rating || 5
            });

            res.json({ success: true });
        } catch (error) {
            console.error('Error updating testimonial:', error);
            res.status(500).json({ error: 'Failed to update testimonial' });
        }
    });

    // Delete testimonial
    router.delete('/api/testimonials/:id', requireAuth, (req, res) => {
        try {
            const { id } = req.params;
            testimonialsDB.deleteTestimonial(id);
            res.json({ success: true });
        } catch (error) {
            console.error('Error deleting testimonial:', error);
            res.status(500).json({ error: 'Failed to delete testimonial' });
        }
    });


    // Mount router on app
    if (appInstance) {
        // We need to set the view engine on the main app if we want to use it
        // But since this is a sub-router, we might need to be careful.
        // Express routers behave like mini-apps.
        // Let's try setting it on the router, but usually view engine is app-level.
        // If appInstance is passed, we might need to configure it there or use a separate app for admin.
        // For now, let's assume router configuration works or we configure it on appInstance if possible.
        // Actually, router.set() is not a function. app.set() is.
        // We should probably just use res.render and ensure the app knows about ejs.
        appInstance.set('view engine', 'ejs');
        appInstance.set('views', path.join(__dirname, '../views/pages'));
        
        appInstance.use('/admin', router);
    }

    console.log('Admin panel mounted at /admin');

    return router;
};
