// Player Activity Status
let isRejoining = false;

// DOM Elements - Start Screen
const startScreen = document.getElementById('start-screen');
const lobbyScreen = document.getElementById('lobby-screen');
const gameScreen = document.getElementById('game-screen');

// 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');
    
    // Ensure modal is hidden on route change
    if (joinModal) {
        joinModal.classList.add('hidden');
    }
    
    // Hide chatbox if not in game
    if (hash !== '#/game' && typeof chatbox !== 'undefined' && chatbox) {
        chatbox.hide();
    }
    
    // Show appropriate screen based on hash
    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;
        case '#/':
        default:
            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('bagh_chal_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;
        // Note: We DO NOT clear the session (localStorage) or myRole/myName here
        // because we want to allow reconnection!
    }
    
    handleRoute();
});
// Note: handleRoute() is called manually after session check in the load event handler

// Start Screen Navigation
const modeVsPlayer = document.getElementById('mode-vs-player');
const modeVsAI = document.getElementById('mode-vs-ai');

// Handle VS Player mode selection
if (modeVsPlayer) {
    modeVsPlayer.addEventListener('click', () => {
        window.location.hash = '#/lobby';
    });
}

// Handle VS AI mode selection (coming soon)
if (modeVsAI) {
    modeVsAI.addEventListener('click', () => {
        showNotification('VS AI mode is coming soon!', 'info');
    });
}

// Handle back to start screen from lobby
const backToStartBtn = document.getElementById('back-to-start');
if (backToStartBtn) {
    backToStartBtn.addEventListener('click', () => {
        window.location.hash = '#/';
    });
}

// Handle back to portal from start screen
const backToPortalBtn = document.getElementById('back-to-portal-btn');
if (backToPortalBtn) {
    backToPortalBtn.addEventListener('click', () => {
        window.location.href = '/';
    });
}



// Connect to the bagh-chal namespace
const socket = io('/bagh-chal', {
    reconnection: true,
    reconnectionAttempts: 5
});

socket.on('connect', () => {
    console.log('✅ Connected to Bagh Chal server via Proxy!');
    console.log('Socket ID:', socket.id);
});

socket.on('connect_error', (err) => {
    console.error('❌ Connection Error:', err);
});

socket.on('room_list', (rooms) => {
    console.log('📦 Received room list:', rooms);
});

// DOM Elements - Additional Game Elements
const roomListEl = document.getElementById('room-list');
const joinModal = document.getElementById('join-modal');
const modalRoomName = document.getElementById('modal-room-name');
const usernameInput = document.getElementById('username');
const passwordInput = document.getElementById('room-password');
const confirmJoinBtn = document.getElementById('confirm-join-btn');
const cancelJoinBtn = document.getElementById('cancel-join-btn');
const boardEl = document.getElementById('spots-container');
const playerMeEl = document.getElementById('player-me');
const playerOpponentEl = document.getElementById('player-opponent');
const turnDisplayEl = document.getElementById('turn-display');
const capturedCountEl = document.getElementById('goats-captured');
const placedCountEl = document.getElementById('goats-placed');
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 myRole = null; // 'tiger' | 'goat'
let myName = '';
let currentRoomId = null;
let currentMatchId = null; // Unique match identifier
let isMyTurn = false;
let gameState = null;
let selectedPiece = null; // { r, c }
let selectedRoomId = null;
let gameStartTime = null; // Track game duration

// Constants
const BOARD_SIZE = 5;
const STORAGE_KEY = 'bagh_chal_session';

// Chatbox instance
let chatbox = null;

// LocalStorage Management
function saveSession(roomId, playerName, role, password) {
    const sessionData = {
        roomId,
        playerName,
        role,
        password,
        timestamp: Date.now()
    };
    localStorage.setItem(STORAGE_KEY, JSON.stringify(sessionData));
}

function loadSession() {
    const data = localStorage.getItem(STORAGE_KEY);
    if (!data) return null;
    
    try {
        const session = JSON.parse(data);
        // Clear stale sessions (older than 24 hours)
        const oneDayMs = 24 * 60 * 60 * 1000;
        if (Date.now() - session.timestamp > oneDayMs) {
            clearSession();
            return null;
        }
        return session;
    } catch (e) {
        clearSession();
        return null;
    }
}

function clearSession() {
    localStorage.removeItem(STORAGE_KEY);
    // Also reset in-memory state
    currentRoomId = null;
    myRole = null;
    myName = '';
}

// Player Activity Status
let isActive = true;

// Check session on page load
window.addEventListener('load', () => {
    const savedSession = loadSession();
    if (savedSession) {
        const disconnectTime = localStorage.getItem('bagh_chal_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('bagh_chal_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;
                    
                    socket.emit('join_room', {
                        roomId: savedSession.roomId,
                        password: savedSession.password,
                        role: savedSession.role,
                        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();
    
    // Now handle routing after session check is complete
    handleRoute();
});

// Function to load and display game stats
async function loadGameStats() {
    try {
        const response = await fetch('/api/sessions/game-stats/bagh-chal');
        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';
    }
}

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

// Also track window focus (backup detection)
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' 
        });
    }
});

// Handle Socket Reconnection (e.g. server restart)
socket.on('connect', () => {
    // Clear any disconnection warning
    const existingWarning = document.getElementById('disconnect-warning');
    if (existingWarning) existingWarning.remove();

    // If we have a current room ID (meaning we were playing), try to rejoin
    // We check currentRoomId to avoid rejoining if we were just in the lobby
    // But if page refreshed, currentRoomId is null, handled by window.load
    // This is specifically for when socket drops/reconnects WITHOUT page refresh
    if (currentRoomId) {
        const savedSession = loadSession();
        if (savedSession && savedSession.roomId === currentRoomId) {
            console.log('Socket reconnected, re-joining room...');
            joinFromSession(savedSession);
        }
    }
});

socket.on('disconnect', () => {
    showNotification('Connection lost. Reconnecting...', 'error');
    // Optional: Add a persistent warning banner if you want
});

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

function renderRoomList(rooms) {
    // Update summary statistics
    const totalRooms = rooms.length;
    const availableRooms = rooms.filter(room => !room.isActive).length;
    
    document.getElementById('total-rooms').textContent = totalRooms;
    document.getElementById('available-rooms').textContent = availableRooms;
    
    // Render room cards
    roomListEl.innerHTML = '';
    rooms.forEach(room => {
        const card = document.createElement('div');
        card.classList.add('room-card');
        if (room.isActive) card.classList.add('active');
        
        // Add room type badge class
        card.classList.add(`room-type-${room.type}`);
        
        // Helper function to format time ago
        const formatTimeAgo = (timestamp) => {
            const seconds = Math.floor((Date.now() - timestamp) / 1000);
            if (seconds < 60) return 'just now';
            const minutes = Math.floor(seconds / 60);
            if (minutes < 60) return `${minutes} min ago`;
            const hours = Math.floor(minutes / 60);
            if (hours < 24) return `${hours} hr ago`;
            const days = Math.floor(hours / 24);
            return `${days} day${days > 1 ? 's' : ''} ago`;
        };
        
        // Build player info HTML
        const tigerInfo = room.players.tiger 
            ? `<div class="player-info">
                   <span class="player-name">
                       <i class="fas fa-dog" style="color: #ef4444;"></i> 
                       ${room.players.tiger.name}
                       ${room.players.tiger.status === 'disconnected' ? '<span class="status-badge offline">(Away)</span>' : ''}
                   </span>
                   <span class="player-time">Joined ${formatTimeAgo(room.players.tiger.joinedAt)}</span>
               </div>`
            : `<div class="player-info empty">
                   <span class="player-name"><i class="fas fa-dog" style="color: #ef4444;"></i> Open</span>
               </div>`;
        
        const goatInfo = room.players.goat
            ? `<div class="player-info">
                   <span class="player-name">
                       <i class="fas fa-horse-head" style="color: #22c55e;"></i> 
                       ${room.players.goat.name}
                       ${room.players.goat.status === 'disconnected' ? '<span class="status-badge offline">(Away)</span>' : ''}
                   </span>
                   <span class="player-time">Joined ${formatTimeAgo(room.players.goat.joinedAt)}</span>
               </div>`
            : `<div class="player-info empty">
                   <span class="player-name"><i class="fas fa-horse-head" style="color: #22c55e;"></i> Open</span>
               </div>`;
        
        const status = room.isActive ? 'Active' : 'Empty';
        
        // Room type badge
        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>${room.name}</h3>
                <span class="room-status ${room.isActive ? 'active' : ''}">${status}</span>
            </div>
            <div class="room-meta">
                ${typeBadge}
            </div>
            <div class="room-players">
                ${tigerInfo}
                <div class="vs-badge">VS</div>
                ${goatInfo}
            </div>
        `;
        
        card.addEventListener('click', () => openJoinModal(room));
        roomListEl.appendChild(card);
    });
}

function openJoinModal(room) {
    selectedRoomId = room.id;
    modalRoomName.textContent = `Join ${room.name}`;
    
    // Auto-fill password for public rooms
    if (room.type === 'public' && room.password) {
        passwordInput.value = room.password;
    } else {
        passwordInput.value = '';
    }
    
    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.trim();
    const role = document.querySelector('input[name="role"]:checked').value;
    
    // Validate username
    if (!name) return showNotification('Please enter your name', 'error');
    
    // Check length (3-10 characters)
    if (name.length < 3 || name.length > 10) {
        return showNotification('Name must be 3-10 characters long', 'error');
    }
    
    // Check for spaces
    if (/\s/.test(name)) {
        return showNotification('Name cannot contain spaces', 'error');
    }
    
    // Check for special characters (only allow alphanumeric)
    if (!/^[a-zA-Z0-9]+$/.test(name)) {
        return showNotification('Name can only contain letters and numbers', 'error');
    }
    
    if (!selectedRoomId) return;

    socket.emit('join_room', {
        roomId: selectedRoomId,
        password,
        role,
        playerName: name
    });
});

// Update chatbox config when joining room
socket.on('joined_room', (data) => {
    currentRoomId = data.roomId;
    myRole = data.role;
    // Use name from server if available (handles refresh where input is empty)
    if (data.players && data.players[myRole]) {
        myName = data.players[myRole].name;
    } else {
        myName = usernameInput.value;
    }
    gameState = data.gameState;
    
    // Clear rejoining state
    isRejoining = false;
    localStorage.removeItem('bagh_chal_disconnect_time');
    
    // Save session to localStorage
    // Important: During auto-rejoin, passwordInput.value might be empty
    // so we should preserve the existing saved password
    const savedSession = loadSession();
    const password = passwordInput.value.trim() || (savedSession?.password || '');
    saveSession(data.roomId, myName, data.role, password);
    
    // Switch to game screen
    window.location.hash = '#/game';
    
    // Ensure modal is hidden
    joinModal.classList.add('hidden');
    
    // Initialize board
    renderBoard();
    
    // Initialize chatbox
    if (!chatbox) {
        chatbox = new Chatbox({
            socket: socket,
            roomId: data.roomId,
            playerName: myName,
            playerRole: data.role,
            roleEmojis: {
                tiger: '🐯',
                goat: '🐐'
            }
        });
    } else {
        chatbox.updateConfig({
            roomId: data.roomId,
            playerName: myName,
            playerRole: data.role
        });
    }
    
    // Load chat history if available
    if (data.chatHistory && data.chatHistory.length > 0) {
        chatbox.loadHistory(data.chatHistory);
    }
    
    chatbox.show();
    
    updateUI();
    updatePlayerInfo(data.players);
    showNotification('Joined room successfully!', 'success');
});

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

socket.on('player_status_update', (data) => {
    console.log('Received status update:', data);
    updatePlayerInfo(data.players);
});


socket.on('game_start', (data) => {
    // Handle both old and new format
    gameState = data.gameState || data;
    currentMatchId = data.matchId || currentRoomId;
    
    updateUI();
    gameOverModal.classList.add('hidden');
    showNotification('Game Started!', 'info');
    
    // Track game start with unique match ID
    gameStartTime = Date.now();
    if (typeof trackGameStart === 'function') {
        trackGameStart('bagh-chal', {
            matchId: currentMatchId
        });
    }
    
    // Force sync player info to ensure opponent name is shown
    if (currentRoomId) {
        socket.emit('get_players', { roomId: currentRoomId });
    }
});

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

socket.on('update_game', (data) => {
    gameState = data.gameState;
    updateUI();
});

// Notifications
function showNotification(message, type = 'info') {
    const container = document.getElementById('notification-container');
    const notif = document.createElement('div');
    notif.classList.add('notification', type);
    notif.textContent = message;
    
    container.appendChild(notif);
    
    // Remove after 3 seconds
    setTimeout(() => {
        notif.style.animation = 'fadeOut 0.3s ease-out forwards';
        notif.addEventListener('animationend', () => {
            notif.remove();
        });
    }, 3000);
}

// Game Over Modal Logic
const gameOverModal = document.getElementById('game-over-modal');
const gameOverTitle = document.getElementById('game-over-title');
const gameOverMessage = document.getElementById('game-over-message');
const restartBtn = document.getElementById('restart-btn');

restartBtn.addEventListener('click', () => {
    // Use currentRoomId as selectedRoomId might be null after page refresh
    socket.emit('restart_game', { roomId: currentRoomId });
    gameOverModal.classList.add('hidden');
});

socket.on('game_over', (data) => {
    const isWinner = data.winner === myRole;
    
    // Track game end with result
    if (typeof trackGameEnd === 'function' && gameStartTime) {
        const duration = Date.now() - gameStartTime;
        const result = isWinner ? 'win' : 'loss';
        
        trackGameEnd('bagh-chal', duration, {
            metrics: {
                playerRole: myRole,
                goatsCaptured: gameState.goatsCaptured || 0,
                goatsPlaced: gameState.goatsPlaced || 0,
                result: result
            },
            matchId: currentMatchId
        });
        gameStartTime = null;
    }
    
    gameOverTitle.textContent = isWinner ? 'Congratulations!' : 'Game Over';
    gameOverMessage.textContent = isWinner ? 'You Won!' : 'You Lost!';
    
    // Style adjustments based on result
    gameOverTitle.style.color = isWinner ? '#22c55e' : '#ef4444';
    
    gameOverModal.classList.remove('hidden');
    showNotification(`Game Over! Winner: ${data.winner.toUpperCase()}`, 'success');
    
    // Reload stats to show updated counts
    loadGameStats();
});

// Note: game_start is already handled earlier in the file (lines 279-282)
// Game start handled by updateUI called from socket listeners

socket.on('player_left', (data) => {
    showNotification(`Player (${data.role}) disconnected.`, 'error');
});

// Handle intentional disconnect/leave (if needed in the future)
window.addEventListener('beforeunload', () => {
    // Save the disconnect time when leaving the page
    // This will be checked on page load to determine if we should auto-rejoin
    if (currentRoomId) {
        localStorage.setItem('bagh_chal_disconnect_time', Date.now().toString());
    }
});

socket.on('error', (msg) => {
    isRejoining = false;
    showNotification(msg, 'error');
    
    // Clear session on error (likely invalid rejoin attempt)
    if (currentRoomId === null) {
        clearSession();
        // Ensure we're showing the lobby
        lobbyScreen.classList.remove('hidden');
        gameScreen.classList.add('hidden');
        joinModal.classList.add('hidden');
        if (chatbox) {
            chatbox.hide();
        }
    }
});


// UI Update Functions
function updatePlayerInfo(players) {
    const opponentRole = myRole === 'tiger' ? 'goat' : 'tiger';
    const opponentName = players[opponentRole]?.name || 'Waiting...';
    const opponentStatus = players[opponentRole]?.status || 'offline';
    
    const myEmoji = myRole === 'tiger' ? '🐯' : '🐐';
    playerMeEl.innerHTML = `
        <div class="status-dot online"></div>
        <div class="player-avatar">${myEmoji}</div>
        <div class="player-info-col">
            <div class="player-name">${myName}</div>
            <div class="player-status-text" id="status-text-me">${myRole ? myRole.toUpperCase() : ''}</div>
        </div>
    `;
    
    const opponentEmoji = opponentRole === 'tiger' ? '🐯' : '🐐';
    const isWaiting = opponentName === 'Waiting...';
    
    playerOpponentEl.innerHTML = `
        <div class="status-dot ${isWaiting ? 'offline' : opponentStatus}"></div>
        <div class="player-avatar">${isWaiting ? '⏳' : opponentEmoji}</div>
        <div class="player-info-col">
            <div class="player-name">${opponentName}</div>
            <div class="player-status-text" id="status-text-opponent">${isWaiting ? 'WAITING' : opponentRole.toUpperCase()}</div>
        </div>
    `;
    
    if (isWaiting) {
        playerOpponentEl.classList.add('empty');
    } else {
        playerOpponentEl.classList.remove('empty');
    }
}

function updateUI() {
    if (!gameState) return;
    renderBoard();
    updateStatus();
    
    // Update stats
    if (gameState.goatsPlaced !== undefined) {
        placedCountEl.textContent = gameState.goatsPlaced;
    }
    if (gameState.goatsCaptured !== undefined) {
        capturedCountEl.textContent = gameState.goatsCaptured;
    }
}

function updateStatus() {
    const turnBadge = turnDisplayEl.querySelector('.turn-badge');
    const statusTextMe = document.getElementById('status-text-me');
    const statusTextOpponent = document.getElementById('status-text-opponent');
    
    turnBadge.textContent = "VS";
    
    if (!gameState.gameActive) {
        playerMeEl.classList.remove('active-turn');
        playerOpponentEl.classList.remove('active-turn');
        if (statusTextMe && myRole) statusTextMe.textContent = myRole.toUpperCase();
        if (statusTextOpponent) statusTextOpponent.textContent = "WAITING";
        return;
    }

    isMyTurn = gameState.turn === myRole;
    
    if (isMyTurn) {
        playerMeEl.classList.add('active-turn');
        playerOpponentEl.classList.remove('active-turn');
        if (statusTextMe) statusTextMe.textContent = "YOUR TURN";
        if (statusTextOpponent) statusTextOpponent.textContent = "WAITING...";
    } else {
        playerMeEl.classList.remove('active-turn');
        playerOpponentEl.classList.add('active-turn');
        if (statusTextMe) statusTextMe.textContent = "WAITING...";
        if (statusTextOpponent) statusTextOpponent.textContent = "PLAYING";
    }
}

function renderBoard() {
    boardEl.innerHTML = '';
    
    // Create 5x5 grid
    for (let r = 0; r < BOARD_SIZE; r++) {
        for (let c = 0; c < BOARD_SIZE; c++) {
            const spot = document.createElement('div');
            spot.classList.add('spot');
            spot.style.top = `${r * 25}%`;
            spot.style.left = `${c * 25}%`;
            spot.dataset.r = r;
            spot.dataset.c = c;
            
            const piece = gameState.board[r][c];
            if (piece) {
                const pieceEl = document.createElement('div');
                pieceEl.classList.add('piece', piece);
                pieceEl.textContent = piece === 'tiger' ? '🐯' : '🐐';
                spot.appendChild(pieceEl);
            }
            
            // Highlight selected
            if (selectedPiece && selectedPiece.r === r && selectedPiece.c === c) {
                const pieceEl = spot.querySelector('.piece');
                if (pieceEl) pieceEl.classList.add('selected');
            }
            
            // Highlight last move
            if (gameState.lastMove) {
                const { type, from, to } = gameState.lastMove;
                if (type === 'place') {
                    if (to.r === r && to.c === c) {
                        spot.classList.add('last-move-to');
                    }
                } else if (type === 'move') {
                    if (from.r === r && from.c === c) {
                        spot.classList.add('last-move-from');
                    } else if (to.r === r && to.c === c) {
                        spot.classList.add('last-move-to');
                    }
                }
            }

            // Highlight valid moves (if piece selected)
            if (selectedPiece && isValidMove(selectedPiece, {r, c})) {
                spot.classList.add('valid-move');
            }

            // Highlight trapped tigers
            if (piece === 'tiger') {
                let hasValidMove = false;
                // Check all possible directions
                const directions = [
                    [-1, -1], [-1, 0], [-1, 1],
                    [0, -1],           [0, 1],
                    [1, -1],  [1, 0],  [1, 1]
                ];
                
                for (const [dr, dc] of directions) {
                    const newR = r + dr;
                    const newC = c + dc;
                    
                    // Check if destination is within bounds
                    if (newR >= 0 && newR < BOARD_SIZE && newC >= 0 && newC < BOARD_SIZE) {
                        // Check if destination is empty
                        if (!gameState.board[newR][newC]) {
                            // Check if diagonal move is allowed (only on center/corner spots)
                            const isDiagonal = Math.abs(dr) === 1 && Math.abs(dc) === 1;
                            const canMoveDiagonal = (r + c) % 2 === 0;
                            
                            if (!isDiagonal || canMoveDiagonal) {
                                hasValidMove = true;
                                break;
                            }
                        }
                        // Check if it's a goat (for jump)
                        else if (gameState.board[newR][newC] === 'goat') {
                            const jumpR = r + 2 * dr;
                            const jumpC = c + 2 * dc;
                            
                            // Check if jump destination is valid and empty
                            if (jumpR >= 0 && jumpR < BOARD_SIZE && jumpC >= 0 && jumpC < BOARD_SIZE && !gameState.board[jumpR][jumpC]) {
                                // Check if diagonal jump is allowed
                                const isDiagonal = Math.abs(dr) === 1 && Math.abs(dc) === 1;
                                const canMoveDiagonal = (r + c) % 2 === 0;
                                
                                if (!isDiagonal || canMoveDiagonal) {
                                    hasValidMove = true;
                                    break;
                                }
                            }
                        }
                    }
                }
                
                if (!hasValidMove) {
                    console.log(`Tiger at (${r}, ${c}) is trapped!`);
                    spot.classList.add('trapped-tiger');
                }
            }

            spot.addEventListener('click', () => handleSpotClick(r, c));
            boardEl.appendChild(spot);
        }
    }
}

function handleSpotClick(r, c) {
    if (!isMyTurn || !gameState.gameActive) return;

    const clickedPiece = gameState.board[r][c];

    // Goat Placement Phase
    if (myRole === 'goat' && gameState.goatsPlaced < 20) {
        if (!clickedPiece) {
            // Place goat
            socket.emit('make_move', { roomId: currentRoomId, move: { type: 'place', r, c } });
        }
        return;
    }

    // Movement Phase
    if (clickedPiece === myRole) {
        // Select own piece
        selectedPiece = { r, c };
        renderBoard(); // Re-render to show selection/valid moves
    } else if (selectedPiece && !clickedPiece) {
        // Try to move to empty spot
        if (isValidMove(selectedPiece, { r, c })) {
            socket.emit('make_move', { 
                roomId: currentRoomId,
                move: { 
                    type: 'move', 
                    from: selectedPiece, 
                    to: { r, c } 
                }
            });
            selectedPiece = null;
        }
    }
}

function isValidMove(from, to) {
    const dr = Math.abs(from.r - to.r);
    const dc = Math.abs(from.c - to.c);
    
    const isOrthogonal = (dr + dc === 1);
    const isDiagonal = (dr === 1 && dc === 1);
    const canMoveDiagonal = (from.r + from.c) % 2 === 0;

    if (myRole === 'goat') {
        if (isOrthogonal) return true;
        if (isDiagonal && canMoveDiagonal) return true;
        return false;
    }
    
    if (myRole === 'tiger') {
        if (isOrthogonal) return true;
        if (isDiagonal && canMoveDiagonal) return true;
        
        const isJumpOrthogonal = (dr === 2 && dc === 0) || (dr === 0 && dc === 2);
        const isJumpDiagonal = (dr === 2 && dc === 2);
        
        if (isJumpOrthogonal || (isJumpDiagonal && canMoveDiagonal)) {
            const midR = (from.r + to.r) / 2;
            const midC = (from.c + to.c) / 2;
            const midPiece = gameState.board[midR][midC];
            return midPiece === 'goat';
        }
    }
    
    return false;
}
