// Player Activity Status
let isRejoining = false;

// Connect to Ludo namespace
const socket = io('/ludo', {
    reconnection: true,
    reconnectionAttempts: 5
});

socket.on('connect', () => {
    console.log('✅ Connected to Ludo server');
});

// DOM Elements
const startScreen = document.getElementById('start-screen');
const lobbyScreen = document.getElementById('lobby-screen');
const gameScreen = document.getElementById('game-screen');
const roomListEl = document.getElementById('room-list'); // Renamed for consistency
const joinModal = document.getElementById('join-modal');
const gameOverModal = document.getElementById('game-over-modal');

const usernameInput = document.getElementById('username-input');
const passwordInput = document.getElementById('password-input');
const modalRoomName = document.getElementById('modal-room-name');
const confirmJoinBtn = document.getElementById('confirm-join-btn');
const cancelJoinBtn = document.getElementById('cancel-join-btn');

// Navigation Elements
const backToPortalBtn = document.getElementById('back-to-portal-btn');
const backToStartBtn = document.getElementById('back-to-start');
const modeVsPlayerBtn = document.getElementById('mode-vs-player');
const modeVsAiBtn = document.getElementById('mode-vs-ai');

const restartBtn = document.getElementById('restart-btn');
// const roomNameEl = document.getElementById('room-name'); // Removed as not in new UI

const gameBoard = document.getElementById('game-board');
const ctx = gameBoard.getContext('2d');
const diceCube = document.getElementById('dice-cube');
const rollDiceBtn = document.getElementById('roll-dice-btn');
const turnIndicator = document.getElementById('turn-indicator');



const playAgainBtn = document.getElementById('play-again-btn');
const gameOverTitle = document.getElementById('game-over-title');
const gameOverMessage = document.getElementById('game-over-message');
const statsScreen = document.getElementById('stats-screen');
const statsTableBody = document.getElementById('stats-table-body');
const closeStatsBtn = document.getElementById('close-stats-btn');
const viewStatsCard = document.getElementById('view-stats-card');

// Game State
let myColor = null; // 'red', 'blue', 'green', 'yellow'
let myName = '';
let currentRoomId = null;
let currentMatchId = null; // Unique match identifier
let gameState = null;
let selectedRoomId = null;
let gameStartTime = null; // Track game duration
const STORAGE_KEY = 'ludo_session';

// Chatbox instance
let chatbox = null;

// Ludo Path Coordinates (0-51)
// x = column (0-14), y = row (0-14)
const LUDO_PATH = [
    {x:1, y:6}, {x:2, y:6}, {x:3, y:6}, {x:4, y:6}, {x:5, y:6}, // 0-4 (Red Arm)
    {x:6, y:5}, {x:6, y:4}, {x:6, y:3}, {x:6, y:2}, {x:6, y:1}, {x:6, y:0}, // 5-10 (Up)
    {x:7, y:0}, {x:8, y:0}, // 11-12 (Top Turn)
    {x:8, y:1}, {x:8, y:2}, {x:8, y:3}, {x:8, y:4}, {x:8, y:5}, // 13-17 (Down - Blue Start at 13)
    {x:9, y:6}, {x:10, y:6}, {x:11, y:6}, {x:12, y:6}, {x:13, y:6}, {x:14, y:6}, // 18-23 (Right)
    {x:14, y:7}, {x:14, y:8}, // 24-25 (Right Turn)
    {x:13, y:8}, {x:12, y:8}, {x:11, y:8}, {x:10, y:8}, {x:9, y:8}, // 26-30 (Left - Green Start at 26)
    {x:8, y:9}, {x:8, y:10}, {x:8, y:11}, {x:8, y:12}, {x:8, y:13}, {x:8, y:14}, // 31-36 (Down)
    {x:7, y:14}, {x:6, y:14}, // 37-38 (Bottom Turn)
    {x:6, y:13}, {x:6, y:12}, {x:6, y:11}, {x:6, y:10}, {x:6, y:9}, // 39-43 (Up - Yellow Start at 39)
    {x:5, y:8}, {x:4, y:8}, {x:3, y:8}, {x:2, y:8}, {x:1, y:8}, {x:0, y:8}, // 44-49 (Left)
    {x:0, y:7}, {x:0, y:6} // 50-51 (Left Turn)
];
// Note: The path array above has 52 entries (indices 0-51).
// 0 is Red Start. 13 is Blue Start. 26 is Green Start. 39 is Yellow Start.

// LocalStorage Management
function saveSession(roomId, playerName, color, password) {
    localStorage.setItem(STORAGE_KEY, JSON.stringify({
        roomId,
        playerName,
        color,
        password,
        savedAt: Date.now()
    }));
}

function loadSession() {
    const saved = localStorage.getItem(STORAGE_KEY);
    return saved ? JSON.parse(saved) : null;
}

function clearSession() {
    localStorage.removeItem(STORAGE_KEY);
}

// Routing Logic
function handleRoute() {
    const hash = window.location.hash || '#/';
    
    // Hide all screens first
    startScreen.classList.add('hidden');
    lobbyScreen.classList.add('hidden');
    gameScreen.classList.add('hidden');
    
    // Hide chatbox if not in game
    if (hash !== '#/game' && typeof chatbox !== 'undefined' && chatbox) {
        chatbox.hide();
    }
    
    switch(hash) {
        case '#/lobby':
            lobbyScreen.classList.remove('hidden');
            break;
        case '#/game':
            if (!currentRoomId && !isRejoining) {
                // Redirect to lobby if not in a room AND not currently rejoining
                window.location.hash = '#/lobby';
                return;
            }
            gameScreen.classList.remove('hidden');
            break;
        default: // '#/' or empty
            startScreen.classList.remove('hidden');
            break;
    }
}

// Initialize routing  
window.addEventListener('hashchange', (e) => {
    const oldHash = new URL(e.oldURL).hash;
    const newHash = new URL(e.newURL).hash;
    
    // If leaving game screen while in a room, save disconnect time
    if (oldHash === '#/game' && newHash !== '#/game' && currentRoomId) {
        console.log('Leaving game screen, saving disconnect time and leaving room');
        localStorage.setItem('ludo_disconnect_time', Date.now().toString());
        
        // Notify server we are leaving (triggers grace period on server)
        socket.emit('leave_room', { roomId: currentRoomId });
        
        // Clear local room state so notification can appear
        currentRoomId = null;
    }
    
    handleRoute();
});

window.addEventListener('load', () => {
    const savedSession = loadSession();
    if (savedSession) {
        const disconnectTime = localStorage.getItem('ludo_disconnect_time');
        
        if (disconnectTime) {
            // Check if still within grace period (10 seconds)
            const GRACE_PERIOD_MS = 10000;
            const now = Date.now();
            const disconnectedAt = parseInt(disconnectTime);
            const timeSinceDisconnect = now - disconnectedAt;
            
            if (timeSinceDisconnect > GRACE_PERIOD_MS) {
                // Grace period expired - clear session and return to start screen
                console.log('Grace period expired on load. Clearing session.');
                clearSession();
                localStorage.removeItem('ludo_disconnect_time');
                // Reset to start screen
                if (window.location.hash !== '#/') {
                    window.location.hash = '#/';
                }
            } else {
                // Within grace period
                // If we are on the game screen (Refresh), auto-rejoin!
                if (window.location.hash === '#/game') {
                    console.log('Refreshing game screen - Auto-rejoining...');
                    isRejoining = true;
                    
                    usernameInput.value = savedSession.playerName;
                    
                    socket.emit('join_room', {
                        roomId: savedSession.roomId,
                        password: savedSession.password,
                        color: savedSession.color,
                        playerName: savedSession.playerName
                    });
                    
                    // Show loading indicator
                    showNotification('Restoring game session...', 'info');
                } else {
                    // We are in lobby/start, let grace-period.js show notification
                    console.log(`Session still valid. ${Math.ceil((GRACE_PERIOD_MS - timeSinceDisconnect) / 1000)}s remaining`);
                }
            }
        }
    }

    // Load game stats on page load
    loadGameStats();
    
    // Call handleRoute after session checking to ensure correct screen is shown
    handleRoute();
});

// Function to load and display game stats
async function loadGameStats() {
    try {
        const response = await fetch('/api/sessions/game-stats/ludo');
        if (response.ok) {
            const data = await response.json();
            
            // Update wins display
            const totalWinsEl = document.getElementById('total-wins');
            if (totalWinsEl) {
                totalWinsEl.textContent = data.totalWins || 0;
            }
            
            // Update losses display
            const totalLossesEl = document.getElementById('total-losses');
            if (totalLossesEl) {
                totalLossesEl.textContent = data.totalLosses || 0;
            }
        }
    } catch(error) {
        console.error('Failed to load game stats:', error);
        // Set to 0 on error
        const totalWinsEl = document.getElementById('total-wins');
        const totalLossesEl = document.getElementById('total-losses');
        if (totalWinsEl) totalWinsEl.textContent = '0';
        if (totalLossesEl) totalLossesEl.textContent = '0';
    }
}

// Navigation Event Listeners
if (backToPortalBtn) {
    backToPortalBtn.addEventListener('click', () => {
        window.location.href = '/';
    });
}

if (backToStartBtn) {
    backToStartBtn.addEventListener('click', () => {
        window.location.hash = '#/';
    });
}

if (modeVsPlayerBtn) {
    modeVsPlayerBtn.addEventListener('click', () => {
        window.location.hash = '#/lobby';
    });
}

if (modeVsAiBtn) {
    modeVsAiBtn.addEventListener('click', () => {
        showNotification('AI mode coming soon!', 'info');
    });
}

window.addEventListener('beforeunload', () => {
    if (currentRoomId) {
        localStorage.setItem('ludo_disconnect_time', Date.now().toString());
    }
});

// Socket Events
socket.on('room_list', (rooms) => {
    renderRoomList(rooms);
});

function renderRoomList(rooms) {
    // Update Lobby Summary
    const totalRoomsEl = document.getElementById('total-rooms');
    const availableRoomsEl = document.getElementById('available-rooms');
    
    if (totalRoomsEl) totalRoomsEl.textContent = rooms.length;
    if (availableRoomsEl) {
        const availableCount = rooms.filter(r => r.playerCount < 4).length;
        availableRoomsEl.textContent = availableCount;
    }

    roomListEl.innerHTML = '';
    rooms.forEach(room => {
        const card = document.createElement('div');
        card.className = 'room-card';
        if (room.playerCount >= 4) card.classList.add('full');
        if (room.isActive) card.classList.add('active');
        
        // Add room type class for styling
        if (room.type) {
            card.classList.add(`room-type-${room.type}`);
        }
        
        const colors = ['red', 'blue', 'green', 'yellow'];
        const playerSlots = colors.map(color => {
            const player = room.players[color];
            return `
                <div class="room-player-slot ${player ? '' : 'empty'}">
                    <div class="color-dot ${color}"></div>
                    <span>${player ? player.name : 'Empty'}</span>
                </div>
            `;
        }).join('');

        const status = room.isActive ? 'Active' : (room.playerCount >= 4 ? 'Full' : 'Waiting');
        const typeIcon = room.type === 'public' ? '<i class="fas fa-unlock"></i>' : '<i class="fas fa-lock"></i>';
        const typeLabel = room.type === 'public' ? 'Public' : 'Private';
        const typeBadge = `<span class="room-type-badge ${room.type}">${typeIcon} ${typeLabel}</span>`;

        card.innerHTML = `
            <div class="room-header">
                <h3 class="room-name">${room.name}</h3>
                <span class="room-status ${room.isActive ? 'active' : ''}">${status}</span>
            </div>
            <div class="room-meta">
                ${typeBadge}
            </div>
            <div class="room-players">
                ${playerSlots}
            </div>
        `;
        
        if (room.playerCount < 4) {
            card.addEventListener('click', () => openJoinModal(room));
        }
        
        roomListEl.appendChild(card);
    });
}

function openJoinModal(room) {
    selectedRoomId = room.id;
    modalRoomName.textContent = room.name;
    
    if (room.type === 'public' && room.password) {
        passwordInput.value = room.password;
    } else {
        passwordInput.value = '';
    }
    
    // Reset color selection and show available colors
    const colorOptions = joinModal.querySelectorAll('input[name="color"]');
    colorOptions.forEach(input => {
        const color = input.value;
        const isTaken = room.players[color] !== null;
        input.disabled = isTaken;
        if (isTaken) {
            input.parentElement.style.opacity = '0.5';
        } else {
            input.parentElement.style.opacity = '1';
        }
        input.checked = false;
    });
    
    joinModal.classList.remove('hidden');
}

cancelJoinBtn.addEventListener('click', () => {
    joinModal.classList.add('hidden');
    selectedRoomId = null;
});

confirmJoinBtn.addEventListener('click', () => {
    const name = usernameInput.value.trim();
    const password = passwordInput.value;
    const colorInput = joinModal.querySelector('input[name="color"]:checked');
    
    if (!name || name.length < 3 || name.length > 10) {
        return showNotification('Name must be 3-10 characters', 'error');
    }
    
    if (!/^[a-zA-Z0-9]+$/.test(name)) {
        return showNotification('Name must be alphanumeric only', 'error');
    }
    
    if (!colorInput) {
        return showNotification('Please select a color', 'error');
    }
    
    const color = colorInput.value;
    
    socket.emit('join_room', {
        roomId: selectedRoomId,
        password,
        color,
        playerName: name
    });
    
    joinModal.classList.add('hidden');
});

socket.on('error', (message) => {
    showNotification(message, 'error');
    isRejoining = false; // Clear rejoining state on error
    joinModal.classList.add('hidden');
});

socket.on('joined_room', (data) => {
    currentRoomId = data.roomId;
    myColor = data.color;
    
    // Fix: Get name from server response or saved session to handle refresh correctly
    if (data.players && data.players[myColor]) {
        myName = data.players[myColor].name;
    } else {
        const saved = loadSession();
        myName = usernameInput.value || (saved ? saved.playerName : 'Player');
    }
    
    // Update input for consistency
    usernameInput.value = myName;
    
    gameState = data.gameState;
    
    const savedSession = loadSession();
    const password = passwordInput.value || (savedSession?.password || '');
    saveSession(data.roomId, myName, myColor, password);
    
    lobbyScreen.classList.add('hidden');
    gameScreen.classList.remove('hidden');
    window.location.hash = '#/game';
    
    updatePlayerInfo(data.players);
    updateUI();
    
    // Initialize chatbox
    if (!chatbox) {
        chatbox = new Chatbox({
            socket: socket,
            roomId: currentRoomId,
            playerName: myName,
            playerRole: myColor,
            roleEmojis: {
                'red': '🔴',
                'blue': '🔵',
                'green': '🟢',
                'yellow': '🟡'
            }
        });
    } else {
        chatbox.updateConfig({
            roomId: currentRoomId,
            playerName: myName,
            playerRole: myColor,
            roleEmojis: {
                'red': '🔴',
                'blue': '🔵',
                'green': '🟢',
                'yellow': '🟡'
            }
        });
    }
    
    // Load chat history if available
    if (data.chatHistory && data.chatHistory.length > 0) {
        chatbox.loadHistory(data.chatHistory);
    }
    
    chatbox.show();
    
    showNotification('Joined room successfully!', 'success');
});

socket.on('player_update', (players) => {
    updatePlayerInfo(players);
});

socket.on('player_status_update', (data) => {
    updatePlayerInfo(data.players);
});


socket.on('connect', () => {
    console.log('Connected to server');
    // Join room if ID exists in URL
    const urlParams = new URLSearchParams(window.location.search);
    const roomId = urlParams.get('room');
    if (roomId) {
        joinRoom(roomId);
    }
});

socket.on('room_joined', (data) => {
    currentRoomId = data.roomId;
    myColor = data.color;
    gameState = data.gameState;
    
    // Hide lobby, show game
    document.getElementById('lobby-screen').classList.add('hidden');
    document.getElementById('game-screen').classList.remove('hidden');
    
    // Update UI
    updatePlayerInfo(data.players);
    drawBoard();
    
    // Update dice if value exists
    if (gameState.diceValue) {
        diceCube.className = 'cube'; // Reset classes
        diceCube.classList.add(`show-${gameState.diceValue}`);
    }
    
    // Update turn indicator
    updateTurnIndicator();
});

socket.on('player_update', (players) => {
    updatePlayerInfo(players);
});

socket.on('game_start', (data) => {
    // Handle both old and new format
    gameState = data.gameState || data;
    currentMatchId = data.matchId || currentRoomId;
    previousGameState = JSON.parse(JSON.stringify(gameState));
    
    updateUI();
    gameOverModal.classList.add('hidden');
    showNotification('Game Started!', 'info');
    
    // Track game start with unique match ID
    gameStartTime = Date.now();
    if (typeof trackGameStart === 'function') {
        trackGameStart('ludo', {
            matchId: currentMatchId
        });
    }
    
    if (chatbox) {
        chatbox.clearMessages();
    }
});

socket.on('dice_rolled', (data) => {
    if (!gameState) return;
    
    gameState.diceValue = data.diceValue;
    
    // Animate dice
    diceCube.className = 'cube rolling'; // Start rolling animation
    
    setTimeout(() => {
        diceCube.classList.remove('rolling');
        diceCube.classList.add(`show-${data.diceValue}`); // Show result face
    }, 600); // Match CSS animation duration
    
    // Redraw board to show possible moves
    drawBoard();
    
    if (data.extraTurn) {
        showNotification(`${data.player} rolled a 6! Extra turn!`, 'info');
    }
    
    // Update UI to show valid moves immediately
    updateUI();
});

// Store previous gameState for animation detection
let previousGameState = null;
let animatingPiece = null; // {color, pieceIndex, currentPos, targetPos, pathIndex, path}

socket.on('update_game', (data) => {
    const newGameState = data.gameState;
    
    // Detect piece movement for animation
    if (previousGameState && !animatingPiece) {
        const movement = detectPieceMovement(previousGameState, newGameState);
        
        if (movement && movement.fromPos !== -1 && movement.toPos !== -1) {
            // Build path for animation
            const path = buildPath(movement.color, movement.fromPos, movement.toPos);
            
            if (path.length > 0) {
                // Start animation
                animatingPiece = {
                    color: movement.color,
                    pieceIndex: movement.pieceIndex,
                    path: path,
                    pathIndex: 0,
                    targetPos: movement.toPos
                };
                
                // Update game state immediately (so turn switches properly)
                gameState = newGameState;
                previousGameState = JSON.parse(JSON.stringify(newGameState));
                updateUI();
                
                // Start the animation loop
                animateNextStep();
                return;
            }
        }
    }
    
    // No animation needed, just update
    previousGameState = JSON.parse(JSON.stringify(newGameState));
    gameState = newGameState;
    updateUI();
});

socket.on('game_over', (data) => {
    gameState.winner = data.winner;
    
    // Track game end with result
    if (typeof trackGameEnd === 'function' && gameStartTime && myColor) {
        const duration = Date.now() - gameStartTime;
        const myRanking = data.rankings.find(r => r.color === myColor);
        let result;
        
        if (myRanking) {
            // In Ludo, 1st = win, 2nd-4th = loss (or we can use 'place-N')
            result = myRanking.rank === 1 ? 'win' : 'loss';
        } else {
            result = 'abandoned';
        }
        
        trackGameEnd('ludo', duration, {
            metrics: {
                playerRole: myColor,
                rank: myRanking ? myRanking.rank : null,
                piecesFinished: myRanking ? (myRanking.piecesFinished || 0) : 0,
                result: result
            },
            matchId: currentMatchId
        });
        gameStartTime = null;
    }
    
    // Build rankings display
    let rankingsHtml = '<div style="margin-top: 1.5rem;"><h3 style="margin-bottom: 1rem;">Final Rankings:</h3><div style="display: flex; flex-direction: column; gap: 0.75rem;">';
    
    data.rankings.forEach(ranking => {
        const medal = ranking.rank === 1 ? '🥇' : ranking.rank === 2 ? '🥈' : ranking.rank === 3 ? '🥉' : '🏁';
        const colorEmoji = { red: '🔴', blue: '🔵', green: '🟢', yellow: '🟡' }[ranking.color];
        
        // Get player name from the DOM
        const playerCard = document.getElementById(`player-${ranking.color}`);
        const playerName = playerCard ? playerCard.querySelector('.player-name').textContent : ranking.color;
        
        rankingsHtml += `
            <div style="display: flex; align-items: center; gap: 1rem; padding: 0.75rem; background: rgba(0,0,0,0.2); border-radius: 8px;">
                <span style="font-size: 1.5rem;">${medal}</span>
                <span style="font-size: 1.2rem; font-weight: 600;">${ranking.rank}${ranking.rank === 1 ? 'st' : ranking.rank === 2 ? 'nd' : ranking.rank === 3 ? 'rd' : 'th'}</span>
                <span style="font-size: 1.5rem;">${colorEmoji}</span>
                <div style="display: flex; flex-direction: column; align-items: flex-start;">
                    <span style="font-size: 1.1rem; font-weight: 600;">${playerName}</span>
                    <span style="font-size: 0.8rem; opacity: 0.7; text-transform: capitalize;">${ranking.color}</span>
                </div>
            </div>
        `;
    });
    
    rankingsHtml += '</div></div>';
    
    gameOverTitle.textContent = data.winner.toUpperCase() + ' WINS!';
    gameOverMessage.innerHTML = `Congratulations to ${data.winner}!${rankingsHtml}`;
    gameOverModal.classList.remove('hidden');
    restartBtn.classList.remove('hidden');
    
    // Reload stats to show updated counts
    loadGameStats();
});

socket.on('player_left', (data) => {
    showNotification(`${data.color} player left`, 'error');
});

socket.on('player_finished', (data) => {
    const medal = data.rank === 1 ? '🥇' : data.rank === 2 ? '🥈' : data.rank === 3 ? '🥉' : '🏁';
    const rankSuffix = data.rank === 1 ? 'st' : data.rank === 2 ? 'nd' : data.rank === 3 ? 'rd' : 'th';
    showNotification(`${medal} ${data.color.toUpperCase()} finished ${data.rank}${rankSuffix} place!`, 'success');
});

socket.on('error', (message) => {
    // Don't show "Invalid move" notifications as they're too spammy
    if (message === 'Invalid move') return;
    showNotification(message, 'error');
});

socket.on('chat_cleared', () => {
    if (chatbox) {
        chatbox.clearMessages();
    }
});

// Game Controls


restartBtn.addEventListener('click', () => {
    socket.emit('restart_game', { roomId: currentRoomId });
});

playAgainBtn.addEventListener('click', () => {
    socket.emit('restart_game', { roomId: currentRoomId });
    gameOverModal.classList.add('hidden');
});

rollDiceBtn.addEventListener('click', () => {
    if (!gameState || !gameState.gameActive) return;
    if (gameState.currentTurn !== myColor) return;
    if (gameState.diceValue !== null) return;
    
    socket.emit('roll_dice', { roomId: currentRoomId });
});

// Board Click Handler
gameBoard.addEventListener('click', (e) => {
    if (!gameState || !gameState.gameActive) return;
    if (gameState.currentTurn !== myColor) return;
    if (gameState.diceValue === null) return;
    
    const rect = gameBoard.getBoundingClientRect();
    const scaleX = gameBoard.width / rect.width;
    const scaleY = gameBoard.height / rect.height;
    
    const x = (e.clientX - rect.left) * scaleX;
    const y = (e.clientY - rect.top) * scaleY;
    
    const pieceIndex = getPieceAtClick(x, y, myColor);
    
    if (pieceIndex >= 0) {
        socket.emit('move_piece', { 
            roomId: currentRoomId,
            pieceIndex,
            steps: gameState.diceValue
        });
    }
});



// UI Updates
function updatePlayerInfo(players) {
    // Update player cards for all colors
    ['red', 'blue', 'green', 'yellow'].forEach(color => {
        const card = document.querySelector(`.player-card[data-color="${color}"]`);
        if (!card) return;
        
        const player = players[color];
        const nameEl = card.querySelector('.player-name');
        
        if (player) {
            nameEl.textContent = player.name;
            card.classList.remove('away');
            card.classList.add('online');
            
            // Update card status based on player status
            if (player.status === 'disconnected') {
                card.classList.remove('online');
                card.classList.add('away');
            }
        } else {
            nameEl.textContent = 'Waiting...';
            card.classList.remove('online', 'away');
        }
    });
}

// Visibility Change Handler
let isActive = true;

document.addEventListener('visibilitychange', () => {
    isActive = !document.hidden;
    if (currentRoomId) {
        socket.emit('player_status', { 
            roomId: currentRoomId, 
            status: isActive ? 'online' : 'away' 
        });
    }
});

window.addEventListener('blur', () => {
    if (currentRoomId && isActive) {
        isActive = false;
        socket.emit('player_status', { 
            roomId: currentRoomId, 
            status: 'away' 
        });
    }
});

window.addEventListener('focus', () => {
    if (currentRoomId && !isActive) {
        isActive = true;
        socket.emit('player_status', { 
            roomId: currentRoomId, 
            status: 'online' 
        });
    }
});

socket.on('player_status_update', (data) => {
    updatePlayerInfo(data.players);
});

// Detect which piece moved between two game states
function detectPieceMovement(oldState, newState) {
    const colors = ['red', 'blue', 'green', 'yellow'];
    
    for (const color of colors) {
        const oldPieces = oldState.board[color];
        const newPieces = newState.board[color];
        
        for (let i = 0; i < oldPieces.length; i++) {
            if (oldPieces[i] !== newPieces[i]) {
                // Found a piece that moved
                return {
                    color,
                    pieceIndex: i,
                    fromPos: oldPieces[i],
                    toPos: newPieces[i]
                };
            }
        }
    }
    
    return null;
}

// Animate the next step of the moving piece
function animateNextStep() {
    if (!animatingPiece) return;
    
    const stepDuration = 400; // ms per step (increased from 150ms for better visibility)
    
    if (animatingPiece.pathIndex >= animatingPiece.path.length) {
        // Animation complete
        animatingPiece = null;
        drawBoard();
        return;
    }
    
    // Redraw with current animation position
    drawBoard();
    
    // Move to next step
    animatingPiece.pathIndex++;
    setTimeout(animateNextStep, stepDuration);
}

// Build path from fromPos to toPos
function buildPath(color, fromPos, toPos) {
    const path = [];
    
    // Handle different movement scenarios
    if (fromPos === -1 && toPos >= 0) {
        // Entering board from home - just show the target position
        path.push(toPos);
    } else if (toPos === 100) {
        // Reaching finish - animate to position 57, then jump to 100
        // Don't animate through positions 58-99 as they don't exist
        path.push(fromPos);
        const maxPos = Math.min(fromPos + 10, 57); // Limit to position 57
        for (let pos = fromPos + 1; pos <= maxPos; pos++) {
            path.push(pos);
        }
        // Final position will be set by game state, animation stops at 57 or earlier
        path.push(100);
    } else if (fromPos >= 52 && toPos >= 52) {
        // Movement within home stretch
        path.push(fromPos);
        for (let pos = fromPos + 1; pos <= toPos; pos++) {
            path.push(pos);
        }
    } else if (fromPos < 52 && toPos >= 52) {
        // Entering home stretch from outer track
        // We need to animate from current position -> entry point -> home stretch start (52) -> target
        
        const entryPoints = {
            red: 51,
            blue: 12,
            green: 25,
            yellow: 38
        };
        const entryPoint = entryPoints[color];
        
        path.push(fromPos);
        
        // Part 1: Move to entry point (handling wrap-around)
        if (entryPoint >= fromPos) {
            // No wrap needed (e.g. 10 -> 12)
            for (let pos = fromPos + 1; pos <= entryPoint; pos++) {
                path.push(pos);
            }
        } else {
            // Wrap needed (e.g. 50 -> 12)
            // Go to end of track (51)
            for (let pos = fromPos + 1; pos <= 51; pos++) {
                path.push(pos);
            }
            // Wrap to 0 and go to entry point
            for (let pos = 0; pos <= entryPoint; pos++) {
                path.push(pos);
            }
        }
        
        // Part 2: Enter home stretch (52 to toPos)
        for (let pos = 52; pos <= toPos; pos++) {
            path.push(pos);
        }
    } else if (fromPos >= 0 && fromPos < 52 && toPos >= 0 && toPos < 52) {
        // Movement on outer track only
        if (toPos > fromPos) {
            // Normal forward movement (no wrap)
            path.push(fromPos);
            for (let pos = fromPos + 1; pos <= toPos; pos++) {
                path.push(pos);
            }
        } else {
            // Wrap around (e.g., from 50 to 3)
            path.push(fromPos);
            // Go to end of track
            for (let pos = fromPos + 1; pos <= 51; pos++) {
                path.push(pos);
            }
            // Wrap to beginning
            for (let pos = 0; pos <= toPos; pos++) {
                path.push(pos);
            }
        }
    }
    
    return path;
}

function updateUI() {
    if (!gameState) return;
    
    // Update turn indicator
    if (gameState.gameActive) {
        const isMyTurn = gameState.currentTurn === myColor;
        turnIndicator.textContent = isMyTurn ? 'Your Turn!' : `${gameState.currentTurn}'s Turn`;
        turnIndicator.style.color = `var(--color-${gameState.currentTurn})`;
        
        // Highlight active player
        const colors = ['red', 'blue', 'green', 'yellow'];
        colors.forEach(color => {
            const card = document.getElementById(`player-${color}`);
            if (color === gameState.currentTurn) {
                card.classList.add('active');
            } else {
                card.classList.remove('active');
            }
        });
        
        // Enable/disable dice button and scene
        const shouldDisable = !isMyTurn || gameState.diceValue !== null;
        rollDiceBtn.disabled = shouldDisable;
        if (shouldDisable) {
            rollDiceBtn.setAttribute('disabled', 'true');
        } else {
            rollDiceBtn.removeAttribute('disabled');
        }
    } else {
        turnIndicator.textContent = 'Waiting...';
        rollDiceBtn.disabled = true;
        rollDiceBtn.setAttribute('disabled', 'true');
    }
    
    // Draw board
    drawBoard();
}

function drawBoard() {
    const size = 600;
    const cellSize = size / 15; // 15x15 grid
    
    // Clear canvas
    ctx.fillStyle = '#1a1f35';
    ctx.fillRect(0, 0, size, size);
    
    // Draw cross-shaped board
    drawBoardStructure(cellSize);
    
    // Draw pieces
    drawPieces(cellSize);
    
    // Dice value is handled by event listeners directly to support animation
}

function drawBoardStructure(cellSize) {
    const colors = {
        red: '#ef4444',
        blue: '#3b82f6',
        green: '#22c55e',
        yellow: '#eab308',
        white: '#ffffff',
        safe: 'rgba(0,0,0,0.1)'
    };
    
    // Draw home areas (corners)
    const homeSize = cellSize * 6;
    
    // Red (top-left)
    ctx.fillStyle = colors.red;
    ctx.fillRect(0, 0, homeSize, homeSize);
    // Red Home Inner White
    ctx.fillStyle = colors.white;
    ctx.fillRect(cellSize, cellSize, cellSize * 4, cellSize * 4);
    
    // Blue (top-right)
    ctx.fillStyle = colors.blue;
    ctx.fillRect(600 - homeSize, 0, homeSize, homeSize);
    // Blue Home Inner White
    ctx.fillStyle = colors.white;
    ctx.fillRect(600 - homeSize + cellSize, cellSize, cellSize * 4, cellSize * 4);
    
    // Green (bottom-left) - Wait, Green is usually Bottom-Right in standard? 
    // Server says: Red=0, Blue=13, Green=26, Yellow=39.
    // My path: 0=(1,6) [Top-Leftish], 13=(8,1) [Top-Rightish], 26=(13,8) [Bottom-Rightish], 39=(6,13) [Bottom-Leftish]
    // So: Red=TL, Blue=TR, Green=BR, Yellow=BL.
    // BUT the previous code had Green=BL, Yellow=BR.
    // Let's stick to Server Logic:
    // Red Start=0 (1,6). Blue Start=13 (8,1). Green Start=26 (13,8). Yellow Start=39 (6,13).
    // (1,6) is near TL. (8,1) is near TR. (13,8) is near BR. (6,13) is near BL.
    // So: Red=TL, Blue=TR, Green=BR, Yellow=BL.
    // Previous code: Green=BL, Yellow=BR.
    // I will adjust the corners to match the path.
    
    // Green (bottom-right)
    ctx.fillStyle = colors.green;
    ctx.fillRect(600 - homeSize, 600 - homeSize, homeSize, homeSize);
    ctx.fillStyle = colors.white;
    ctx.fillRect(600 - homeSize + cellSize, 600 - homeSize + cellSize, cellSize * 4, cellSize * 4);
    
    // Yellow (bottom-left)
    ctx.fillStyle = colors.yellow;
    ctx.fillRect(0, 600 - homeSize, homeSize, homeSize);
    ctx.fillStyle = colors.white;
    ctx.fillRect(cellSize, 600 - homeSize + cellSize, cellSize * 4, cellSize * 4);
    
    // Draw Center
    ctx.fillStyle = '#1a1f35'; // Dark center
    ctx.beginPath();
    ctx.moveTo(6 * cellSize, 6 * cellSize);
    ctx.lineTo(9 * cellSize, 6 * cellSize);
    ctx.lineTo(9 * cellSize, 9 * cellSize);
    ctx.lineTo(6 * cellSize, 9 * cellSize);
    ctx.closePath();
    ctx.fill();
    
    // Draw Triangles in Center
    // Red Triangle (Left)
    ctx.fillStyle = colors.red;
    ctx.beginPath();
    ctx.moveTo(6 * cellSize, 6 * cellSize);
    ctx.lineTo(7.5 * cellSize, 7.5 * cellSize);
    ctx.lineTo(6 * cellSize, 9 * cellSize);
    ctx.fill();
    
    // Blue Triangle (Top)
    ctx.fillStyle = colors.blue;
    ctx.beginPath();
    ctx.moveTo(6 * cellSize, 6 * cellSize);
    ctx.lineTo(9 * cellSize, 6 * cellSize);
    ctx.lineTo(7.5 * cellSize, 7.5 * cellSize);
    ctx.fill();
    
    // Green Triangle (Right)
    ctx.fillStyle = colors.green;
    ctx.beginPath();
    ctx.moveTo(9 * cellSize, 6 * cellSize);
    ctx.lineTo(9 * cellSize, 9 * cellSize);
    ctx.lineTo(7.5 * cellSize, 7.5 * cellSize);
    ctx.fill();
    
    // Yellow Triangle (Bottom)
    ctx.fillStyle = colors.yellow;
    ctx.beginPath();
    ctx.moveTo(6 * cellSize, 9 * cellSize);
    ctx.lineTo(9 * cellSize, 9 * cellSize);
    ctx.lineTo(7.5 * cellSize, 7.5 * cellSize);
    ctx.fill();
    
    // Draw Grid Cells
    ctx.strokeStyle = '#000';
    ctx.lineWidth = 1;
    
    // Draw all 52 path cells
    LUDO_PATH.forEach((pos, index) => {
        ctx.fillStyle = 'white';
        // Safe spots (Star)
        const isSafe = [0, 8, 13, 21, 26, 34, 39, 47].includes(index);
        if (isSafe) {
            ctx.fillStyle = '#e2e8f0';
        }
        // Colored start spots
        if (index === 0) ctx.fillStyle = colors.red;
        if (index === 13) ctx.fillStyle = colors.blue;
        if (index === 26) ctx.fillStyle = colors.green;
        if (index === 39) ctx.fillStyle = colors.yellow;
        
        const x = pos.x * cellSize;
        const y = pos.y * cellSize;
        
        ctx.fillRect(x, y, cellSize, cellSize);
        ctx.strokeRect(x, y, cellSize, cellSize);
        
        // Draw Star on Safe Spots (excluding start spots which get arrows)
        if ([8, 21, 34, 47].includes(index)) {
            drawStar(x + cellSize/2, y + cellSize/2, cellSize * 0.3, '#64748b');
        }
        
        // Draw Arrows on Start Spots
        if (index === 0) drawArrow(x + cellSize/2, y + cellSize/2, cellSize * 0.6, 'right', 'white');
        if (index === 13) drawArrow(x + cellSize/2, y + cellSize/2, cellSize * 0.6, 'down', 'white');
        if (index === 26) drawArrow(x + cellSize/2, y + cellSize/2, cellSize * 0.6, 'left', 'white');
        if (index === 39) drawArrow(x + cellSize/2, y + cellSize/2, cellSize * 0.6, 'up', 'white');
        
        // Small directional arrows at corners (like traditional Ludo)
        // Top corners
        if (index === 11) drawTriangle(x + cellSize/2, y + cellSize/2, cellSize * 0.3, 'right', 'rgba(100,100,100,0.5)');
        if (index === 12) drawTriangle(x + cellSize/2, y + cellSize/2, cellSize * 0.3, 'down', 'rgba(100,100,100,0.5)');
        
        // Right corners
        if (index === 24) drawTriangle(x + cellSize/2, y + cellSize/2, cellSize * 0.3, 'down', 'rgba(100,100,100,0.5)');
        if (index === 25) drawTriangle(x + cellSize/2, y + cellSize/2, cellSize * 0.3, 'left', 'rgba(100,100,100,0.5)');
        
        // Bottom corners
        if (index === 37) drawTriangle(x + cellSize/2, y + cellSize/2, cellSize * 0.3, 'left', 'rgba(100,100,100,0.5)');
        if (index === 38) drawTriangle(x + cellSize/2, y + cellSize/2, cellSize * 0.3, 'up', 'rgba(100,100,100,0.5)');
        
        // Left corners
        if (index === 50) drawTriangle(x + cellSize/2, y + cellSize/2, cellSize * 0.3, 'up', 'rgba(100,100,100,0.5)');
        if (index === 51) drawTriangle(x + cellSize/2, y + cellSize/2, cellSize * 0.3, 'right', 'rgba(100,100,100,0.5)');
    });
    
    // Draw small arrows indicating home stretch entries (on the cells before entry)
    // These guide players to know when they're about to enter home
    const pos6 = LUDO_PATH[6];
    drawTriangle(pos6.x * cellSize + cellSize/2, pos6.y * cellSize + cellSize/2, cellSize * 0.25, 'up', 'rgba(239, 68, 68, 0.6)');
    
    const pos19 = LUDO_PATH[19];
    drawTriangle(pos19.x * cellSize + cellSize/2, pos19.y * cellSize + cellSize/2, cellSize * 0.25, 'right', 'rgba(59, 130, 246, 0.6)');
    
    const pos32 = LUDO_PATH[32];
    drawTriangle(pos32.x * cellSize + cellSize/2, pos32.y * cellSize + cellSize/2, cellSize * 0.25, 'down', 'rgba(34, 197, 94, 0.6)');
    
    const pos45 = LUDO_PATH[45];
    drawTriangle(pos45.x * cellSize + cellSize/2, pos45.y * cellSize + cellSize/2, cellSize * 0.25, 'left', 'rgba(234, 179, 8, 0.6)');
    
    // Draw Home Stretch Cells
    // Red (Row 7, Cols 1-5)
    for(let i=1; i<=5; i++) {
        ctx.fillStyle = colors.red;
        ctx.fillRect(i * cellSize, 7 * cellSize, cellSize, cellSize);
        ctx.strokeRect(i * cellSize, 7 * cellSize, cellSize, cellSize);
    }
    
    // Blue (Col 7, Rows 1-5)
    for(let i=1; i<=5; i++) {
        ctx.fillStyle = colors.blue;
        ctx.fillRect(7 * cellSize, i * cellSize, cellSize, cellSize);
        ctx.strokeRect(7 * cellSize, i * cellSize, cellSize, cellSize);
    }
    
    // Green (Row 7, Cols 13-9) -> 9-13
    for(let i=9; i<=13; i++) {
        ctx.fillStyle = colors.green;
        ctx.fillRect(i * cellSize, 7 * cellSize, cellSize, cellSize);
        ctx.strokeRect(i * cellSize, 7 * cellSize, cellSize, cellSize);
    }
    
    // Yellow (Col 7, Rows 13-9) -> 9-13
    for(let i=9; i<=13; i++) {
        ctx.fillStyle = colors.yellow;
        ctx.fillRect(7 * cellSize, i * cellSize, cellSize, cellSize);
        ctx.strokeRect(7 * cellSize, i * cellSize, cellSize, cellSize);
    }
}

function drawPieces(cellSize) {
    if (!gameState) return;
    
    const colors = {
        red: '#ef4444',
        blue: '#3b82f6',
        green: '#22c55e',
        yellow: '#eab308'
    };
    
    // Darker shades for 3D gradient
    const darkColors = {
        red: '#991b1b',
        blue: '#1e40af',
        green: '#166534',
        yellow: '#854d0e'
    };
    
    const playerColors = ['red', 'blue', 'green', 'yellow'];
    
    // Helper to draw a single 3D piece
    const draw3DPiece = (color, x, y, isAnimating = false) => {
        const radius = cellSize * 0.35;
        
        ctx.save();
        
        // 1. Drop Shadow
        ctx.shadowColor = 'rgba(0, 0, 0, 0.4)';
        ctx.shadowBlur = isAnimating ? 8 : 4;
        ctx.shadowOffsetX = isAnimating ? 3 : 2;
        ctx.shadowOffsetY = isAnimating ? 3 : 2;
        
        // 2. Main Body (Radial Gradient for 3D sphere effect)
        ctx.beginPath();
        ctx.arc(x, y, radius, 0, Math.PI * 2);
        
        // Create gradient from top-left (light) to bottom-right (dark)
        const gradient = ctx.createRadialGradient(
            x - radius * 0.3, y - radius * 0.3, radius * 0.1, // Inner circle (highlight)
            x, y, radius // Outer circle
        );
        
        gradient.addColorStop(0, colors[color]); // Light color at highlight
        gradient.addColorStop(1, darkColors[color]); // Dark color at edges
        
        ctx.fillStyle = gradient;
        ctx.fill();
        
        // Reset shadow for subsequent drawing
        ctx.shadowColor = 'transparent';
        ctx.shadowBlur = 0;
        ctx.shadowOffsetX = 0;
        ctx.shadowOffsetY = 0;
        
        // 3. Specular Highlight (Glossy reflection)
        ctx.beginPath();
        ctx.ellipse(
            x - radius * 0.3, 
            y - radius * 0.3, 
            radius * 0.15, 
            radius * 0.1, 
            Math.PI / 4, 
            0, 
            Math.PI * 2
        );
        ctx.fillStyle = 'rgba(255, 255, 255, 0.4)';
        ctx.fill();
        
        // 4. Border (Subtle rim)
        ctx.beginPath();
        ctx.arc(x, y, radius, 0, Math.PI * 2);
        ctx.strokeStyle = 'rgba(255, 255, 255, 0.3)';
        ctx.lineWidth = 1;
        ctx.stroke();
        
        ctx.restore();
    };
    
    // Group pieces by position to handle overlaps
    const piecesByPosition = new Map();
    
    playerColors.forEach(color => {
        const pieces = gameState.board[color];
        pieces.forEach((position, index) => {
            // Skip pieces in home (-1) or finished (100) - they have their own fixed positions
            // Also skip animating piece
            if (position === -1 || position === 100 || 
                (animatingPiece && animatingPiece.color === color && animatingPiece.pieceIndex === index)) {
                return;
            }
            
            if (!piecesByPosition.has(position)) {
                piecesByPosition.set(position, []);
            }
            piecesByPosition.get(position).push({ color, index });
        });
    });

    // Draw pieces
    playerColors.forEach(color => {
        const pieces = gameState.board[color];
        pieces.forEach((position, index) => {
            // Skip the animating piece
            if (animatingPiece && 
                animatingPiece.color === color && 
                animatingPiece.pieceIndex === index) {
                return;
            }
            
            let { x, y } = getPiecePosition(color, position, index);
            
            // Apply offset if multiple pieces are at this position (and not in base/home)
            if (position !== -1 && position !== 100 && piecesByPosition.has(position)) {
                const piecesAtPos = piecesByPosition.get(position);
                if (piecesAtPos.length > 1) {
                    // Find index of this piece in the group
                    const groupIndex = piecesAtPos.findIndex(p => p.color === color && p.index === index);
                    
                    // Calculate offset based on group size and index
                    // Create a small circle pattern for overlaps
                    const offsetRadius = cellSize * 0.15;
                    const angle = (Math.PI * 2 * groupIndex) / piecesAtPos.length;
                    
                    x += Math.cos(angle) * offsetRadius;
                    y += Math.sin(angle) * offsetRadius;
                }
            }
            
            // Check if piece should be highlighted (playable)
            let isPlayable = false;
            if (color === myColor && gameState.currentTurn === myColor && gameState.diceValue !== null) {
                if (position === 100) {
                    isPlayable = false;
                } else if (position === -1) {
                    isPlayable = (gameState.diceValue === 1 || gameState.diceValue === 6);
                } else {
                    const getSteps = (pos) => {
                        if (pos >= 52) return pos;
                        const startPos = { red: 0, blue: 13, green: 26, yellow: 39 }[color];
                        let steps;
                        if (pos >= startPos) {
                            steps = pos - startPos;
                        } else {
                            steps = (52 - startPos) + pos;
                        }
                        return steps;
                    };
                    const currentSteps = getSteps(position);
                    isPlayable = (currentSteps + gameState.diceValue <= 57);
                }
            }

            // Draw Glow BEHIND the piece if playable
            if (isPlayable) {
                ctx.save();
                const time = Date.now() / 300; 
                const pulse = (Math.sin(time) + 1) / 2; // 0 to 1
                
                // Soft, radiant glow
                const maxRadius = cellSize * 0.6 + (pulse * cellSize * 0.1);
                const gradient = ctx.createRadialGradient(x, y, cellSize * 0.2, x, y, maxRadius);
                
                // Purple/Violet glow fading to transparent
                // Using a vibrant purple that stands out well on white
                gradient.addColorStop(0, 'rgba(147, 51, 234, 0.8)'); // Purple center (Tailwind purple-600)
                gradient.addColorStop(0.5, 'rgba(168, 85, 247, 0.4)'); // Violet mid (Tailwind purple-500)
                gradient.addColorStop(1, 'rgba(168, 85, 247, 0)'); // Transparent edge
                
                ctx.fillStyle = gradient;
                ctx.beginPath();
                ctx.arc(x, y, maxRadius, 0, Math.PI * 2);
                ctx.fill();
                
                ctx.restore();
            }
            
            draw3DPiece(color, x, y);
        });
    });
    
    // Draw the animating piece last (on top of everything)
    if (animatingPiece && animatingPiece.pathIndex < animatingPiece.path.length) {
        const color = animatingPiece.color;
        const index = animatingPiece.pieceIndex;
        const drawPosition = animatingPiece.path[animatingPiece.pathIndex];
        
        const { x, y } = getPiecePosition(color, drawPosition, index);
        
        // Draw animating piece with slightly larger shadow/lift
        draw3DPiece(color, x, y, true);
    }
}

function getPiecePosition(color, position, pieceIndex) {
    const size = 600;
    const cellSize = size / 15;
    
    if (position === -1) {
        // In home (Inner White Squares)
        const homeOffsets = {
            red: { x: cellSize * 2, y: cellSize * 2 },
            blue: { x: size - cellSize * 4, y: cellSize * 2 },
            green: { x: size - cellSize * 4, y: size - cellSize * 4 },
            yellow: { x: cellSize * 2, y: size - cellSize * 4 }
        };
        
        const offset = homeOffsets[color];
        const gridX = (pieceIndex % 2) * cellSize * 1.5;
        const gridY = Math.floor(pieceIndex / 2) * cellSize * 1.5;
        
        return {
            x: offset.x + gridX,
            y: offset.y + gridY
        };
    } else if (position === 100) {
        // Finished - center triangles
        const centerOffsets = {
            red: { x: cellSize * 6.5, y: cellSize * 7.5 },
            blue: { x: cellSize * 7.5, y: cellSize * 6.5 },
            green: { x: cellSize * 8.5, y: cellSize * 7.5 },
            yellow: { x: cellSize * 7.5, y: cellSize * 8.5 }
        };
        return centerOffsets[color];
    } else {
        // On board
        if (position < 52) {
            // Main track
            const pos = LUDO_PATH[position];
            return {
                x: pos.x * cellSize + cellSize / 2,
                y: pos.y * cellSize + cellSize / 2
            };
        } else {
            // Home stretch (52-57)
            const steps = position - 51; // 1 to 6
            let x, y;
            
            if (color === 'red') {
                x = steps;
                y = 7;
            } else if (color === 'blue') {
                x = 7;
                y = steps;
            } else if (color === 'green') {
                x = 14 - steps;
                y = 7;
            } else if (color === 'yellow') {
                x = 7;
                y = 14 - steps;
            }
            
            return {
                x: x * cellSize + cellSize / 2,
                y: y * cellSize + cellSize / 2
            };
        }
    }
}

function getPieceAtClick(clickX, clickY, playerColor) {
    if (!gameState) return -1;
    
    const cellSize = 600 / 15;
    const pieces = gameState.board[playerColor];
    
    for (let i = 0; i < 4; i++) {
        const { x, y } = getPiecePosition(playerColor, pieces[i], i);
        const distance = Math.sqrt((clickX - x) ** 2 + (clickY - y) ** 2);
        
        if (distance < cellSize * 0.5) {
            return i;
        }
    }
    
    return -1;
}

// Notifications
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.textContent = message;
    
    const container = document.getElementById('notification-container');
    container.appendChild(notification);
    
    setTimeout(() => {
        notification.style.opacity = '0';
        setTimeout(() => notification.remove(), 300);
    }, 3000);
}

// Initialize
socket.emit('get_rooms');
drawBoardStructure(600/15); // Initial draw
drawBoard();

function drawStar(cx, cy, outerRadius, color) {
    const innerRadius = outerRadius / 2;
    const spikes = 5;
    
    let rot = Math.PI / 2 * 3;
    let x = cx;
    let y = cy;
    let step = Math.PI / spikes;

    ctx.beginPath();
    ctx.moveTo(cx, cy - outerRadius);
    for (let i = 0; i < spikes; i++) {
        x = cx + Math.cos(rot) * outerRadius;
        y = cy + Math.sin(rot) * outerRadius;
        ctx.lineTo(x, y);
        rot += step;

        x = cx + Math.cos(rot) * innerRadius;
        y = cy + Math.sin(rot) * innerRadius;
        ctx.lineTo(x, y);
        rot += step;
    }
    ctx.lineTo(cx, cy - outerRadius);
    ctx.closePath();
    ctx.fillStyle = color;
    ctx.fill();
}

function drawArrow(x, y, size, direction, color) {
    ctx.save();
    ctx.translate(x, y);
    if (direction === 'right') ctx.rotate(0);
    if (direction === 'down') ctx.rotate(Math.PI / 2);
    if (direction === 'left') ctx.rotate(Math.PI);
    if (direction === 'up') ctx.rotate(-Math.PI / 2);
    
    ctx.beginPath();
    ctx.moveTo(-size/2, -size/4);
    ctx.lineTo(0, -size/4);
    ctx.lineTo(0, -size/2);
    ctx.lineTo(size/2, 0);
    ctx.lineTo(0, size/2);
    ctx.lineTo(0, size/4);
    ctx.lineTo(-size/2, size/4);
    ctx.closePath();
    
    ctx.fillStyle = color;
    ctx.fill();
    ctx.restore();
}

function drawTriangle(x, y, size, direction, color) {
    ctx.save();
    ctx.fillStyle = color;
    ctx.translate(x, y);
    
    // Rotate based on direction
    if (direction === 'right') ctx.rotate(0);
    if (direction === 'down') ctx.rotate(Math.PI / 2);
    if (direction === 'left') ctx.rotate(Math.PI);
    if (direction === 'up') ctx.rotate(-Math.PI / 2);
    
    // Draw simple triangle pointing right (before rotation)
    ctx.beginPath();
    ctx.moveTo(size / 2, 0);
    ctx.lineTo(-size / 3, -size / 2);
    ctx.lineTo(-size / 3, size / 2);
    ctx.closePath();
    ctx.fill();
    
    ctx.restore();
}
