// Import the dictionary
//import { SCRABBLE_DICTIONARY } from './dictionary.js';

// Define an empty dictionary array since we're using OpenAI for validation
const SCRABBLE_DICTIONARY = [];

// Define the letter distribution for Scrabble tiles
const letterDistribution = {
  "A": { count: 9, points: 1 },
  "B": { count: 2, points: 3 },
  "C": { count: 2, points: 3 },
  "D": { count: 4, points: 2 },
  "E": { count: 12, points: 1 },
  "F": { count: 2, points: 4 },
  "G": { count: 3, points: 2 },
  "H": { count: 2, points: 4 },
  "I": { count: 9, points: 1 },
  "J": { count: 1, points: 8 },
  "K": { count: 1, points: 5 },
  "L": { count: 4, points: 1 },
  "M": { count: 2, points: 3 },
  "N": { count: 6, points: 1 },
  "O": { count: 8, points: 1 },
  "P": { count: 2, points: 3 },
  "Q": { count: 1, points: 10 },
  "R": { count: 6, points: 1 },
  "S": { count: 4, points: 1 },
  "T": { count: 6, points: 1 },
  "U": { count: 4, points: 1 },
  "V": { count: 2, points: 4 },
  "W": { count: 2, points: 4 },
  "X": { count: 1, points: 8 },
  "Y": { count: 2, points: 4 },
  "Z": { count: 1, points: 10 },
  " ": { count: 2, points: 0 } // Blank tiles
};

// Add a cache for previously validated words
const validatedWordsCache = new Map();

// Global variables for connection handling
let connectionAttempts = 0;
let connectionTimeout = null;
let connectionLogInterval = null;
let connectionStartTime = null;
let totalConnectionTime = 60000; // Extend to 60 seconds total attempt time
let apiConnected = false;
let currentSuggestedMove = null; // Store the current AI move suggestion
let connectionAttemptModels = [
  { model: "gpt-3.5-turbo-0125", temp: 0.3, message: "Connection test" }
];

// Global variables and state
let apiChecksAttempted = 0;
let apiLastAttempt = 0;
let offlineMode = false; // Set to true to bypass API connection requirements

// Game State Management
class GameState {
    constructor() {
        this.players = [];
        this.currentPlayerIndex = 0;
        this.board = Array(15).fill().map(() => Array(15).fill(null));
        this.tileBag = [];
        this.gameStarted = false;
        this.gameEnded = false;
        this.startTime = null;
        this.moveHistory = [];
        this.chatHistory = [];
        this.recommendations = [];
        this.scores = new Map();
        this.turnCount = 0;
        this.roundCount = 1;
        this.remainingTiles = 100;
        this.specialCells = this.initializeSpecialCells();
        
        // Initialize statistics
        this.statistics = {
            totalMoves: 0,
            wordsPlayed: 0,
            totalScore: 0,
            highestWord: { word: "", score: 0 },
            chatInteractions: 0,
            recommendationsAccepted: 0,
            recommendationsDenied: 0,
            startTime: null,
            endTime: null
        };
    }

    initializeSpecialCells() {
        const specialCells = new Map();
        // Center star
        specialCells.set('7,7', 'DW');
        
        // Double Word (DW)
        const dwPositions = [
            '1,1', '1,13', '2,2', '2,12', '3,3', '3,11', '4,4', '4,10',
            '7,1', '7,13', '10,4', '10,10', '11,3', '11,11', '12,2', '12,12',
            '13,1', '13,13'
        ];
        dwPositions.forEach(pos => specialCells.set(pos, 'DW'));
        
        // Triple Word (TW)
        const twPositions = [
            '0,0', '0,7', '0,14', '7,0', '7,14', '14,0', '14,7', '14,14'
        ];
        twPositions.forEach(pos => specialCells.set(pos, 'TW'));
        
        // Double Letter (DL)
        const dlPositions = [
            '0,3', '0,11', '2,6', '2,8', '3,0', '3,7', '3,14', '6,2', '6,6',
            '6,8', '6,12', '7,3', '7,11', '8,2', '8,6', '8,8', '8,12', '11,0',
            '11,7', '11,14', '12,6', '12,8', '14,3', '14,11'
        ];
        dlPositions.forEach(pos => specialCells.set(pos, 'DL'));
        
        // Triple Letter (TL)
        const tlPositions = [
            '1,5', '1,9', '5,1', '5,5', '5,9', '5,13', '9,1', '9,5', '9,9',
            '9,13', '13,5', '13,9'
        ];
        tlPositions.forEach(pos => specialCells.set(pos, 'TL'));
        
        return specialCells;
    }

    addPlayer(name, isHuman = false, difficulty = null) {
        const player = {
            name,
            isHuman,
            difficulty,
            rack: [],
            score: 0
        };
        this.players.push(player);
        this.scores.set(name, 0);
    }

    initializeTileBag() {
        this.tileBag = [];
        for (const [letter, data] of Object.entries(letterDistribution)) {
            for (let i = 0; i < data.count; i++) {
                this.tileBag.push({
                    letter,
                    points: data.points,
                    id: `${letter}-${i}`
                });
            }
        }
        this.shuffleTileBag();
    }

    shuffleTileBag() {
        for (let i = this.tileBag.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [this.tileBag[i], this.tileBag[j]] = [this.tileBag[j], this.tileBag[i]];
        }
    }

    drawTiles(player, count = 7) {
        const drawnTiles = [];
        for (let i = 0; i < count && this.tileBag.length > 0; i++) {
            drawnTiles.push(this.tileBag.pop());
        }
        player.rack.push(...drawnTiles);
        this.remainingTiles = this.tileBag.length;
        return drawnTiles;
    }

    getCurrentPlayer() {
        return this.players[this.currentPlayerIndex];
    }

    nextTurn() {
        this.currentPlayerIndex = (this.currentPlayerIndex + 1) % this.players.length;
        if (this.currentPlayerIndex === 0) {
            this.roundCount++;
        }
        this.turnCount++;
    }

    isGameOver() {
        // Check if any player has used all their tiles
        const hasEmptyRack = this.players.some(player => player.rack.length === 0);
        if (hasEmptyRack && this.tileBag.length === 0) {
            return true;
        }

        // Check for consecutive passes (6 passes in a row)
        if (this.moveHistory.length >= 6) {
            const lastSixMoves = this.moveHistory.slice(-6);
            if (lastSixMoves.every(move => move.type === 'pass')) {
                return true;
            }
        }

        return false;
    }

    calculateFinalScores() {
        // Subtract unplayed tiles from each player's score
        for (const player of this.players) {
            let unplayedPoints = 0;
            for (const tile of player.rack) {
                unplayedPoints += tile.points;
            }
            this.scores.set(player.name, this.scores.get(player.name) - unplayedPoints);
        }

        // Add unplayed points to the player who used all their tiles
        const playerWithEmptyRack = this.players.find(player => player.rack.length === 0);
        if (playerWithEmptyRack) {
            let totalUnplayedPoints = 0;
            for (const player of this.players) {
                if (player !== playerWithEmptyRack) {
                    for (const tile of player.rack) {
                        totalUnplayedPoints += tile.points;
                    }
                }
            }
            this.scores.set(
                playerWithEmptyRack.name,
                this.scores.get(playerWithEmptyRack.name) + totalUnplayedPoints
            );
        }
    }
}

// Create global game state instance
const gameState = new GameState();

// Board Interaction and Word Validation
class BoardManager {
    constructor(gameState) {
        this.gameState = gameState;
        this.currentPlacement = new Map(); // Tracks tiles placed in current turn
        this.dragSource = null;
    }

    isValidPlacement(row, col) {
        // Check if position is within board bounds
        if (row < 0 || row >= 15 || col < 0 || col >= 15) {
            return false;
        }

        // Check if position is already occupied
        if (this.gameState.board[row][col] !== null) {
            return false;
        }

        // For first move, must use center square
        if (this.gameState.turnCount === 0) {
            return row === 7 && col === 7;
        }

        // Must be adjacent to existing tiles
        const adjacentPositions = [
            [row - 1, col], [row + 1, col],
            [row, col - 1], [row, col + 1]
        ];

        return adjacentPositions.some(([r, c]) => {
            return r >= 0 && r < 15 && c >= 0 && c < 15 && 
                   this.gameState.board[r][c] !== null;
        });
    }

    placeTile(tile, row, col) {
        if (!this.isValidPlacement(row, col)) {
            return false;
        }

        this.gameState.board[row][col] = {
            ...tile,
            row,
            col,
            placedBy: this.gameState.getCurrentPlayer().name
        };

        this.currentPlacement.set(`${row},${col}`, tile);
        return true;
    }

    removeTile(row, col) {
        if (this.currentPlacement.has(`${row},${col}`)) {
            this.gameState.board[row][col] = null;
            this.currentPlacement.delete(`${row},${col}`);
            return true;
        }
        return false;
    }

    clearCurrentPlacement() {
        for (const [pos, tile] of this.currentPlacement) {
            const [row, col] = pos.split(',').map(Number);
            this.gameState.board[row][col] = null;
        }
        this.currentPlacement.clear();
    }

    getWordAtPosition(row, col, direction = 'horizontal') {
        const word = [];
        let currentRow = row;
        let currentCol = col;

        // Move backwards to find start of word
        while (true) {
            if (direction === 'horizontal') {
                if (currentCol < 0 || this.gameState.board[currentRow][currentCol] === null) {
                    currentCol++;
                    break;
                }
                currentCol--;
            } else {
                if (currentRow < 0 || this.gameState.board[currentRow][currentCol] === null) {
                    currentRow++;
                    break;
                }
                currentRow--;
            }
        }

        // Collect word
        while (true) {
            if (direction === 'horizontal') {
                if (currentCol >= 15 || this.gameState.board[currentRow][currentCol] === null) {
                    break;
                }
                word.push(this.gameState.board[currentRow][currentCol]);
                currentCol++;
            } else {
                if (currentRow >= 15 || this.gameState.board[currentRow][currentCol] === null) {
                    break;
                }
                word.push(this.gameState.board[currentRow][currentCol]);
                currentRow++;
            }
        }

        return word;
    }

    getCrossWords(row, col) {
        const words = [];
        const mainWord = this.getWordAtPosition(row, col, 'horizontal');
        if (mainWord.length > 1) {
            words.push(mainWord);
        }

        // Check for cross words
        for (const tile of mainWord) {
            const crossWord = this.getWordAtPosition(tile.row, tile.col, 'vertical');
            if (crossWord.length > 1) {
                words.push(crossWord);
            }
        }

        return words;
    }

    calculateWordScore(word) {
        let score = 0;
        let wordMultiplier = 1;

        for (const tile of word) {
            let letterScore = tile.points;
            const cellKey = `${tile.row},${tile.col}`;
            const specialCell = this.gameState.specialCells.get(cellKey);

            // Apply letter multipliers
            if (specialCell === 'DL') {
                letterScore *= 2;
            } else if (specialCell === 'TL') {
                letterScore *= 3;
            }

            // Apply word multipliers
            if (specialCell === 'DW') {
                wordMultiplier *= 2;
            } else if (specialCell === 'TW') {
                wordMultiplier *= 3;
            }

            score += letterScore;
        }

        return score * wordMultiplier;
    }

    validateMove() {
        if (this.currentPlacement.size === 0) {
            return { valid: false, message: "No tiles placed" };
        }

        // Get all words formed by the current placement
        const words = [];
        for (const [pos, tile] of this.currentPlacement) {
            const [row, col] = pos.split(',').map(Number);
            const crossWords = this.getCrossWords(row, col);
            words.push(...crossWords);
        }

        // Remove duplicates
        const uniqueWords = [...new Set(words.map(word => 
            word.map(tile => tile.letter).join('')
        ))];

        // Validate each word
        for (const word of uniqueWords) {
            const isValid = this.validateWord(word);
            if (!isValid) {
                return { 
                    valid: false, 
                    message: `Invalid word: ${word}` 
                };
            }
        }

        return { 
            valid: true, 
            words: uniqueWords,
            score: words.reduce((total, word) => total + this.calculateWordScore(word), 0)
        };
    }

    async validateWord(word) {
        // Check cache first
        if (validatedWordsCache.has(word)) {
            return validatedWordsCache.get(word);
        }

        try {
            const response = await callOpenAI(
                `Is "${word}" a valid Scrabble word? Answer with only "yes" or "no".`,
                { temperature: 0.1 }
            );
            
            const isValid = response.toLowerCase().includes('yes');
            validatedWordsCache.set(word, isValid);
            return isValid;
        } catch (error) {
            console.error('Error validating word:', error);
            return false;
        }
    }

    commitMove() {
        const validation = this.validateMove();
        if (!validation.valid) {
            this.clearCurrentPlacement();
            return validation;
        }

        // Update scores
        const currentPlayer = this.gameState.getCurrentPlayer();
        this.gameState.scores.set(
            currentPlayer.name,
            this.gameState.scores.get(currentPlayer.name) + validation.score
        );

        // Record move in history
        this.gameState.moveHistory.push({
            type: 'play',
            player: currentPlayer.name,
            words: validation.words,
            score: validation.score,
            tiles: Array.from(this.currentPlacement.values())
        });

        // Clear current placement tracking
        this.currentPlacement.clear();

        return validation;
    }
}

// Create global board manager instance
const boardManager = new BoardManager(gameState);

// Global helper function to safely toggle thinking indicator
function toggleThinkingIndicator(show) {
    try {
        const indicator = document.getElementById("thinking-indicator");
  if (indicator) {
    indicator.style.display = show ? "flex" : "none";
            
            // Also toggle the brain icon animation
            const brainIcon = indicator.querySelector(".thinking-brain");
            if (brainIcon) {
                if (show) {
                    brainIcon.classList.add("active");
  } else {
                    brainIcon.classList.remove("active");
                }
            }
        }
    } catch (error) {
        console.error("Error toggling thinking indicator:", error);
  }
}

// Update start button state based on connection status
function updateStartButtonState(enabled) {
    const startButton = document.getElementById("start-game");
    if (!startButton) {
        console.warn("Start button not found in DOM");
        return;
    }
    
    if (enabled === undefined) {
        enabled = window.apiConnected === true;
    }
    
    if (enabled) {
        startButton.disabled = false;
        startButton.classList.add("active");
        startButton.classList.remove("disabled");
        console.log("Start button enabled");
    } else {
        startButton.disabled = true;
        startButton.classList.add("disabled");
        startButton.classList.remove("active");
        console.log("Start button disabled");
    }
}

// Add debug function at the top of the file to help diagnose issues
function debugElement(elementId, description) {
    const element = document.getElementById(elementId);
    console.log(`Debug ${description || elementId}:`, {
        exists: !!element,
        element: element,
        styles: element ? {
            display: element.style.display,
            visibility: element.style.visibility,
            width: element.offsetWidth,
            height: element.offsetHeight,
            backgroundColor: element.style.backgroundColor
        } : null,
        children: element ? element.children.length : 0,
        html: element ? element.innerHTML.substring(0, 100) + (element.innerHTML.length > 100 ? '...' : '') : null
    });
    return element;
}

// Add this right after the DOMContentLoaded event listener to fix MIME type issues
// This should be around line 2 in your file
if (document.currentScript && document.currentScript.type === 'module') {
    console.log("Script is loaded as a module - this might cause MIME type issues");
    // Try to load script again as a regular script if needed
}

document.addEventListener("DOMContentLoaded", () => {
    // Skip initialization if already done
    if (window.appInitialized) {
        console.log("Application already initialized, skipping duplicate initialization");
        return;
    }
    
    console.log("DOM fully loaded, initializing application components");
    window.appInitialized = true;
    
    try {
        // Initialize connection log if it exists
        const connectionLogElement = document.getElementById("connection-log");
        if (connectionLogElement) {
            // Initialize retry button if it exists
            if (!window.retryButtonInitialized) {
                const retryBtn = document.getElementById("retry-connection-btn");
                if (retryBtn) {
                    retryBtn.addEventListener("click", function() {
                        addConnectionLog("Manual connection retry initiated.");
                        startAPIConnectionProcess();
                    });
                    window.retryButtonInitialized = true;
                    console.log("Retry button initialized");
                }
            }
            
            // Start connection process
            if (!window.connectionInitialized) {
                console.log("Starting API connection process");
                addConnectionLog("Initializing application...", "info");
                
                // Start the API connection process after a short delay
                setTimeout(() => {
                    startAPIConnectionProcess();
                }, 500);
                
                // Set up periodic checks
                setTimeout(() => {
                    if (!window.connectionCheckInterval) {
                        startPeriodicConnectionCheck();
                    }
                }, 30000);
                
                window.connectionInitialized = true;
            }
        } else {
            console.error("Connection log element not found in DOM");
        }
        
        // Initialize game components
        initializeGameComponents();
        
    } catch (error) {
        console.error("Error during initialization:", error);
        if (typeof addConnectionLog === 'function') {
            addConnectionLog("Initialization error: " + error.message, "error");
        }
    }
});

// Function to start periodic connection checks
function startPeriodicConnectionCheck() {
    // Check connection every 60 seconds
    setInterval(function() {
        if (window.apiConnected === true) {
            console.log("Skipping periodic connection check - API already connected");
            return;
        }
        
        console.log("Running periodic API connection check");
        addConnectionLog("Performing periodic connection check...", "info");
        
        testAPIConnection()
            .then(function(connected) {
                if (!connected) {
                    console.log("Periodic connection check failed");
                    addConnectionLog("Periodic connection check failed", "error");
                } else {
                    console.log("Periodic connection check successful");
                    addConnectionLog("Periodic connection check successful", "success");
                }
            })
            .catch(function(error) {
                console.error("Error in periodic connection check:", error);
                addConnectionLog("Error in periodic connection check: " + error.message, "error");
            });
    }, 60000); // 60 seconds
    
    console.log("Setting up periodic API connection checks");
    addConnectionLog("Setting up periodic connection monitoring", "info");
}

// Helper function to add a log entry
function addConnectionLog(message, type = "info") {
    const connectionLog = document.getElementById("connection-log");
    if (!connectionLog) return;
    
    const timestamp = new Date().toLocaleTimeString();
    const logEntry = document.createElement("li");
    logEntry.className = type;
    logEntry.innerHTML = `<span class="timestamp">[${timestamp}]</span> ${message}`;
    
    // Insert at the top
    connectionLog.insertBefore(logEntry, connectionLog.firstChild);
    
    // Limit to 20 entries
    while (connectionLog.children.length > 20) {
        connectionLog.removeChild(connectionLog.lastChild);
    }
}

// Function to start the game timer
function startGameTimer() {
    console.log("Starting game timer...");
    
    // Reset game timer
    gameTimeSeconds = 0;
    
    // Update timer display initially
    updateGameTimer();
    
    // Start interval for timer updates
    gameTimerInterval = setInterval(() => {
        updateGameTimer();
    }, 1000);
    
    console.log("Game timer started");
    return true;
}

// Helper function to find empty board cells adjacent to already placed tiles
function findEmptyCellsAdjacentToPlacedTiles() {
    const emptyCells = [];
    const boardCells = document.querySelectorAll('.board-cell');
    
    // First find all cells with played tiles
    const occupiedCells = [];
    boardCells.forEach(cell => {
        if (cell.querySelector('.tile.played')) {
            const position = cell.dataset.position;
            if (position) {
                const [row, col] = position.split(',').map(Number);
                occupiedCells.push({ row, col, element: cell });
            }
        }
    });
    
    // Now find empty cells adjacent to occupied cells
    boardCells.forEach(cell => {
        // Skip cells that already have tiles
        if (cell.querySelector('.tile')) {
            return;
        }
        
        const position = cell.dataset.position;
        if (position) {
            const [row, col] = position.split(',').map(Number);
            
            // Check if this cell is adjacent to any occupied cell
            for (const occupiedCell of occupiedCells) {
                // Check if adjacent (horizontally or vertically)
                if ((Math.abs(row - occupiedCell.row) === 1 && col === occupiedCell.col) || 
                    (Math.abs(col - occupiedCell.col) === 1 && row === occupiedCell.row)) {
                    emptyCells.push(cell);
                    return; // Skip further checks for this cell
                }
            }
        }
    });
    
    return emptyCells;
}

// Update the rack display for a player
function updateRack(player) {
    try {
        if (!player) {
            console.error("Player object is undefined or null in updateRack");
            return;
        }
    
        // Get the rack element based on player index
        let rackElement;
        if (player.index === 0) {
            rackElement = document.getElementById("player-rack"); // Updated to match HTML
        } else {
            rackElement = document.getElementById(`cpu-${player.index}-rack`);
        }
        
        if (!rackElement) {
            console.error(`Rack element not found for player ${player.index}`);
            return;
        }

        // Clear the current rack
        rackElement.innerHTML = "";

        // Create slots for a consistent rack size (7 slots)
        for (let i = 0; i < 7; i++) {
            const slotElement = document.createElement("div");
            slotElement.className = "rack-slot";
            
            // Add a tile if available
            if (i < player.tiles.length) {
                const tile = player.tiles[i];
                const tileElement = createTileElement(tile, player.index);
                if (tileElement) {
                    slotElement.appendChild(tileElement);
                }
            }
            
            rackElement.appendChild(slotElement);
        }

        // Set up drag events for the human player's rack
        if (player.index === 0) {
            addDragEventsToTiles();
        }
        
        console.log(`Updated rack for player ${player.index} with ${player.tiles.length} tiles`);
    } catch (error) {
        console.error("Error updating rack:", error);
    }
}

// Set up drag and drop for player tiles
function setupDragEvents() {
    try {
        console.log("Setting up drag events for tiles...");
        
        // Get all tiles that belong to the human player (player index 0)
        const tiles = document.querySelectorAll('.tile[data-player-index="0"]');
        
        tiles.forEach(tile => {
            // Make the tile draggable
            tile.draggable = true;
            
            // Add dragstart event
            tile.addEventListener('dragstart', function(e) {
                console.log("Drag started for tile:", this.dataset.letter);
                this.classList.add('dragging');
                
                // Set data transfer
                e.dataTransfer.setData('text/plain', JSON.stringify({
                    id: this.dataset.id,
                    letter: this.dataset.letter,
                    value: this.dataset.value,
                    playerIndex: this.dataset.playerIndex
                }));
                
                // Set drag image (optional)
                // Create a clone of the tile for the drag image
                const dragImage = this.cloneNode(true);
                dragImage.style.opacity = '0.7';
                dragImage.style.position = 'absolute';
                dragImage.style.top = '-1000px';
                document.body.appendChild(dragImage);
                e.dataTransfer.setDragImage(dragImage, 20, 20);
                
                // Remove the drag image after it's no longer needed
                setTimeout(() => {
                    document.body.removeChild(dragImage);
                }, 0);
            });
            
            // Add dragend event
            tile.addEventListener('dragend', function() {
                console.log("Drag ended for tile:", this.dataset.letter);
                this.classList.remove('dragging');
            });
        });
        
        console.log(`Drag events set up for ${tiles.length} tiles`);
        return true;
    } catch (error) {
        console.error("Error setting up drag events:", error);
        return false;
    }
}

// Function to handle tile placement in the game state
function placeTile(playerIndex, tileId, row, col) {
    try {
        console.log(`Player ${playerIndex} placing tile ${tileId} at position ${row},${col}`);
        
        // Get the player
        const player = getPlayer(playerIndex);
        if (!player) {
            throw new Error(`Player with index ${playerIndex} not found`);
        }
        
        // Find the tile in the player's rack
        const tileIndex = player.tiles.findIndex(t => t.id === tileId);
        if (tileIndex === -1) {
            throw new Error(`Tile with ID ${tileId} not found in player ${playerIndex}'s rack`);
        }
        
        // Remove tile from player's rack
        const tile = player.tiles.splice(tileIndex, 1)[0];
        
        // Add tile to board
        gameState.board[row][col] = {
            ...tile,
            playerIndex: playerIndex,
            placed: true,
            permanent: false // Will be true after word is confirmed
        };
        
        // Add to current move
        gameState.currentMove.push({
            row: row,
            col: col,
            letter: tile.letter,
            value: tile.value,
            tileId: tileId,
            playerIndex: playerIndex
        });
        
        // Update the player's rack display
        updateRack(player);
        
        console.log(`Tile ${tile.letter} successfully placed at ${row},${col}`);
        
        // Check if player can submit word
        checkSubmitWordAvailability();
        
        return true;
    } catch (error) {
        console.error("Error placing tile:", error);
    return false;
    }
}

// Helper function to check if the player can submit a word
function checkSubmitWordAvailability() {
    try {
        // Enable submit button if at least one tile has been placed
        const submitButton = document.getElementById('submit-word');
        if (submitButton) {
            submitButton.disabled = gameState.currentMove.length === 0;
        }
        
        return true;
    } catch (error) {
        console.error("Error checking submit availability:", error);
    return false;
    }
}

// Helper function to get a player by index
function getPlayer(playerIndex) {
    try {
        // Check if players array exists
        if (!gameState.players || !Array.isArray(gameState.players)) {
            throw new Error("Game state players array not initialized");
        }
        
        // Find player by index
        const player = gameState.players.find(p => p.index === playerIndex);
        
        // If not found, log an error
        if (!player) {
            console.error(`Player with index ${playerIndex} not found`);
            return null;
        }
        
        return player;
    } catch (error) {
        console.error("Error getting player:", error);
        return null;
    }
}

// Functions for API connection status
function updateAPIStatus(status) {
    const statusIcon = document.getElementById('api-status-icon');
    const statusText = document.getElementById('api-status-text');
    const gameAPIStatus = document.getElementById('game-api-status');
    
    if (!statusIcon || !statusText) {
        console.error("API status elements not found");
        return;
    }
    
    // Remove all previous classes
    statusIcon.classList.remove('pending', 'connected', 'error');
    
    // Update game area API status if it exists
    if (gameAPIStatus) {
        gameAPIStatus.classList.remove('pending', 'connected', 'error');
    }
    
    switch (status) {
        case 'pending':
            statusIcon.classList.add('pending');
            statusText.textContent = 'Connecting...';
            if (gameAPIStatus) gameAPIStatus.classList.add('pending');
            apiConnected = false;
            break;
        case 'connected':
            statusIcon.classList.add('connected');
            statusText.textContent = 'Connected';
            if (gameAPIStatus) gameAPIStatus.classList.add('connected');
            apiConnected = true;
            break;
        case 'error':
            statusIcon.classList.add('error');
            statusText.textContent = 'Connection Failed';
            if (gameAPIStatus) gameAPIStatus.classList.add('error');
            apiConnected = false;
        break;
    }
    
    // Update start button state
    updateStartButtonState();
}

// Recommendation overlay system
let currentRecommendation = null;

function showRecommendation(recommendation) {
    // Store the recommendation
    currentRecommendation = recommendation;
    
    if (!recommendation || !recommendation.placements || recommendation.placements.length === 0) {
        console.error("Invalid recommendation format:", recommendation);
        return;
    }
    
    const overlay = document.getElementById('recommendation-overlay');
    if (!overlay) {
        console.error("Recommendation overlay not found");
        return;
    }
    
    // Clear any existing tiles in the overlay
    overlay.innerHTML = '';
    
    // Create tiles for each letter in the recommendation
    recommendation.placements.forEach(placement => {
        const { row, col, letter, value } = placement;
        
        // Create recommendation tile
        const tile = document.createElement('div');
        tile.className = 'recommendation-tile';
        
        // Calculate position based on row and col
        const cellElement = document.querySelector(`.board-cell[data-position="${row},${col}"]`);
        if (cellElement) {
            const rect = cellElement.getBoundingClientRect();
            const boardRect = document.getElementById('board').getBoundingClientRect();
            
            tile.style.left = `${cellElement.offsetLeft}px`;
            tile.style.top = `${cellElement.offsetTop}px`;
            
            // Add letter and value to the tile
            const letterEl = document.createElement('span');
            letterEl.className = 'tile-letter';
            letterEl.textContent = letter;
            tile.appendChild(letterEl);
            
            const valueEl = document.createElement('span');
            valueEl.className = 'tile-value';
            valueEl.textContent = value;
            tile.appendChild(valueEl);
            
            overlay.appendChild(tile);
        }
    });
    
    // Show the overlay
    overlay.classList.remove('hidden');
    
    // Enable accept/deny buttons
    const acceptBtn = document.getElementById('accept-recommendation');
    const denyBtn = document.getElementById('deny-recommendation');
    
    if (acceptBtn) acceptBtn.disabled = false;
    if (denyBtn) denyBtn.disabled = false;
}

function clearRecommendation() {
    currentRecommendation = null;
    
    const overlay = document.getElementById('recommendation-overlay');
    if (overlay) {
        overlay.innerHTML = '';
        overlay.classList.add('hidden');
    }
    
    // Disable accept/deny buttons
    const acceptBtn = document.getElementById('accept-recommendation');
    const denyBtn = document.getElementById('deny-recommendation');
    
    if (acceptBtn) acceptBtn.disabled = true;
    if (denyBtn) denyBtn.disabled = true;
}

function acceptRecommendation() {
    if (!currentRecommendation) {
        console.error("No recommendation to accept");
        return;
    }
    
    // For each placement in the recommendation, find the corresponding tile in the player's rack
    // and place it on the board at the recommended position
    for (const placement of currentRecommendation.placements) {
        const { row, col, letter } = placement;
        
        // Find a tile in the player's rack with this letter
        const player = getPlayer(0); // Get human player
        const tileIndex = player.tiles.findIndex(t => t.letter === letter);
        
        if (tileIndex !== -1) {
            // Place the tile on the board
            placeTile(0, player.tiles[tileIndex].id, row, col);
} else {
            console.error(`No tile with letter ${letter} found in player's rack`);
        }
    }
    
    // Clear the recommendation
    clearRecommendation();
    
    // Add to chat history
    addChatMessage("player", "I accept your recommendation.", false);
    addChatMessage("bot", "Great! I've placed the tiles for you. You can submit your word now.", false);
    
    // Update move history
    addToMoveHistory(`Player accepted AI recommendation: "${currentRecommendation.word}" for ${currentRecommendation.score} points`);
    
    // Update game statistics
    gameState.stats.recommendationsAccepted++;
}

function denyRecommendation() {
    if (!currentRecommendation) {
        console.error("No recommendation to deny");
        return;
    }
    
    // Clear the recommendation
    clearRecommendation();
    
    // Add to chat history
    addChatMessage("player", "I don't want to use that recommendation.", false);
    addChatMessage("bot", "No problem! Let me know if you'd like another suggestion.", false);
    
    // Update game statistics
    gameState.stats.recommendationsDenied++;
}

// Update bot thinking state
function setBotThinking(isThinking) {
    const thinkingIcon = document.getElementById('bot-thinking-status');
    if (!thinkingIcon) {
        console.error("Bot thinking status icon not found");
        return;
    }
    
    if (isThinking) {
        thinkingIcon.classList.add('active');
    } else {
        thinkingIcon.classList.remove('active');
    }
}

// Call OpenAI API through Volunteer Science endpoint
async function callOpenAI(message, options = {}) {
    try {
        // Show thinking indicator
        toggleThinkingIndicator(true);
        addConnectionLog("Sending request to OpenAI: " + options.model || "gpt-3.5-turbo-0125");
        
        // Default values
        const model = options.model || "gpt-3.5-turbo-0125";
        const temperature = options.temperature || 0.3;
        
        // Create the request payload
        const requestData = {
            model: model,
            temperature: temperature,
            message: {
                role: "user",
                content: message
            }
        };
        
        debugLog("Sending request to OpenAI:", requestData);
        
        // Use the Volunteer Science endpoint
        const response = await fetch('https://volunteerscience.com/openai/chat/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(requestData)
        });
        
        // Check if the request was successful
        if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`API Error (${response.status}): ${errorText}`);
        }
        
        // Parse the response
        const data = await response.json();
        debugLog("Received response from OpenAI", data);
        
        // Update API status
        updateAPIStatus(true, "Connected");
        addConnectionLog("Received response from OpenAI", "success");
        
        return data.response || "No response from API";
    } catch (error) {
        // Handle errors
        debugError("API Error:", error);
        updateAPIStatus(false, "Error");
        addConnectionLog("API Error: " + error.message, "error");
        return "Sorry, I encountered an error while processing your request. Please try again later.";
    } finally {
        // Hide thinking indicator
        toggleThinkingIndicator(false);
    }
}

// Test the API connection
async function testAPIConnection() {
    try {
        console.log("Testing API connection...");
        addConnectionLog("Testing API connection...");
        
        // Prepare a simple message for the API
        const message = "Connection test";
        const model = "gpt-3.5-turbo-0125";
        const temperature = 0.3;
        
        // Call the OpenAI API
        const requestData = {
            model: model,
    temperature: temperature,
            message: {
                role: "user",
                content: message
            }
        };
        
        // Log the request for debugging
        console.log("Sending request to OpenAI:", requestData);
        addConnectionLog("Sending request to OpenAI: " + model);
        
        // Use the Volunteer Science endpoint
        const response = await fetch('https://volunteerscience.com/openai/chat/', {
            method: 'POST',
        headers: {
                'Content-Type': 'application/json'
        },
            body: JSON.stringify(requestData)
    });
    
        // Check if the request was successful
    if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`API Error (${response.status}): ${errorText}`);
        }
        
        // Parse the response
        const data = await response.json();
        console.log("Received response from OpenAI", data);
        
        // Update API status based on response
        if (data && data.response) {
            updateAPIStatus(true, "Connected");
            addConnectionLog("Received response from OpenAI", "success");
    return true;
        } else {
            updateAPIStatus(false, "Error: Invalid response");
            addConnectionLog("API connection failed: Invalid response format", "error");
            return false;
        }
} catch (error) {
    console.error("API connection test error:", error);
        updateAPIStatus(false, error.message || "Connection error");
        addConnectionLog("API Error: " + (error.message || "Unknown error"), "error");
    return false;
}
}
  
    // Update API connection status
    function updateAPIStatus(connected, message = "") {
        const statusElem = document.getElementById("connection-status");
        const textElem = document.getElementById("connection-text");
        
        // Set the global connection flag
        if (connected === true) {
            window.apiConnected = true;
        } else if (connected === false) {
            window.apiConnected = false;
        }
        // If connected is null, don't change the apiConnected state (pending)
        
        if (!statusElem || !textElem) {
            console.warn("API status elements not found in DOM");
            return;
        }

        // Clear all status classes
        statusElem.className = "status-indicator";
        
        if (connected === true) {
            // Connected - green status
            statusElem.classList.add("connected");
            textElem.textContent = message || "Connected";
            
            // Update start button state
            updateStartButtonState(true);
        } else if (connected === false) {
            // Disconnected - red status
            statusElem.classList.add("disconnected");
            textElem.textContent = message || "Disconnected";
            
            // Update start button state
            updateStartButtonState(false);
        } else {
            // Connecting/Pending - orange status
            statusElem.classList.add("connecting");
            textElem.textContent = message || "Connecting...";
            
            // Button remains disabled during connecting state
            updateStartButtonState(false);
        }
        
        console.log("API status updated:", connected, message);
    }

    // Function to update connection timer display
    function updateConnectionTimer() {
        if (!connectionStartTime) return;
        
        const timerElement = document.getElementById("connection-timer");
        if (!timerElement) return;
        
        const elapsedTime = Date.now() - connectionStartTime;
        const remainingTime = Math.max(0, totalConnectionTime - elapsedTime);
        const secondsRemaining = Math.ceil(remainingTime / 1000);
        
        if (remainingTime > 0 && !apiConnected) {
            timerElement.textContent = `Connection attempt timeout in ${secondsRemaining} seconds...`;
            timerElement.className = "info";
        } else if (apiConnected) {
            timerElement.textContent = "Connected successfully!";
            timerElement.className = "success";
        } else {
            timerElement.textContent = "Connection timeout reached. Please retry.";
            timerElement.className = "error";
        }
    }

    // Function to start connection process with proper state tracking
    function startAPIConnectionProcess() {
        // Skip if already connected
        if (window.apiConnected === true) {
            console.log("API already connected, skipping connection process");
            return;
        }
        
        // Skip if another connection process is active
        if (window.connectionProcessActive === true) {
            console.log("Connection process already active, skipping new attempt");
            return;
        }
        
        // Set flag to prevent multiple connection processes
        window.connectionProcessActive = true;
        
        // Reset connection state
        connectionAttempts = 0;
        connectionStartTime = Date.now();
        apiConnected = false;
        
        // Clear any existing intervals/timeouts
        if (connectionTimeout) clearTimeout(connectionTimeout);
        if (connectionLogInterval) clearInterval(connectionLogInterval);
        
        // Update UI for connecting state
        updateAPIStatus("pending", "Initiating connection...");
        addConnectionLog("Starting connection to OpenAI API via Volunteer Science...");
        addConnectionLog(`Using model ${connectionAttemptModels[0].model} with temperature ${connectionAttemptModels[0].temp}`, "info");
        
        // Start the timer display update
        connectionLogInterval = setInterval(() => {
            updateConnectionTimer();
        }, 1000);
        
        // Set the overall timeout
        connectionTimeout = setTimeout(() => {
            if (!apiConnected) {
                addConnectionLog("Connection attempts timed out after 60 seconds.", "error");
                updateAPIStatus("disconnected", "Connection timed out");
                clearInterval(connectionLogInterval);
                window.connectionProcessActive = false;
            }
        }, totalConnectionTime);
        
        // Make first connection attempt
        attemptConnection();
    }

    // Function to attempt connection with retry logic
    function attemptConnection() {
        connectionAttempts++;
        
        // Get the model configuration
        const { model, temp, message } = connectionAttemptModels[0];
        
        addConnectionLog(`Attempt #${connectionAttempts}: Using model ${model} with temp ${temp}`);
        
        // Execute the test connection
        testAPIConnection(model, temp, message)
            .then(success => {
                if (success) {
                    // Connected successfully
                    addConnectionLog(`Successfully connected to OpenAI API using ${model}!`, "success");
                    clearTimeout(connectionTimeout);
                    window.connectionProcessActive = false;
                    // Keep the timer interval for display purposes
                } else if (connectionAttempts < 3 && !apiConnected) {
                    // Try again with the same parameters (up to 3 attempts)
                    const delay = Math.min(3000 + (connectionAttempts * 1000), 8000); // Increasing delays between attempts
                    addConnectionLog(`Connection failed. Waiting ${delay/1000} seconds before retry...`, "info");
                    
                    setTimeout(() => {
                        if (!apiConnected) {
                            addConnectionLog(`Retrying connection (attempt ${connectionAttempts + 1} of 3)...`);
                            attemptConnection();
                        }
                    }, delay);
                } else if (!apiConnected) {
                    // All attempts failed
                    addConnectionLog("All connection attempts failed. Please check your account or try again later.", "error");
                    addConnectionLog("Make sure your account is registered at volunteerscience.com/openai/add_account/1/", "error");
                    updateAPIStatus("disconnected", "Connection failed");
                    window.connectionProcessActive = false;
                }
            })
            .catch(error => {
                addConnectionLog(`Error during attempt #${connectionAttempts}: ${error.message}`, "error");
                
                if (connectionAttempts < 3 && !apiConnected) {
                    // Try again with the same parameters (up to 3 attempts)
                    const delay = Math.min(3000 + (connectionAttempts * 1000), 8000); // Increasing delays between attempts
                    addConnectionLog(`Waiting ${delay/1000} seconds before retry...`, "info");
                    
                    setTimeout(() => {
                        if (!apiConnected) {
                            addConnectionLog(`Retrying connection (attempt ${connectionAttempts + 1} of 3)...`);
                            attemptConnection();
                        }
                    }, delay);
                } else if (!apiConnected) {
                    // All attempts failed
                    addConnectionLog("All connection attempts failed. Please check your account or try again later.", "error");
                    addConnectionLog("Make sure your account is registered at volunteerscience.com/openai/add_account/1/", "error");
                    updateAPIStatus("disconnected", "Connection failed");
                    window.connectionProcessActive = false;
                }
            });
    }

    // Enhanced function to test API connection to Volunteer Science
    async function testAPIConnection(model = "gpt-3.5-turbo-0125", temperature = 0.3, content = "Connection test") {
        console.log(`Testing API connection with model=${model}, temp=${temperature}, content="${content}"`);
        updateAPIStatus("pending", `Connecting using ${model}...`);
        
        const payload = {
            message: {"role": "user", "content": content},
            temperature: temperature,
            model: model
        };
        
        // Log fetch attempt
        addConnectionLog(`Sending request to https://volunteerscience.com/openai/chat/ with ${model}...`, "info");
        
        try {
            const response = await fetch("https://volunteerscience.com/openai/chat/", {
                method: "POST",
                body: JSON.stringify(payload),
                headers: {
                    "Content-Type": "application/json; charset=UTF-8"
                },
                credentials: "include",
                mode: "cors"
            });
            
            if (!response.ok) {
                const errorText = await response.text().catch(() => "Could not get response text");
                addConnectionLog(`Error response (${response.status}): ${errorText.substring(0, 100)}`, "error");
                throw new Error(`HTTP error! Status: ${response.status} ${response.statusText || ""}`);
            }
            
            const result = await response.json();
            console.log("API connection successful!", result);
            
            if (!result || !result.response) {
                addConnectionLog("Response didn't contain expected 'response' field", "error");
                throw new Error("Invalid response format from API");
            }
            
            addConnectionLog(`API returned valid response: "${result.response?.substring(0, 20) || "No response"}..."`, "success");
            apiConnected = true;
            updateAPIStatus("connected", `Connected to OpenAI API using ${model}`);
            // Send welcome message on successful connection
            sendWelcomeMessage();
            return true;
        } catch (error) {
            console.error("API connection test error:", error);
            addConnectionLog(`Connection error: ${error.message}`, "error");
            apiConnected = false;
            updateAPIStatus("disconnected", `Connection error: ${error.message}`);
            return false;
        }
    }

    // Function to send welcome message when connection is established
    function sendWelcomeMessage() {
        if (window.apiConnected) {
            // Check if chat log exists first
            const chatLog = document.getElementById('chat-log');
            if (chatLog) {
                // Only send welcome message if the chat is empty or has just the initial message
                if (chatLog.children.length <= 1) {
                    appendChatMessage('bot', 'Connection successful! I can now help you find the best moves and explain the rules.');
                }
            }
        }
    }

    // Chat interaction functions
    function addChatMessage(sender, message, updateStats = true) {
        const chatHistory = document.getElementById('chat-history');
        if (!chatHistory) {
            console.error("Chat history container not found");
            return;
        }
        
        const messageDiv = document.createElement('div');
        messageDiv.className = sender === 'bot' ? 'bot-message' : 'player-message';
        
        const messageContent = document.createElement('div');
        messageContent.className = 'message-content';
        messageContent.textContent = message;
        
        messageDiv.appendChild(messageContent);
        chatHistory.appendChild(messageDiv);
        
        // Scroll to bottom
        chatHistory.scrollTop = chatHistory.scrollHeight;
        
        // Update chat statistics if needed
        if (updateStats && gameState && gameState.stats) {
            gameState.stats.totalChats++;
        }
    }

    // Handle player chat message
    async function handleChatMessage(message) {
        if (!message || message.trim() === '') {
            return;
        }
        
        // Add the player's message to the chat
        addChatMessage('player', message);
        
        // Clear the input
        const chatInput = document.getElementById('chat-input');
        if (chatInput) {
            chatInput.value = '';
            chatInput.disabled = true;
        }
        
        // Disable send button
        const sendButton = document.getElementById('send-chat');
        if (sendButton) {
            sendButton.disabled = true;
        }
        
        // Show thinking indicator
        setBotThinking(true);
        
        // Process the message for special commands
        const lowerMessage = message.toLowerCase();
        let isMoveRequest = false;
        
        // Check if this is a move recommendation request
        if (lowerMessage.includes('what word') || 
            lowerMessage.includes('recommend') || 
            lowerMessage.includes('suggestion') || 
            lowerMessage.includes('best move') ||
            lowerMessage.includes('help me')) {
            isMoveRequest = true;
        }
        
        // Prepare game state context
        const gameContext = prepareGameStateContext();
        
        // Call the OpenAI API
        const response = await callOpenAI(message, {
            isMoveRequest: isMoveRequest,
            additionalContext: gameContext
        });
        
        // Hide thinking indicator
        setBotThinking(false);
        
        // Re-enable input and button
        if (chatInput) {
            chatInput.disabled = false;
            chatInput.focus();
        }
        if (sendButton) {
            sendButton.disabled = false;
        }
        
        // Add the bot's response to the chat
        if (response.success) {
            addChatMessage('bot', response.response);
        } else {
            addChatMessage('bot', "I'm sorry, I encountered an error while processing your request. Please try again.");
        }
    }

    // Prepare game state context for the AI
    function prepareGameStateContext() {
        if (!gameState) {
            return "";
        }
        
        // Get the current player and board state
        const player = getPlayer(0);
        if (!player) {
            return "";
        }
        
        // Create a board representation
        let boardContext = "Current board state:\n";
        for (let row = 0; row < 15; row++) {
            let rowStr = "";
            for (let col = 0; col < 15; col++) {
                const cell = gameState.board[row][col];
                if (cell && cell.letter) {
                    rowStr += cell.letter;
                } else {
                    rowStr += ".";
                }
            }
            boardContext += rowStr + "\n";
        }
        
        // Add player's tiles
        let tilesContext = "Your available tiles: ";
        if (player.tiles && player.tiles.length > 0) {
            tilesContext += player.tiles.map(t => t.letter).join(", ");
        } else {
            tilesContext += "None";
        }
        
        // Add special cells information
        const specialCells = getSpecialCellsInfo();
        
        return `${boardContext}\n${tilesContext}\n${specialCells}`;
    }

    // Get information about special cells (DL, TL, DW, TW)
    function getSpecialCellsInfo() {
        return `Special cells information:
- DL (Double Letter): Doubles the score of a letter placed on it
- TL (Triple Letter): Triples the score of a letter placed on it
- DW (Double Word): Doubles the score of an entire word if a letter is placed on it
- TW (Triple Word): Triples the score of an entire word if a letter is placed on it`;
    }

    // Add a message to the move history
    function addToMoveHistory(message) {
        const moveHistory = document.getElementById('move-history');
        if (!moveHistory) {
            console.error("Move history container not found");
            return;
        }
        
        const entry = document.createElement('div');
        entry.className = 'move-entry';
        entry.textContent = message;
        
        moveHistory.appendChild(entry);
        moveHistory.scrollTop = moveHistory.scrollHeight;
    }

    // Initialize game event listeners
    function setupGameEventListeners() {
        // Chat input
        const chatInput = document.getElementById('chat-input');
        const sendChatBtn = document.getElementById('sendChatBtn');
        
        if (chatInput && sendChatBtn) {
            // Send message on button click
            sendChatBtn.addEventListener('click', () => {
                const message = chatInput.value.trim();
                if (message) {
                    handleChatMessage(message);
                }
            });
            
            // Send message on Enter key
            chatInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    const message = chatInput.value.trim();
                    if (message) {
                        handleChatMessage(message);
                    }
                }
            });
        }
        
        // Recommendation buttons
        const acceptRecommendationBtn = document.getElementById('acceptRecommendationBtn');
        const denyRecommendationBtn = document.getElementById('denyRecommendationBtn');
        
        if (acceptRecommendationBtn) {
            acceptRecommendationBtn.addEventListener('click', acceptRecommendation);
        }
        
        if (denyRecommendationBtn) {
            denyRecommendationBtn.addEventListener('click', denyRecommendation);
        }
        
        // API connection retry button
        const retryConnectionBtn = document.getElementById('retry-connection-btn');
        if (retryConnectionBtn) {
            retryConnectionBtn.addEventListener('click', () => {
                if (typeof addConnectionLog === 'function') {
                    addConnectionLog("Manual connection retry initiated.");
                }
                if (typeof startAPIConnectionProcess === 'function') {
                    startAPIConnectionProcess();
                }
            });
        }
        
        // Start game button
        const startGameBtn = document.getElementById('startGameBtn');
        if (startGameBtn) {
            startGameBtn.addEventListener('click', () => {
                if (apiConnected) {
                    if (typeof startGame === 'function') {
                        startGame();
                    }
                } else {
                    alert("Please wait for API connection to be established.");
                }
            });
        }
        
        console.log("Game event listeners setup complete");
    }
    
    // Call the setup function
    setupGameEventListeners();

    // Add a function to update the statistics display
    function updateStatistics() {
        try {
            if (!gameState || !gameState.stats) {
                console.log("Game statistics not available yet");
                return;
            }
            
            // Update total moves
            const totalMovesElement = document.getElementById('total-moves');
            if (totalMovesElement) {
                totalMovesElement.textContent = gameState.stats.totalMoves || 0;
            }
            
            // Update words played
            const wordsPlayedElement = document.getElementById('words-played');
            if (wordsPlayedElement) {
                wordsPlayedElement.textContent = gameState.stats.wordsPlayed || 0;
            }
            
            // Update total score
            const totalScoreElement = document.getElementById('total-score');
            if (totalScoreElement) {
                totalScoreElement.textContent = gameState.stats.totalScore || 0;
            }
            
            // Update highest word
            const highestWordElement = document.getElementById('highest-word');
            if (highestWordElement) {
                const highestWord = gameState.stats.highestWord || { word: 'None', score: 0 };
                highestWordElement.textContent = `${highestWord.word} (${highestWord.score})`;
            }
            
            // Update chat interactions
            const chatInteractionsElement = document.getElementById('chat-interactions');
            if (chatInteractionsElement) {
                chatInteractionsElement.textContent = gameState.stats.totalChats || 0;
            }
            
            console.log("Statistics updated");
        } catch (error) {
            console.error("Error updating statistics:", error);
        }
    }

    // Ensure the game state includes statistics
    function initializeGame() {
        try {
            console.log("Initializing game state...");
            
            // Create the tile bag
            createTileBag();
            
            // Initialize players
            gameState.players = [];
            
            // Add human player
            const playerName = document.getElementById("playerName")?.value || "Player";
            gameState.players.push({
                index: 0,
                name: playerName,
                score: 0,
                tiles: [],
                isHuman: true
            });
            
            // Get number of opponents
            const numOpponents = parseInt(document.getElementById("numOpponents")?.value || "2");
            console.log(`Creating ${numOpponents} AI opponents`);
            
            // Add CPU players
            for (let i = 1; i <= numOpponents; i++) {
                const difficultySelect = document.getElementById(`cpu-${i}-difficulty`);
                const difficulty = difficultySelect ? difficultySelect.value : "medium";
                
                gameState.players.push({
                    index: i,
                    name: `CPU ${i}`,
                    score: 0,
                    tiles: [],
                    isHuman: false,
                    difficulty: difficulty
                });
            }
            
            // Initialize game statistics
            gameState.stats = {
                totalMoves: 0,
                wordsPlayed: 0,
                totalScore: 0,
                highestWord: { word: '', score: 0 },
                totalChats: 0,
                recommendationsAccepted: 0,
                recommendationsDenied: 0,
                gameStartTime: new Date()
            };
            
            // Update scoreboard
            updateScoreboard();
    
    // Update remaining tiles count
    updateRemainingTilesCount();
    
            console.log("Game initialization complete", gameState);
            return true;
        } catch (error) {
            console.error("Error initializing game:", error);
            return false;
        }
    }

    // Fix scoreboard update function to handle missing elements
function updateScoreboard() {
        try {
            console.log("Updating scoreboard...");
            
            // Get main scoreboard container
            const scoreContainer = document.querySelector('.score-container');
            if (!scoreContainer) {
                console.error("Score container not found");
                return;
            }
            
            // Clear current scores if needed
            let playerInfoElements = scoreContainer.querySelectorAll('.player-info');
            if (playerInfoElements.length === 0) {
                // Create player info elements if they don't exist
                for (let i = 0; i < gameState.players.length; i++) {
                    const player = gameState.players[i];
                    const playerInfo = document.createElement('div');
                    playerInfo.className = 'player-info';
                    
                    // Add icon based on player type
                    const icon = document.createElement('i');
                    icon.className = player.isHuman ? 'fas fa-user' : 'fas fa-robot';
                    playerInfo.appendChild(icon);
                    
                    // Add player name and score
                    const nameSpan = document.createElement('span');
                    nameSpan.textContent = ` ${player.name}: `;
                    playerInfo.appendChild(nameSpan);
                    
                    // Add score value
                    const scoreSpan = document.createElement('span');
                    scoreSpan.className = 'score-value';
                    scoreSpan.textContent = player.score;
                    scoreSpan.id = `player-${i}-score`;
                    playerInfo.appendChild(scoreSpan);
                    
                    scoreContainer.appendChild(playerInfo);
                }
        } else {
                // Update existing player scores
                for (let i = 0; i < gameState.players.length; i++) {
                    const player = gameState.players[i];
                    const scoreElement = document.getElementById(`player-${i}-score`);
                    if (scoreElement) {
                        scoreElement.textContent = player.score;
                        console.log(`Updated ${player.name} score: ${player.score}`);
                    } else {
                        console.error(`Score element for ${player.name} not found`);
                    }
                }
            }
    } catch (error) {
            console.error("Error updating scoreboard:", error);
        }
    }

    // Function to initialize statistics section
    function initializeStatistics() {
        try {
            // Create statistics section if it doesn't exist
            const rightPanel = document.getElementById('right-panel');
            if (!rightPanel) {
                console.error("Right panel not found");
        return;
    }
    
            // Check if statistics section already exists
            let statsSection = document.getElementById('statistics-section');
            if (!statsSection) {
                // Create statistics section
                statsSection = document.createElement('div');
                statsSection.id = 'statistics-section';
                statsSection.className = 'statistics-section';
                
                // Add title
                const title = document.createElement('h2');
                title.textContent = 'Game Statistics';
                statsSection.appendChild(title);
                
                // Add content container
                const statsContent = document.createElement('div');
                statsContent.className = 'stats-content';
                
                // Add statistics items
                const statsItems = [
                    { id: 'total-moves', label: 'Total Moves' },
                    { id: 'words-played', label: 'Words Played' },
                    { id: 'total-score', label: 'Total Score' },
                    { id: 'highest-word', label: 'Highest Word' },
                    { id: 'chat-interactions', label: 'Chat Interactions' }
                ];
                
                statsItems.forEach(item => {
                    const statRow = document.createElement('div');
                    statRow.className = 'stat-row';
                    
                    const statLabel = document.createElement('span');
                    statLabel.className = 'stat-label';
                    statLabel.textContent = item.label + ':';
                    
                    const statValue = document.createElement('span');
                    statValue.className = 'stat-value';
                    statValue.id = item.id;
                    statValue.textContent = '0';
                    
                    statRow.appendChild(statLabel);
                    statRow.appendChild(statValue);
                    statsContent.appendChild(statRow);
                });
                
                statsSection.appendChild(statsContent);
                
                // Add to the right panel, before the statisticsBtn if it exists
                const statsBtn = document.getElementById('statisticsBtn');
                if (statsBtn) {
                    rightPanel.insertBefore(statsSection, statsBtn);
                } else {
                    rightPanel.appendChild(statsSection);
                }
                
                console.log("Statistics section initialized");
            }
            
            // Update the statistics with initial values
            if (gameState && gameState.stats) {
                updateStatistics();
            }
        } catch (error) {
            console.error("Error initializing statistics section:", error);
        }
    }

    function initializeUI() {
        try {
            console.log("Initializing UI components...");
            
            // Initialize the player rack with empty slots
            initializePlayerRack();
            
            // Initialize the statistics section
            initializeStatistics();
            
            // Initialize the move history panel
            initializeMoveHistory();
            
            // Set up API connection status indicator
            updateAPIStatus(false, "Not connected");
            
            // Set up the drag and drop events
            setupTileDragEvents();
            
            console.log("UI initialization complete");
        } catch (error) {
            console.error("Error initializing UI components:", error);
        }
    }

    // Function to initialize move history panel
    function initializeMoveHistory() {
        try {
            // Get or create the move history container
            let moveHistoryContainer = document.getElementById('move-history');
            
            if (!moveHistoryContainer) {
                // Find the right panel
                const rightPanel = document.getElementById('right-panel');
                if (!rightPanel) {
                    console.error("Right panel not found");
        return;
    }
    
                // Create move history section
                moveHistoryContainer = document.createElement('div');
                moveHistoryContainer.id = 'move-history';
                moveHistoryContainer.className = 'move-history';
                
                // Add title
                const title = document.createElement('h2');
                title.textContent = 'Move History';
                moveHistoryContainer.appendChild(title);
                
                // Add content container
                const historyContent = document.createElement('div');
                historyContent.className = 'history-content';
                historyContent.id = 'history-content';
                moveHistoryContainer.appendChild(historyContent);
                
                // Add to the right panel
                rightPanel.appendChild(moveHistoryContainer);
                
                console.log("Move history panel initialized");
            } else {
                // Clear existing history entries
                const historyContent = document.getElementById('history-content');
                if (historyContent) {
                    historyContent.innerHTML = '';
                }
            }
        } catch (error) {
            console.error("Error initializing move history:", error);
        }
    }

    // Function to update the move history
    function updateMoveHistory(playerName, word, score, turn) {
        try {
            const historyContent = document.getElementById('history-content');
            if (!historyContent) {
                console.error("Move history content container not found");
        return;
    }
    
            // Create move entry
            const moveEntry = document.createElement('div');
            moveEntry.className = 'move-entry';
            
            // Add turn number
            const turnSpan = document.createElement('span');
            turnSpan.className = 'turn-number';
            turnSpan.textContent = `${turn}. `;
            moveEntry.appendChild(turnSpan);
            
            // Add player name
            const playerSpan = document.createElement('span');
            playerSpan.className = 'player-name';
            playerSpan.textContent = playerName;
            moveEntry.appendChild(playerSpan);
            
            // Add move details
            const moveDetails = document.createElement('span');
            moveDetails.className = 'move-details';
            moveDetails.textContent = ` played "${word}" for ${score} points`;
            moveEntry.appendChild(moveDetails);
            
            // Add timestamp
            const timestamp = document.createElement('div');
            timestamp.className = 'move-timestamp';
            const time = new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
            timestamp.textContent = time;
            moveEntry.appendChild(timestamp);
            
            // Add to history container (at the top)
            historyContent.insertBefore(moveEntry, historyContent.firstChild);
            
            console.log(`Added move to history: ${playerName} played "${word}" for ${score} points`);
        } catch (error) {
            console.error("Error updating move history:", error);
        }
    }

    // Make sure startGame calls initializeUI
    function startGame() {
        try {
            console.log("Starting game...");
            
            // Hide start menu and show game container
            const startMenu = document.getElementById('start-menu');
            const gameContainer = document.getElementById('game-container');
            
            if (startMenu) startMenu.style.display = 'none';
            if (gameContainer) gameContainer.style.display = 'flex';
            
            // Initialize the game state
            if (!initializeGame()) {
                console.error("Failed to initialize game state");
                return;
            }
            
            // Initialize the board
            initializeBoard();
            
            // Initialize UI components
            initializeUI();
            
            // Draw initial tiles for players
            for (const player of gameState.players) {
                drawTilesForPlayer(player, 7);
                updateRack(player);
            }
            
            // Start the game timer
            startGameTimer();
            
            // Update the remaining tiles count
            updateRemainingTilesCount();
            
            // Connect to Volunteer Science API
            connectToVolunteerScienceAPI();
            
            console.log("Game started successfully");
            
            // Set the current player (human player goes first)
            gameState.currentPlayerIndex = 0;
            highlightCurrentPlayer();
            
            // Show a welcome message
            if (document.getElementById('connection-log')) {
                addConnectionLog("Welcome to Scrabble! It's your turn to play.");
            }
        } catch (error) {
            console.error("Error starting game:", error);
        }
    }

    // Function to toggle statistics visibility
    function toggleStatistics() {
        try {
            const statsSection = document.getElementById('statistics-section');
            if (!statsSection) {
                console.error("Statistics section not found");
                return;
            }
            
            if (statsSection.style.display === 'none') {
                statsSection.style.display = 'block';
                // Update statistics when showing
                updateStatistics();
    } else {
                statsSection.style.display = 'none';
            }
            
            console.log("Statistics visibility toggled");
        } catch (error) {
            console.error("Error toggling statistics:", error);
        }
    }

    // Function to set up board drop events
    function setupBoardDropEvents() {
        try {
            console.log("Setting up board drop events...");
            const board = document.getElementById('board');
            if (!board) {
                console.error("Board element not found");
                return;
            }
            
            // Get all cells
            const cells = board.querySelectorAll('.board-cell');
            
            cells.forEach(cell => {
                // Remove any existing event listeners to avoid duplicates
                cell.removeEventListener('dragover', handleDragOver);
                cell.removeEventListener('drop', handleDrop);
                
                // Add new event listeners
                cell.addEventListener('dragover', handleDragOver);
                cell.addEventListener('drop', handleDrop);
            });
            
            console.log(`Drop events set up for ${cells.length} board cells`);
        } catch (error) {
            console.error("Error setting up board drop events:", error);
        }
    }

    // Function to handle drag over event
    function handleDragOver(e) {
        e.preventDefault();
        e.dataTransfer.dropEffect = 'move';
        this.classList.add('drag-over');
    }

    // Function to handle drop event
    function handleDrop(e) {
        e.preventDefault();
        this.classList.remove('drag-over');
        
        const tileId = e.dataTransfer.getData('text/plain');
        const tile = document.getElementById(tileId);
        
        if (!tile) {
            console.error("Dropped tile element not found:", tileId);
            return;
        }
        
        // Get row and column from the cell's data attributes
        const row = parseInt(this.dataset.row);
        const col = parseInt(this.dataset.col);
        
        // Check if the cell is already occupied
        if (this.querySelector('.tile')) {
            console.log("Cell already occupied");
            return;
        }
        
        // Place the tile on the board
        const playerIndex = 0; // Human player index
        placeTile(playerIndex, tileId, row, col);
        
        // Update the submit word button state
        checkSubmitWordAvailability();
    }

    // Function to initialize player rack with empty slots
    function initializePlayerRack() {
        try {
            console.log("Initializing player rack...");
            const rack = document.getElementById('rack');
            if (!rack) {
                console.error("Rack element not found");
                return;
            }
            
            // Clear current rack
            rack.innerHTML = '';
            
            // Create 7 empty tile slots
            for (let i = 0; i < 7; i++) {
                const slotDiv = document.createElement('div');
                slotDiv.className = 'tile-slot';
                slotDiv.dataset.index = i;
                rack.appendChild(slotDiv);
            }
            
            console.log("Player rack initialized with 7 empty slots");
        } catch (error) {
            console.error("Error initializing player rack:", error);
        }
    }

    // Function to draw tiles for player
    function drawTilesForPlayer(player, count) {
        try {
            if (!player) {
                console.error("Invalid player object");
                return;
            }
            
            if (!gameState.tileBag || gameState.tileBag.length === 0) {
                console.log("Tile bag is empty");
                return;
            }
            
            console.log(`Drawing up to ${count} tiles for ${player.name}...`);
            
            // Determine how many tiles to draw
            const currentTileCount = player.tiles ? player.tiles.length : 0;
            const neededTiles = Math.min(count, 7 - currentTileCount);
            
            if (neededTiles <= 0) {
                console.log(`Player ${player.name} already has enough tiles`);
                return;
            }
            
            // Draw tiles from the bag
            for (let i = 0; i < neededTiles && gameState.tileBag.length > 0; i++) {
                const tile = gameState.tileBag.pop();
                if (!player.tiles) player.tiles = [];
                player.tiles.push(tile);
                console.log(`Drew tile "${tile.letter}" for ${player.name}`);
            }
            
            // Update the remaining tiles count
            updateRemainingTilesCount();
            
            // Update the player's rack display
            updateRack(player);
            
            console.log(`Drew ${neededTiles} tiles for ${player.name}`);
        } catch (error) {
            console.error("Error drawing tiles for player:", error);
        }
    }

    // Fix the API status update function
    function updateAPIStatus(connected, message) {
        try {
            console.log(`Updating API status: connected=${connected}, message=${message}`);
            const statusIndicator = document.getElementById('connection-status');
            const statusText = document.getElementById('connection-text');
            
            if (!statusIndicator || !statusText) {
                console.error("API status elements not found");
        return;
    }
    
            // Update status indicator
            statusIndicator.className = 'status-indicator ' + (connected ? 'connected' : 'disconnected');
            
            // Update status text
            statusText.textContent = message || (connected ? 'Connected' : 'Disconnected');
            
            console.log(`API status updated: ${statusText.textContent}`);
        } catch (error) {
            console.error("Error updating API status:", error);
        }
    }

    // Fix the connection log function
    function addConnectionLog(message, type = 'info') {
        try {
            console.log(`Adding to connection log: ${message} (${type})`);
            const logContainer = document.getElementById('connection-log');
            
            if (!logContainer) {
                console.error("Connection log container not found");
                return;
            }
            
            const logEntry = document.createElement('div');
            logEntry.className = `log-entry ${type}`;
            logEntry.textContent = message;
            
            // Add timestamp
            const timestamp = new Date().toLocaleTimeString();
            const timeSpan = document.createElement('span');
            timeSpan.className = 'log-timestamp';
            timeSpan.textContent = `[${timestamp}] `;
            logEntry.prepend(timeSpan);
            
            // Add to the log (at the top)
            logContainer.insertBefore(logEntry, logContainer.firstChild);
            
            // Limit the number of log entries to prevent overflow
            if (logContainer.children.length > 50) {
                logContainer.removeChild(logContainer.lastChild);
            }
        } catch (error) {
            console.error("Error adding to connection log:", error);
        }
    }

    // Highlight the current player
    function highlightCurrentPlayer() {
        try {
            console.log("Highlighting current player...");
            
            if (!gameState || typeof gameState.currentPlayerIndex !== 'number') {
                console.error("Game state or current player index missing");
                return;
            }
            
            // Clear all highlights
            const playerInfoDivs = document.querySelectorAll('.player-info');
            playerInfoDivs.forEach(div => {
                div.classList.remove('current-player');
                const icon = div.querySelector('i');
                if (icon) icon.classList.remove('current-player-icon');
            });
            
            // Get the current player index
            const currentIndex = gameState.currentPlayerIndex;
            
            // Highlight the current player
            const currentPlayerDiv = document.getElementById(`player-${currentIndex}-name`);
            if (currentPlayerDiv) {
                currentPlayerDiv.parentElement.classList.add('current-player');
                const icon = currentPlayerDiv.parentElement.querySelector('i');
                if (icon) icon.classList.add('current-player-icon');
                console.log(`Highlighted player ${currentIndex}`);
            } else {
                console.error(`Player element for index ${currentIndex} not found`);
            }
        } catch (error) {
            console.error("Error highlighting current player:", error);
        }
    }

// Setup additional event listeners on document ready
document.addEventListener('DOMContentLoaded', function() {
    console.log("Document ready - checking for API connection");
    // Test for API connection on page load
    if (typeof startAPIConnectionProcess === 'function') {
        startAPIConnectionProcess();
    }
});

// When the document is ready, initialize the game
document.addEventListener("DOMContentLoaded", function() {
    console.log("Document ready - checking for API connection");
    
    // Initialize game components
    try {
        // Add initial log entry
        addConnectionLog("Initializing application...", "info");
        
        // Start the API connection process
        startAPIConnectionProcess();
        
        // Set up periodic connection checks
        startPeriodicConnectionCheck();
    } catch (error) {
        console.error("Error during initialization:", error);
        // Try to log the error if possible
        if (typeof addConnectionLog === 'function') {
            addConnectionLog("Initialization error: " + error.message, "error");
        }
    }
});

// ... existing code ...

// UI Event Handlers and Game Flow Control
class GameController {
    constructor(gameState, boardManager) {
        this.gameState = gameState;
        this.boardManager = boardManager;
        this.dragSource = null;
        this.isDragging = false;
        this.setupEventListeners();
    }

    setupEventListeners() {
        // Start menu events
        document.getElementById('start-game').addEventListener('click', () => this.startGame());
        document.getElementById('retry-connection').addEventListener('click', () => this.retryConnection());

        // Game control events
        document.getElementById('submit-word').addEventListener('click', () => this.submitWord());
        document.getElementById('pass-turn').addEventListener('click', () => this.passTurn());
        document.getElementById('shuffle').addEventListener('click', () => this.shuffleRack());
        document.getElementById('exchange').addEventListener('click', () => this.startExchange());
        document.getElementById('quit').addEventListener('click', () => this.quitGame());

        // Chat interface events
        document.getElementById('send-message').addEventListener('click', () => this.sendChatMessage());
        document.getElementById('chat-input').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') this.sendChatMessage();
        });

        // Recommendation controls - Fixed IDs
        document.getElementById('accept-recommendation').addEventListener('click', () => this.acceptRecommendation());
        document.getElementById('deny-recommendation').addEventListener('click', () => this.denyRecommendation());

        // Sound and debug toggles
        document.getElementById('sound-toggle').addEventListener('click', () => this.toggleSound());
        document.getElementById('debug-toggle').addEventListener('click', () => this.toggleDebug());

        // Drag and drop events
        this.setupDragAndDrop();
    }

    setupDragAndDrop() {
        // Add drag events to tiles in racks
        document.querySelectorAll('.tile').forEach(tile => {
            tile.addEventListener('dragstart', (e) => this.handleDragStart(e));
            tile.addEventListener('dragend', (e) => this.handleDragEnd(e));
        });

        // Add drop events to board cells
        document.querySelectorAll('.cell').forEach(cell => {
            cell.addEventListener('dragover', (e) => this.handleDragOver(e));
            cell.addEventListener('drop', (e) => this.handleDrop(e));
        });
    }

    handleDragStart(e) {
        if (!this.gameState.getCurrentPlayer().isHuman) return;
        
        this.isDragging = true;
        this.dragSource = e.target;
        e.target.classList.add('dragging');
        
        // Store original position
        this.dragSource.dataset.originalRow = this.dragSource.dataset.row;
        this.dragSource.dataset.originalCol = this.dragSource.dataset.col;
    }

    handleDragEnd(e) {
        this.isDragging = false;
        e.target.classList.remove('dragging');
        this.dragSource = null;
    }

    handleDragOver(e) {
        e.preventDefault();
        if (!this.isDragging) return;
        
        const cell = e.target.closest('.cell');
        if (!cell) return;
        
        // Remove highlight from all cells
        document.querySelectorAll('.cell').forEach(c => c.classList.remove('highlight'));
        
        // Highlight valid drop target
        if (this.boardManager.isValidPlacement(
            parseInt(cell.dataset.row),
            parseInt(cell.dataset.col)
        )) {
            cell.classList.add('highlight');
        }
    }

    handleDrop(e) {
        e.preventDefault();
        if (!this.isDragging || !this.dragSource) return;
        
        const cell = e.target.closest('.cell');
        if (!cell) return;
        
        const row = parseInt(cell.dataset.row);
        const col = parseInt(cell.dataset.col);
        
        // Remove highlight from all cells
        document.querySelectorAll('.cell').forEach(c => c.classList.remove('highlight'));
        
        // Check if placement is valid
        if (this.boardManager.isValidPlacement(row, col)) {
            // Remove tile from original position if it was on the board
            if (this.dragSource.dataset.originalRow && this.dragSource.dataset.originalCol) {
                this.boardManager.removeTile(
                    parseInt(this.dragSource.dataset.originalRow),
                    parseInt(this.dragSource.dataset.originalCol)
                );
            }
            
            // Place tile in new position
            const tile = {
                letter: this.dragSource.dataset.letter,
                points: parseInt(this.dragSource.dataset.points)
            };
            
            if (this.boardManager.placeTile(tile, row, col)) {
                // Update tile position
                this.dragSource.dataset.row = row;
                this.dragSource.dataset.col = col;
                
                // Play sound
                document.getElementById('sound-tilePlaced').play();
            } else {
                // Return tile to original position if placement failed
                if (this.dragSource.dataset.originalRow && this.dragSource.dataset.originalCol) {
                    this.boardManager.placeTile(
                        tile,
                        parseInt(this.dragSource.dataset.originalRow),
                        parseInt(this.dragSource.dataset.originalCol)
                    );
                }
            }
        }
        
        this.updateBoardUI();
    }

    async submitWord() {
        const result = await this.boardManager.commitMove();
        
        if (result.valid) {
            // Play success sound
            document.getElementById('sound-tilePlaced').play();
            
            // Update UI
            this.updateUI();
            
            // Update statistics
            this.gameState.statistics.totalMoves++;
            this.gameState.statistics.wordsPlayed++;
            this.gameState.statistics.totalScore += result.score;
            
            if (result.score > this.gameState.statistics.highestWord.score) {
                this.gameState.statistics.highestWord = {
                    word: result.words[0],
                    score: result.score
                };
            }
            
            // Move to next player
            this.gameState.nextTurn();
            
            // Handle CPU turns if needed
            if (!this.gameState.getCurrentPlayer().isHuman) {
                await this.handleCPUTurn();
            }
        } else {
            // Play error sound
            document.getElementById('sound-invalidMove').play();
            
            // Show error message
            this.showMessage(result.message, 'error');
        }
    }

    passTurn() {
        this.gameState.moveHistory.push({
            type: 'pass',
            player: this.gameState.getCurrentPlayer().name
        });

        this.gameState.nextTurn();
        this.updateUI();

        if (!this.gameState.getCurrentPlayer().isHuman) {
            this.handleCPUTurn();
        }
    }

    shuffleRack() {
        const player = this.gameState.getCurrentPlayer();
        if (!player.isHuman) return;

        const rack = player.rack;
        for (let i = rack.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [rack[i], rack[j]] = [rack[j], rack[i]];
        }

        this.updateRackUI();
    }

    startExchange() {
        const player = this.gameState.getCurrentPlayer();
        if (!player.isHuman) return;

        // Enable tile selection mode
        const rack = document.getElementById('player-rack');
        rack.classList.add('exchange-mode');
        
        // Show exchange confirmation button
        const confirmBtn = document.createElement('button');
        confirmBtn.className = 'primary-button';
        confirmBtn.textContent = 'Confirm Exchange';
        confirmBtn.onclick = () => this.confirmExchange();
        
        document.querySelector('.game-controls').appendChild(confirmBtn);
    }

    confirmExchange() {
        const player = this.gameState.getCurrentPlayer();
        const selectedTiles = Array.from(document.querySelectorAll('.rack .tile.selected'));
        
        if (selectedTiles.length === 0) {
            this.showMessage('Please select tiles to exchange', 'error');
            return;
        }

        // Remove selected tiles from rack
        selectedTiles.forEach(tile => {
            const index = player.rack.findIndex(t => t.id === tile.dataset.id);
            if (index !== -1) {
                player.rack.splice(index, 1);
            }
            tile.remove();
        });

        // Draw new tiles
        this.gameState.drawTiles(player, selectedTiles.length);
        
        // Update UI
        this.updateRackUI();
        
        // Remove exchange mode
        document.getElementById('player-rack').classList.remove('exchange-mode');
        document.querySelector('.game-controls').removeChild(
            document.querySelector('.game-controls .primary-button')
        );

        // Move to next player
        this.gameState.nextTurn();
        
        if (!this.gameState.getCurrentPlayer().isHuman) {
            this.handleCPUTurn();
        }
    }

    async handleCPUTurn() {
        const cpu = this.gameState.getCurrentPlayer();
        if (cpu.isHuman) return;

        // Show thinking indicator
        this.showMessage(`${cpu.name} is thinking...`, 'info');

        try {
            // Get AI move recommendation
            const move = await this.getAIMove(cpu);
            
            if (move) {
                // Place tiles
                move.tiles.forEach(tile => {
                    this.boardManager.placeTile(tile, tile.row, tile.col);
                });

                // Submit move
                await this.submitWord();
            } else {
                // No valid move found, pass turn
                this.passTurn();
            }
        } catch (error) {
            console.error('Error during CPU turn:', error);
            this.passTurn();
        }
    }

    async getAIMove(cpu) {
        const prompt = this.prepareGameStateContext();
        const response = await callOpenAI(prompt, {
            temperature: cpu.difficulty === 'easy' ? 0.7 : 
                        cpu.difficulty === 'medium' ? 0.5 : 0.3
        });

        // Parse AI response and return move
        return this.parseAIMove(response);
    }

    updateUI() {
        this.updateBoardUI();
        this.updateRackUI();
        this.updateScoreboard();
        this.updateMoveHistory();
        this.updateGameInfo();
        this.highlightCurrentPlayer();
    }

    updateBoardUI() {
        const board = document.getElementById('board');
        const cells = board.querySelectorAll('.cell');
        
        cells.forEach(cell => {
            const row = parseInt(cell.dataset.row);
            const col = parseInt(cell.dataset.col);
            const tile = this.boardManager.getTileAt(row, col);
            
            if (tile) {
                // Update or create tile element
                let tileElement = cell.querySelector('.tile');
                if (!tileElement) {
                    tileElement = document.createElement('div');
                    tileElement.className = 'tile';
                    cell.appendChild(tileElement);
                }
                
                tileElement.dataset.letter = tile.letter;
                tileElement.dataset.points = tile.points;
                tileElement.dataset.row = row;
                tileElement.dataset.col = col;
                
                // Add drag events if it's the current player's turn
                if (this.gameState.getCurrentPlayer().isHuman) {
                    tileElement.draggable = true;
                    tileElement.addEventListener('dragstart', (e) => this.handleDragStart(e));
                    tileElement.addEventListener('dragend', (e) => this.handleDragEnd(e));
                } else {
                    tileElement.draggable = false;
                    tileElement.removeEventListener('dragstart', this.handleDragStart);
                    tileElement.removeEventListener('dragend', this.handleDragEnd);
                }
                
                tileElement.textContent = tile.letter;
            } else {
                // Remove tile element if no tile at position
                const tileElement = cell.querySelector('.tile');
                if (tileElement) {
                    tileElement.remove();
                }
            }
        });
    }

    updateRackUI() {
        const player = this.gameState.getCurrentPlayer();
        const rack = document.getElementById('player-rack');
        rack.innerHTML = '';

        player.rack.forEach(tile => {
            const tileElement = document.createElement('div');
            tileElement.className = 'tile';
            tileElement.draggable = true;
            tileElement.dataset.letter = tile.letter;
            tileElement.dataset.points = tile.points;
            tileElement.dataset.id = tile.id;
            tileElement.textContent = tile.letter;
            rack.appendChild(tileElement);
        });
    }

    updateScoreboard() {
        const playerScore = document.getElementById('player-score');
        const cpuScores = document.getElementById('cpu-scores');
        
        playerScore.textContent = `Player: ${this.gameState.scores.get(this.gameState.players[0].name)}`;
        
        cpuScores.innerHTML = this.gameState.players
            .slice(1)
            .map(player => `${player.name}: ${this.gameState.scores.get(player.name)}`)
            .join('<br>');
    }

    updateMoveHistory() {
        const moveHistory = document.getElementById('move-history');
        moveHistory.innerHTML = '';
        
        this.gameState.moveHistory.forEach((move, index) => {
            const moveElement = document.createElement('div');
            moveElement.className = 'move-entry';
            
            const moveNumber = document.createElement('span');
            moveNumber.className = 'move-number';
            moveNumber.textContent = `${index + 1}.`;
            
            const playerName = document.createElement('span');
            playerName.className = 'player-name';
            playerName.textContent = move.player.name;
            
            const moveDetails = document.createElement('span');
            moveDetails.className = 'move-details';
            
            if (move.type === 'word') {
                moveDetails.textContent = `${move.word} (${move.score} points)`;
            } else if (move.type === 'pass') {
                moveDetails.textContent = 'Passed';
            } else if (move.type === 'exchange') {
                moveDetails.textContent = `Exchanged ${move.tiles.length} tiles`;
            }
            
            moveElement.appendChild(moveNumber);
            moveElement.appendChild(playerName);
            moveElement.appendChild(moveDetails);
            
            moveHistory.appendChild(moveElement);
        });
        
        // Scroll to bottom
        moveHistory.scrollTop = moveHistory.scrollHeight;
    }

    updateGameInfo() {
        document.getElementById('remaining-tiles').textContent = 
            `Remaining Tiles: ${this.gameState.remainingTiles}`;
        document.getElementById('round-number').textContent = 
            `Round: ${this.gameState.roundCount}`;
    }

    highlightCurrentPlayer() {
        const currentPlayer = this.gameState.getCurrentPlayer();
        document.getElementById('game-status').textContent = 
            `Current Player: ${currentPlayer.name}`;
    }

    showMessage(message, type = 'info') {
        const messageElement = document.createElement('div');
        messageElement.className = `message ${type}`;
        messageElement.textContent = message;
        
        document.querySelector('.game-info').appendChild(messageElement);
        
        setTimeout(() => {
            messageElement.remove();
        }, 3000);
    }

    toggleSound() {
        const soundToggle = document.getElementById('sound-toggle');
        const isMuted = soundToggle.classList.toggle('muted');
        soundToggle.innerHTML = isMuted ? 
            '<i class="fas fa-volume-mute"></i>' : 
            '<i class="fas fa-volume-up"></i>';
    }

    toggleDebug() {
        const debugPanel = document.getElementById('debug-panel');
        debugPanel.style.display = 
            debugPanel.style.display === 'none' ? 'block' : 'none';
    }

    quitGame() {
        if (confirm('Are you sure you want to quit the current game?')) {
            // Reset game state
            this.gameState = new GameState();
            this.boardManager = new BoardManager(this.gameState);
            
            // Reset UI
            this.updateUI();
            
            // Hide game area
            document.getElementById('game-area').style.display = 'none';
            
            // Show start menu
            document.getElementById('start-menu').style.display = 'block';
            
            // Play game end sound
            document.getElementById('sound-gameEnd').play();
        }
    }

    showGameEndModal() {
        const modal = document.getElementById('game-end-modal');
        const stats = this.calculateGameStatistics();
        
        // Update modal content
        document.getElementById('game-winner').textContent = stats.winner.name;
        document.getElementById('final-score').textContent = stats.winner.score;
        document.getElementById('total-moves').textContent = stats.totalMoves;
        document.getElementById('words-played').textContent = stats.wordsPlayed;
        document.getElementById('highest-word').textContent = `${stats.highestWord.word} (${stats.highestWord.score} points)`;
        
        // Show modal
        modal.style.display = 'block';
        
        // Play game end sound
        document.getElementById('sound-gameEnd').play();
    }

    calculateGameStatistics() {
        const stats = {
            winner: { name: '', score: -1 },
            totalMoves: this.gameState.statistics.totalMoves,
            wordsPlayed: this.gameState.statistics.wordsPlayed,
            highestWord: this.gameState.statistics.highestWord
        };
        
        // Find winner
        this.gameState.players.forEach(player => {
            if (player.score > stats.winner.score) {
                stats.winner = {
                    name: player.name,
                    score: player.score
                };
            }
        });
        
        return stats;
    }

    startNewGame() {
        // Reset game state
        this.gameState = new GameState();
        this.boardManager = new BoardManager(this.gameState);
        
        // Reset UI
        this.updateUI();
        
        // Hide game end modal
        document.getElementById('game-end-modal').style.display = 'none';
        
        // Show start menu
        document.getElementById('start-menu').style.display = 'block';
        document.getElementById('game-area').style.display = 'none';
        
        // Play game start sound
        document.getElementById('sound-gameStart').play();
    }
}

// Create global game controller instance
const gameController = new GameController(gameState, boardManager);

// ... existing code ...

class ChatManager {
    constructor() {
        this.messageHistory = [];
        this.isProcessing = false;
        this.setupEventListeners();
    }

    setupEventListeners() {
        const chatInput = document.getElementById('chat-input');
        const sendButton = document.getElementById('send-message');
        
        chatInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.sendMessage();
            }
        });
        
        sendButton.addEventListener('click', () => this.sendMessage());
    }

    async sendMessage() {
        const chatInput = document.getElementById('chat-input');
        const message = chatInput.value.trim();
        
        if (!message || this.isProcessing) return;
        
        // Clear input
        chatInput.value = '';
        
        // Add user message to chat
        this.addMessage(message, 'user');
        
        // Show typing indicator
        const typingIndicator = this.addMessage('Bot is typing...', 'bot', true);
        
        try {
            this.isProcessing = true;
            
            // Get response from API
            const response = await this.getBotResponse(message);
            
            // Remove typing indicator
            typingIndicator.remove();
            
            // Add bot response
            this.addMessage(response, 'bot');
            
            // Update statistics
            gameState.statistics.chatInteractions++;
            
        } catch (error) {
            // Remove typing indicator
            typingIndicator.remove();
            
            // Show error message
            this.addMessage('Sorry, I encountered an error. Please try again.', 'bot error');
        } finally {
            this.isProcessing = false;
        }
    }

    addMessage(text, type, isTemporary = false) {
        const chatMessages = document.getElementById('chat-messages');
        const messageElement = document.createElement('div');
        messageElement.className = `chat-message ${type}`;
        
        const content = document.createElement('div');
        content.className = 'message-content';
        content.textContent = text;
        
        const timestamp = document.createElement('div');
        timestamp.className = 'message-timestamp';
        timestamp.textContent = new Date().toLocaleTimeString();
        
        messageElement.appendChild(content);
        messageElement.appendChild(timestamp);
        
        if (isTemporary) {
            messageElement.classList.add('temporary');
        } else {
            this.messageHistory.push({
                text,
                type,
                timestamp: new Date()
            });
        }
        
        chatMessages.appendChild(messageElement);
        chatMessages.scrollTop = chatMessages.scrollHeight;
        
        return messageElement;
    }

    async getBotResponse(message) {
        // Check API connection status
        if (!apiConnected) {
            throw new Error('API not connected');
        }
        
        // Prepare the request
        const request = {
            messages: [
                {
                    role: 'system',
                    content: 'You are a helpful Scrabble assistant. Provide concise, relevant advice about the game.'
                },
                ...this.messageHistory.map(msg => ({
                    role: msg.type === 'user' ? 'user' : 'assistant',
                    content: msg.text
                })),
                {
                    role: 'user',
                    content: message
                }
            ],
            model: 'gpt-3.5-turbo',
            temperature: 0.7,
            max_tokens: 150
        };
        
        // Send request to API
        const response = await fetch('https://api.openai.com/v1/chat/completions', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${OPENAI_API_KEY}`
            },
            body: JSON.stringify(request)
        });
        
        if (!response.ok) {
            throw new Error('API request failed');
        }
        
        const data = await response.json();
        return data.choices[0].message.content.trim();
    }
}

// API Connection Manager
class APIConnectionManager {
    constructor() {
        this.connected = false;
        this.retryCount = 0;
        this.maxRetries = 3;
        this.setupEventListeners();
    }

    setupEventListeners() {
        const retryButton = document.getElementById('retry-connection');
        retryButton.addEventListener('click', () => this.retryConnection());
    }

    async checkConnection() {
        try {
            const response = await fetch('https://api.openai.com/v1/models', {
                headers: {
                    'Authorization': `Bearer ${OPENAI_API_KEY}`
                }
            });
            
            this.connected = response.ok;
            this.updateConnectionStatus();
            
            if (this.connected) {
                this.retryCount = 0;
            }
            
        } catch (error) {
            this.connected = false;
            this.updateConnectionStatus();
        }
    }

    updateConnectionStatus() {
        const statusElement = document.getElementById('connection-status');
        const statusText = document.getElementById('connection-status-text');
        const retryButton = document.getElementById('retry-connection');
        
        if (this.connected) {
            statusElement.classList.remove('disconnected');
            statusElement.classList.add('connected');
            statusText.textContent = 'Connected';
            retryButton.style.display = 'none';
        } else {
            statusElement.classList.remove('connected');
            statusElement.classList.add('disconnected');
            statusText.textContent = 'Disconnected';
            retryButton.style.display = 'block';
        }
    }

    async retryConnection() {
        if (this.retryCount >= this.maxRetries) {
            this.showError('Maximum retry attempts reached. Please check your API key and try again later.');
            return;
        }
        
        this.retryCount++;
        await this.checkConnection();
    }

    showError(message) {
        const errorElement = document.createElement('div');
        errorElement.className = 'error-message';
        errorElement.textContent = message;
        
        document.getElementById('connection-status').appendChild(errorElement);
        
        setTimeout(() => {
            errorElement.remove();
        }, 5000);
    }
}

// Initialize managers
const chatManager = new ChatManager();
const apiConnectionManager = new APIConnectionManager();

// Check API connection on page load
document.addEventListener('DOMContentLoaded', () => {
    apiConnectionManager.checkConnection();
});

// ... rest of the code ...

class SoundManager {
    constructor() {
        this.sounds = {
            gameStart: document.getElementById('sound-gameStart'),
            tilePlaced: document.getElementById('sound-tilePlaced'),
            invalidMove: document.getElementById('sound-invalidMove'),
            turnStart: document.getElementById('sound-turnStart'),
            gameEnd: document.getElementById('sound-gameEnd')
        };
        
        this.enabled = true;
        this.setupEventListeners();
    }

    setupEventListeners() {
        const soundToggle = document.getElementById('sound-toggle');
        soundToggle.addEventListener('click', () => this.toggleSound());
    }

    toggleSound() {
        this.enabled = !this.enabled;
        const soundToggle = document.getElementById('sound-toggle');
        soundToggle.classList.toggle('muted');
        soundToggle.title = this.enabled ? 'Mute Sound' : 'Unmute Sound';
    }

    play(soundName) {
        if (!this.enabled || !this.sounds[soundName]) return;
        
        // Reset sound to start
        this.sounds[soundName].currentTime = 0;
        
        // Play sound
        this.sounds[soundName].play().catch(error => {
            console.warn(`Failed to play sound ${soundName}:`, error);
        });
    }
}

class ButtonStateManager {
    constructor() {
        this.buttons = {
            submitWord: document.getElementById('submit-word'),
            passTurn: document.getElementById('pass-turn'),
            shuffle: document.getElementById('shuffle'),
            exchange: document.getElementById('exchange'),
            quit: document.getElementById('quit')
        };
    }

    updateButtonStates(gameState) {
        const currentPlayer = gameState.getCurrentPlayer();
        const isHumanTurn = currentPlayer.isHuman;
        const hasTiles = currentPlayer.rack.length > 0;
        
        // Submit Word button
        this.buttons.submitWord.disabled = !isHumanTurn || !hasTiles;
        this.buttons.submitWord.title = !isHumanTurn ? 
            'Not your turn' : 
            !hasTiles ? 'No tiles to play' : 'Submit your word';
        
        // Pass Turn button
        this.buttons.passTurn.disabled = !isHumanTurn;
        this.buttons.passTurn.title = !isHumanTurn ? 
            'Not your turn' : 
            'Skip your turn';
        
        // Shuffle button
        this.buttons.shuffle.disabled = !isHumanTurn || !hasTiles;
        this.buttons.shuffle.title = !isHumanTurn ? 
            'Not your turn' : 
            !hasTiles ? 'No tiles to shuffle' : 'Rearrange your tiles';
        
        // Exchange button
        this.buttons.exchange.disabled = !isHumanTurn || !hasTiles;
        this.buttons.exchange.title = !isHumanTurn ? 
            'Not your turn' : 
            !hasTiles ? 'No tiles to exchange' : 'Exchange tiles';
        
        // Quit button
        this.buttons.quit.disabled = false;
        this.buttons.quit.title = 'End current game';
    }

    addTooltips() {
        Object.entries(this.buttons).forEach(([name, button]) => {
            if (!button.title) {
                button.title = this.getDefaultTooltip(name);
            }
        });
    }

    getDefaultTooltip(buttonName) {
        const tooltips = {
            submitWord: 'Submit your word to the board',
            passTurn: 'Skip your turn',
            shuffle: 'Rearrange your tiles',
            exchange: 'Exchange tiles with the bag',
            quit: 'End current game'
        };
        return tooltips[buttonName] || '';
    }
}

// Initialize managers
const soundManager = new SoundManager();
const buttonStateManager = new ButtonStateManager();

// Update GameController to use managers
class GameController {
    constructor(gameState, boardManager) {
        this.gameState = gameState;
        this.boardManager = boardManager;
        this.dragSource = null;
        this.isDragging = false;
        this.setupEventListeners();
        buttonStateManager.addTooltips();
    }

    updateUI() {
        this.updateBoardUI();
        this.updateRackUI();
        this.updateScoreboard();
        this.updateMoveHistory();
        this.updateGameInfo();
        this.highlightCurrentPlayer();
        buttonStateManager.updateButtonStates(this.gameState);
    }

    // Update sound calls in methods
    submitWord() {
        // ... existing code ...
        if (result.valid) {
            soundManager.play('tilePlaced');
            // ... rest of the code ...
        } else {
            soundManager.play('invalidMove');
            // ... rest of the code ...
        }
    }

    startNewGame() {
        // ... existing code ...
        soundManager.play('gameStart');
    }

    quitGame() {
        // ... existing code ...
        soundManager.play('gameEnd');
    }

    // ... rest of GameController class methods ...
}

// ... existing code ...

class DebugManager {
    constructor() {
        this.enabled = false;
        this.debugPanel = document.getElementById('debug-panel');
        this.debugContent = document.getElementById('debug-content');
        this.setupEventListeners();
    }

    setupEventListeners() {
        const debugToggle = document.getElementById('debug-toggle');
        debugToggle.addEventListener('click', () => this.toggleDebug());
        
        // Add keyboard shortcut (Ctrl+Shift+D)
        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey && e.shiftKey && e.key === 'D') {
                this.toggleDebug();
            }
        });
    }

    toggleDebug() {
        this.enabled = !this.enabled;
        this.debugPanel.classList.toggle('hidden');
        const debugToggle = document.getElementById('debug-toggle');
        debugToggle.classList.toggle('active');
        debugToggle.title = this.enabled ? 'Hide Debug Panel' : 'Show Debug Panel';
    }

    updateDebugInfo(gameState, boardManager) {
        if (!this.enabled) return;
        
        const info = {
            gameState: {
                currentPlayer: gameState.getCurrentPlayer().name,
                turnNumber: gameState.turnCount,
                roundNumber: gameState.roundCount,
                consecutivePasses: gameState.consecutivePasses,
                players: gameState.players.map(p => ({
                    name: p.name,
                    score: p.score,
                    rackSize: p.rack.length
                }))
            },
            boardState: {
                tilesPlaced: boardManager.getTilesPlacedCount(),
                validPlacements: boardManager.getValidPlacementsCount(),
                specialCells: boardManager.getSpecialCellsCount()
            },
            statistics: gameState.statistics
        };
        
        this.debugContent.innerHTML = this.formatDebugInfo(info);
    }

    formatDebugInfo(info) {
        return `
            <div class="debug-section">
                <h3>Game State</h3>
                <p>Current Player: ${info.gameState.currentPlayer}</p>
                <p>Turn: ${info.gameState.turnNumber}</p>
                <p>Round: ${info.gameState.roundNumber}</p>
                <p>Consecutive Passes: ${info.gameState.consecutivePasses}</p>
                <h4>Players:</h4>
                <ul>
                    ${info.gameState.players.map(p => 
                        `<li>${p.name}: ${p.score} points (${p.rackSize} tiles)</li>`
                    ).join('')}
                </ul>
            </div>
            
            <div class="debug-section">
                <h3>Board State</h3>
                <p>Tiles Placed: ${info.boardState.tilesPlaced}</p>
                <p>Valid Placements: ${info.boardState.validPlacements}</p>
                <p>Special Cells: ${info.boardState.specialCells}</p>
            </div>
            
            <div class="debug-section">
                <h3>Statistics</h3>
                <p>Total Moves: ${info.statistics.totalMoves}</p>
                <p>Words Played: ${info.statistics.wordsPlayed}</p>
                <p>Total Score: ${info.statistics.totalScore}</p>
                <p>Highest Word: ${info.statistics.highestWord.word} (${info.statistics.highestWord.score} points)</p>
                <p>Chat Interactions: ${info.statistics.chatInteractions}</p>
            </div>
        `;
    }

    log(message, type = 'info') {
        if (!this.enabled) return;
        
        const logEntry = document.createElement('div');
        logEntry.className = `debug-log ${type}`;
        logEntry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
        
        this.debugContent.appendChild(logEntry);
        this.debugContent.scrollTop = this.debugContent.scrollHeight;
    }
}

// Initialize debug manager
const debugManager = new DebugManager();

// Update GameController constructor
class GameController {
    constructor(gameState, boardManager) {
        this.gameState = gameState;
        this.boardManager = boardManager;
        this.dragSource = null;
        this.isDragging = false;
        this.debugManager = debugManager;
        this.setupEventListeners();
        buttonStateManager.addTooltips();
    }

    updateUI() {
        this.updateBoardUI();
        this.updateRackUI();
        this.updateScoreboard();
        this.updateMoveHistory();
        this.updateGameInfo();
        this.highlightCurrentPlayer();
        buttonStateManager.updateButtonStates(this.gameState);
        this.debugManager.updateDebugInfo(this.gameState, this.boardManager);
    }

    // ... rest of GameController class methods ...
}



