// Player Activity Status
let isRejoining = false;

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

socket.on('connect', () => {
    console.log('✅ Connected to Chess 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
const startScreen = document.getElementById('start-screen');
const lobbyScreen = document.getElementById('lobby-screen');
const gameScreen = document.getElementById('game-screen');
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 capturedByMeEl = document.getElementById('captured-by-me');
const capturedByOpponentEl = document.getElementById('captured-by-opponent');
const capturedByOpponentRightEl = document.getElementById('captured-by-opponent-right');
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');

// 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('chess_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();
});
// 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 = '/';
    });
}

// Game State
let myRole = null; // 'white' | 'black'
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 = 8;
const STORAGE_KEY = 'chess_session';

// Chatbox instance
let chatbox = null;

const PIECE_SYMBOLS = {
    white: {
        king: '♔', queen: '♕', rook: '♖', bishop: '♗', knight: '♘', pawn: '♙'
    },
    black: {
        king: '♚', queen: '♛', rook: '♜', bishop: '♝', knight: '♞', pawn: '♟'
    }
};

// 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);
        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);
}

// Player Activity Status
let isActive = true;

// Check session on page load
window.addEventListener('load', () => {
    const savedSession = loadSession();
    if (savedSession) {
        const disconnectTime = localStorage.getItem('chess_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('chess_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,
                        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();
    
    // 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/chess');
        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';
    }
}

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('connect', () => {
    const existingWarning = document.getElementById('disconnect-warning');
    if (existingWarning) existingWarning.remove();

    if (currentRoomId) {
        const savedSession = loadSession();
        if (savedSession && savedSession.roomId === currentRoomId) {
            console.log('Socket reconnected, re-joining room...');
            joinFromSession(savedSession); // Note: joinFromSession is not defined in original, but logic is similar to load handler
             socket.emit('join_room', {
                roomId: savedSession.roomId,
                password: savedSession.password,
                role: savedSession.role,
                playerName: savedSession.playerName
            });
        }
    }
});

socket.on('disconnect', () => {
    showNotification('Connection lost. Reconnecting...', 'error');
});

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

function renderRoomList(rooms) {
    const totalRooms = rooms.length;
    const availableRooms = rooms.filter(room => !room.isActive).length;
    
    document.getElementById('total-rooms').textContent = totalRooms;
    document.getElementById('available-rooms').textContent = availableRooms;
    
    roomListEl.innerHTML = '';
    rooms.forEach(room => {
        const card = document.createElement('div');
        card.classList.add('room-card');
        if (room.isActive) card.classList.add('active');
        card.classList.add(`room-type-${room.type}`);
        
        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`;
        };
        
        
        const whiteInfo = room.players.white 
            ? `<div class="player-info">
                   <span class="player-name"><i class="fas fa-chess-king" style="color: #f1f5f9;"></i> ${room.players.white.name}</span>
                   <span class="player-time">Joined ${formatTimeAgo(room.players.white.joinedAt)}</span>
               </div>`
            : `<div class="player-info empty">
                   <span class="player-name"><i class="fas fa-chess-king" style="color: #f1f5f9;"></i> Open</span>
               </div>`;
        
        const blackInfo = room.players.black
            ? `<div class="player-info">
                   <span class="player-name"><i class="fas fa-chess-king" style="color: #8b5cf6;"></i> ${room.players.black.name}</span>
                   <span class="player-time">Joined ${formatTimeAgo(room.players.black.joinedAt)}</span>
               </div>`
            : `<div class="player-info empty">
                   <span class="player-name"><i class="fas fa-chess-king" style="color: #8b5cf6;"></i> Open</span>
               </div>`;
        
        const status = room.isActive ? 'Active' : 'Empty';
        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">
                ${whiteInfo}
                <div class="vs-badge">VS</div>
                ${blackInfo}
            </div>
        `;
        
        card.addEventListener('click', () => openJoinModal(room));
        roomListEl.appendChild(card);
    });
}

function openJoinModal(room) {
    selectedRoomId = room.id;
    modalRoomName.textContent = `Join ${room.name}`;
    
    if (room.type === 'public' && room.password) {
        passwordInput.value = room.password;
    } else {
        passwordInput.value = '';
    }
    
    // Reset role selection to default (Black checked by default in HTML, or we can force it)
    // We don't need to overwrite innerHTML anymore as the structure is static and styled
    const blackRadio = document.querySelector('input[name="role"][value="black"]');
    if (blackRadio) blackRadio.checked = true;
    
    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;
    
    if (!name) return showNotification('Please enter your name', 'error');
    if (name.length < 3 || name.length > 10) return showNotification('Name must be 3-10 characters long', 'error');
    if (/\s/.test(name)) return showNotification('Name cannot contain spaces', 'error');
    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
    });
});

// Game Logic
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('chess_disconnect_time');
    
    // Save session to localStorage
    const savedSession = loadSession();
    const password = passwordInput.value.trim() || (savedSession?.password || '');
    saveSession(data.roomId, myName, data.role, password);
    
    // Clear disconnect time on successful join
    localStorage.removeItem('chess_disconnect_time');
    
    // 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: {
                white: '♔',
                black: '♚'
            }
        });
    } else {
        chatbox.updateConfig({
            roomId: data.roomId,
            playerName: myName,
            playerRole: data.role
        });
        chatbox.show();
    }
    
    // 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) => {
    updatePlayerInfo(data.players);
});

socket.on('game_start', (data) => {
    // Handle both old and new format
    gameState = data.gameState || data;
    currentMatchId = data.matchId || currentRoomId;
    
    updateUI();

    // Track game start with unique match ID (playerRole now in metrics on game_end)
    gameStartTime = Date.now();
    if (typeof trackGameStart === 'function') {
        trackGameStart('chess', {
            matchId: currentMatchId
        });
    }

    if (chatbox) {
        chatbox.clearMessages();
    }

    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();
});

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);
    setTimeout(() => {
        notif.style.animation = 'fadeOut 0.3s ease-out forwards';
        notif.addEventListener('animationend', () => notif.remove());
    }, 3000);
}

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', () => {
    socket.emit('restart_game', { roomId: currentRoomId });
    gameOverModal.classList.add('hidden');
});

socket.on('game_over', (data) => {
    const isWinner = data.winner === myRole;
    const isDraw = data.winner === 'draw';
    
    // Track game end with result
    if (typeof trackGameEnd === 'function' && gameStartTime) {
        const duration = Date.now() - gameStartTime;
        let result = isDraw ? 'draw' : (isWinner ? 'win' : 'loss');
        
        trackGameEnd('chess', duration, {
            metrics: {
                playerRole: myRole,
                result: result
            },
            matchId: currentMatchId
        });
        gameStartTime = null;
    }
    
    if (isDraw) {
        gameOverTitle.textContent = 'Draw!';
        gameOverMessage.textContent = `Game ended in a draw (${data.reason})`;
        gameOverTitle.style.color = '#fbbf24';
    } else {
        gameOverTitle.textContent = isWinner ? 'Congratulations!' : 'Game Over';
        gameOverMessage.textContent = isWinner ? 'You Won!' : 'You Lost!';
        gameOverTitle.style.color = isWinner ? '#22c55e' : '#ef4444';
    }
    
    gameOverModal.classList.remove('hidden');
    if (!isDraw) showNotification(`Game Over! Winner: ${data.winner.toUpperCase()}`, 'success');
    
    // Reload stats to show updated counts
    loadGameStats();
});

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

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

socket.on('error', (msg) => {
    showNotification(msg, 'error');
    isRejoining = false; // Clear rejoining state on error
    if (currentRoomId === null) {
        clearSession();
        lobbyScreen.classList.remove('hidden');
        gameScreen.classList.add('hidden');
        joinModal.classList.add('hidden');
        if (chatbox) {
            chatbox.hide();
        }
    }
});

function updatePlayerInfo(players) {
    const opponentRole = myRole === 'white' ? 'black' : 'white';
    const opponentName = players[opponentRole]?.name || 'Waiting...';
    const opponentStatus = players[opponentRole]?.status || 'offline';
    
    // Use FontAwesome icons for avatars
    const myAvatar = myRole === 'white' 
        ? '<i class="fas fa-chess-king" style="color: #fff; filter: drop-shadow(0 0 2px #000);"></i>' 
        : '<i class="fas fa-chess-king" style="color: #000; filter: drop-shadow(0 0 2px #fff);"></i>';
        
    playerMeEl.innerHTML = `
        <div class="status-dot online"></div>
        <div class="player-avatar">${myAvatar}</div>
        <div class="player-info-col">
            <div class="player-name">${myName}</div>
            <div class="player-status-text" id="status-text-me">${myRole.toUpperCase()}</div>
        </div>
    `;
    
    const opponentAvatar = opponentRole === 'white'
        ? '<i class="fas fa-chess-king" style="color: #fff; filter: drop-shadow(0 0 2px #000);"></i>'
        : '<i class="fas fa-chess-king" style="color: #000; filter: drop-shadow(0 0 2px #fff);"></i>';
        
    const isWaiting = opponentName === 'Waiting...';
    
    playerOpponentEl.innerHTML = `
        <div class="status-dot ${isWaiting ? 'offline' : opponentStatus}"></div>
        <div class="player-avatar">${isWaiting ? '⏳' : opponentAvatar}</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() {
    renderBoard();
    updateStatus();
}

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";
    turnBadge.className = 'turn-badge';

    if (!gameState.gameActive) {
        playerMeEl.classList.remove('active-turn');
        playerOpponentEl.classList.remove('active-turn');
        if (statusTextMe) 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";
    }
    
    // Update captured pieces display
    updateCapturedPieces();
    
    if (gameState.check) {
        showNotification('Check!', 'error');
    }
}

function updateCapturedPieces() {
    console.log('updateCapturedPieces called');
    console.log('gameState:', gameState);
    console.log('myRole:', myRole);
    
    if (!gameState.capturedPieces) {
        console.log('No capturedPieces in gameState');
        return;
    }
    
    console.log('capturedPieces:', gameState.capturedPieces);
    
    const opponentRole = myRole === 'white' ? 'black' : 'white';
    
    // Pieces I captured (opponent's pieces)
    const capturedByMe = gameState.capturedPieces[opponentRole];
    console.log('capturedByMe:', capturedByMe);
    capturedByMeEl.innerHTML = '';
    if (capturedByMe.length === 0) {
        capturedByMeEl.innerHTML = '<span class="no-captures">None</span>';
    } else {
        capturedByMe.forEach(pieceType => {
            const pieceSpan = document.createElement('span');
            pieceSpan.classList.add('captured-piece');
            pieceSpan.textContent = PIECE_SYMBOLS[opponentRole][pieceType];
            capturedByMeEl.appendChild(pieceSpan);
        });
    }
    
    // Pieces opponent captured (my pieces)
    const capturedByOpponent = gameState.capturedPieces[myRole];
    console.log('capturedByOpponent:', capturedByOpponent);
    
    // Update both elements (left sidebar for mobile, right sidebar for desktop)
    [capturedByOpponentEl, capturedByOpponentRightEl].forEach(el => {
        if (!el) return;
        el.innerHTML = '';
        if (capturedByOpponent.length === 0) {
            el.innerHTML = '<span class="no-captures">None</span>';
        } else {
            capturedByOpponent.forEach(pieceType => {
                const pieceSpan = document.createElement('span');
                pieceSpan.classList.add('captured-piece');
                pieceSpan.textContent = PIECE_SYMBOLS[myRole][pieceType];
                el.appendChild(pieceSpan);
            });
        }
    });
}


function renderBoard() {
    boardEl.innerHTML = '';
    boardEl.style.gridTemplateColumns = `repeat(${BOARD_SIZE}, 1fr)`;
    boardEl.style.gridTemplateRows = `repeat(${BOARD_SIZE}, 1fr)`;
    
    // Remove lines div if it exists (Bagh Chal specific)
    const lines = document.getElementById('lines');
    if (lines) lines.remove();

    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', 'chess-square');
            
            // Chess board coloring
            const isDark = (r + c) % 2 === 1;
            spot.classList.add(isDark ? 'dark-square' : 'light-square');
            
            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.color);
                pieceEl.textContent = PIECE_SYMBOLS[piece.color][piece.type];
                spot.appendChild(pieceEl);
            }
            
            // Highlight selected
            if (selectedPiece && selectedPiece.r === r && selectedPiece.c === c) {
                spot.classList.add('selected');
            }
            
            // Highlight valid moves for selected piece
            if (selectedPiece && isValidMove(selectedPiece, { r, c })) {
                spot.classList.add('valid-move');
            }
            
            // Highlight last move
            if (gameState.lastMove) {
                if ((gameState.lastMove.from.r === r && gameState.lastMove.from.c === c) ||
                    (gameState.lastMove.to.r === r && gameState.lastMove.to.c === c)) {
                    spot.classList.add('last-move');
                }
            }

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

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

    const clickedPiece = gameState.board[r][c];
    const isMyPiece = clickedPiece && clickedPiece.color === myRole;

    if (isMyPiece) {
        // Select own piece
        selectedPiece = { r, c };
        renderBoard();
    } else if (selectedPiece) {
        // Try to move
        // For better UX, we can check basic validity here, but server is ultimate authority
        // We'll send the move and let server validate
        socket.emit('make_move', { 
            roomId: currentRoomId,
            move: { 
                from: selectedPiece, 
                to: { r, c } 
            }
        });
        selectedPiece = null;
        renderBoard(); 
    }
}

// Simplified client-side validation for highlighting
function isValidMove(from, to) {
    const piece = gameState.board[from.r][from.c];
    if (!piece) return false;

    const dr = to.r - from.r;
    const dc = to.c - from.c;
    const absDr = Math.abs(dr);
    const absDc = Math.abs(dc);
    const target = gameState.board[to.r][to.c];

    // Cannot capture own piece
    if (target && target.color === piece.color) return false;

    switch (piece.type) {
        case 'pawn':
            const direction = piece.color === 'white' ? -1 : 1;
            const startRow = piece.color === 'white' ? 6 : 1;
            // Move forward 1
            if (dc === 0 && dr === direction && !target) return true;
            // Move forward 2
            if (dc === 0 && dr === 2 * direction && from.r === startRow && !target && !gameState.board[from.r + direction][from.c]) return true;
            // Capture
            if (absDc === 1 && dr === direction && target) return true;
            return false;
        case 'rook':
            if (dr !== 0 && dc !== 0) return false;
            return isPathClear(from, to);
        case 'knight':
            return (absDr === 2 && absDc === 1) || (absDr === 1 && absDc === 2);
        case 'bishop':
            if (absDr !== absDc) return false;
            return isPathClear(from, to);
        case 'queen':
            if (dr !== 0 && dc !== 0 && absDr !== absDc) return false;
            return isPathClear(from, to);
        case 'king':
            return absDr <= 1 && absDc <= 1;
    }
    return false;
}

function isPathClear(from, to) {
    const dr = Math.sign(to.r - from.r);
    const dc = Math.sign(to.c - from.c);
    let r = from.r + dr;
    let c = from.c + dc;

    while (r !== to.r || c !== to.c) {
        if (gameState.board[r][c]) return false;
        r += dr;
        c += dc;
    }
    return true;
}
