// ========================
// GOMOKU GAME - ENHANCED AI
// ========================

// Game Configuration
const BOARD_SIZE = 15;
const WIN_LENGTH = 5;

// Difficulty Levels
const DIFFICULTY = {
    BEGINNER: 'beginner',
    EASY: 'easy',
    MEDIUM: 'medium',
    HARD: 'hard',
    EXPERT: 'expert'
};

// Level Progression Order
const LEVEL_ORDER = ['beginner', 'easy', 'medium', 'hard', 'expert'];

// Game State
let gameState = {
    board: Array(BOARD_SIZE).fill(null).map(() => Array(BOARD_SIZE).fill(null)),
    currentPlayer: 'black', // 'black' (player) or 'white' (AI)
    gameActive: false,
    difficulty: DIFFICULTY.EASY,
    moveHistory: [],
    startTime: null,
    timerInterval: null,
    wins: 0,
    unlockedLevels: ['beginner'], // Level progression: start with beginner only
    stats: {
        beginner: { wins: 0, losses: 0, bestWin: null, worstLose: null },
        easy: { wins: 0, losses: 0, bestWin: null, worstLose: null },
        medium: { wins: 0, losses: 0, bestWin: null, worstLose: null },
        hard: { wins: 0, losses: 0, bestWin: null, worstLose: null },
        expert: { wins: 0, losses: 0, bestWin: null, worstLose: null }
    }
};



// DOM Elements
const elements = {
    board: document.getElementById('game-board'),
    startScreen: document.getElementById('start-screen'),
    gameScreen: document.getElementById('game-screen'),
    winScreen: document.getElementById('win-screen'),
    loseScreen: document.getElementById('lose-screen'),
    infoPanel: document.getElementById('info-panel'),
    aiThinking: document.getElementById('ai-thinking'),
    mainMenuBtn: document.getElementById('main-menu-btn'),
    controlsPanel: document.getElementById('control-panel'),
    difficultyDisplay: document.getElementById('difficulty-display'),
    timerDisplay: document.getElementById('timer-display'),
    playerIndicator: document.getElementById('player-indicator'),
    aiIndicator: document.getElementById('ai-indicator'),
    winsDisplay: document.getElementById('wins-display'),
    winsDisplay: document.getElementById('wins-display'),
    totalWinsDisplay: document.getElementById('total-wins'),
    totalLossesDisplay: document.getElementById('total-losses'),
    undoBtn: document.getElementById('undo-btn'),
    restartBtn: document.getElementById('restart-btn'),
    newGameBtn: document.getElementById('new-game-btn'),
    retryBtn: document.getElementById('retry-btn'),
    menuBtnWin: document.getElementById('menu-btn-win'),
    menuBtnLose: document.getElementById('menu-btn-lose'),
    closeStatsBtn: document.getElementById('close-stats-btn'),
    statsScreen: document.getElementById('stats-screen'),
    statsTableBody: document.getElementById('stats-table-body')
};

// ========================
// LEVEL PROGRESSION HELPERS
// ========================

function getNextLevel(currentLevel) {
    const currentIndex = LEVEL_ORDER.indexOf(currentLevel);
    if (currentIndex === -1 || currentIndex === LEVEL_ORDER.length - 1) {
        return null; // No next level
    }
    return LEVEL_ORDER[currentIndex + 1];
}

function unlockNextLevel(currentLevel) {
    const nextLevel = getNextLevel(currentLevel);
    if (nextLevel && !gameState.unlockedLevels.includes(nextLevel)) {
        gameState.unlockedLevels.push(nextLevel);
        saveProgress();
        return nextLevel;
    }
    return null;
}

function isLevelUnlocked(level) {
    return gameState.unlockedLevels.includes(level);
}

// ========================
// INITIALIZATION
// ========================

function initGame() {
    createBoard();
    loadProgress();
    loadGameStats(); // Load stats from API
    setupEventListeners();
    startGracePeriodChecker();
}

function setupEventListeners() {
    // Difficulty Selection
    document.querySelectorAll('.difficulty-card').forEach(btn => {
        btn.addEventListener('click', () => {
            const difficulty = btn.dataset.difficulty;
            // Check if level is unlocked before starting
            if (isLevelUnlocked(difficulty)) {
                startGame(difficulty);
            }
        });
    });

    // Game Controls
    elements.undoBtn.addEventListener('click', undoMove);
    elements.restartBtn.addEventListener('click', () => {
        // Clear active game state to prevent restoration
        localStorage.removeItem('gomoku_active_game');
        startGame(gameState.difficulty);
    });
    elements.mainMenuBtn.addEventListener('click', showMainMenu);
    
    // New Menu Button in controls
    const menuBtnControls = document.getElementById('menu-btn-controls');
    if (menuBtnControls) {
        menuBtnControls.addEventListener('click', showMainMenu);
    }

    // End Screens
    elements.newGameBtn.addEventListener('click', () => startGame(gameState.difficulty));
    elements.retryBtn.addEventListener('click', () => startGame(gameState.difficulty));
    elements.menuBtnWin.addEventListener('click', showMainMenu);
    elements.menuBtnLose.addEventListener('click', showMainMenu);
    
    // Next Level Button
    const nextLevelBtn = document.getElementById('next-level-btn');
    if (nextLevelBtn) {
        nextLevelBtn.addEventListener('click', () => {
            const nextLevel = getNextLevel(gameState.difficulty);
            if (nextLevel && isLevelUnlocked(nextLevel)) {
                startGame(nextLevel);
            }
        });
    }

    // Stats
    const viewStatsCard = document.getElementById('view-stats-card');
    if (viewStatsCard) {
        viewStatsCard.addEventListener('click', showStats);
        // Add keyboard support
        viewStatsCard.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' || e.key === ' ') {
                showStats();
            }
        });
    }
    
    elements.closeStatsBtn.addEventListener('click', () => {
        elements.statsScreen.classList.add('hidden');
    });

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

    // Save state when leaving page or switching tabs
    document.addEventListener('visibilitychange', () => {
        if (document.visibilityState === 'hidden') {
            saveProgress();
        }
    });

    window.addEventListener('beforeunload', () => {
        saveProgress();
    });
}


function createBoard() {
    elements.board.innerHTML = '';
    for (let row = 0; row < BOARD_SIZE; row++) {
        for (let col = 0; col < BOARD_SIZE; col++) {
            const cell = document.createElement('div');
            cell.className = 'cell';
            cell.dataset.row = row;
            cell.dataset.col = col;
            cell.addEventListener('click', () => handleCellClick(row, col));
            elements.board.appendChild(cell);
        }
    }
}

function updateDifficultyCardsUI() {
    document.querySelectorAll('.difficulty-card').forEach(card => {
        const difficulty = card.dataset.difficulty;
        const isUnlocked = isLevelUnlocked(difficulty);
        
        if (isUnlocked) {
            card.classList.remove('locked');
            // Remove lock overlay if exists
            const lockOverlay = card.querySelector('.lock-overlay');
            if (lockOverlay) {
                lockOverlay.remove();
            }
        } else {
            card.classList.add('locked');
            // Add lock overlay if doesn't exist
            if (!card.querySelector('.lock-overlay')) {
                const lockOverlay = document.createElement('div');
                lockOverlay.className = 'lock-overlay';
                lockOverlay.innerHTML = '🔒';
                card.appendChild(lockOverlay);
            }
        }
    });
}

// ========================
// GAME LOGIC
// ========================

function startGame(difficulty) {
    // Check if we have a valid saved game within grace period for this difficulty
    const activeGame = localStorage.getItem('gomoku_active_game');
    if (activeGame) {
        try {
            const savedState = JSON.parse(activeGame);
            const GRACE_PERIOD_MS = 10000;
            const now = Date.now();
            const savedTime = savedState.timestamp || 0;
            
            // If within grace period AND same difficulty, restore it
            if (now - savedTime <= GRACE_PERIOD_MS && savedState.difficulty === difficulty) {
                console.log('Restoring game from grace period');
                loadProgress(); // This will handle the restoration
                return;
            }
        } catch (e) {
            console.error('Error checking saved game:', e);
        }
    }

    // Otherwise start fresh
    gameState.difficulty = difficulty;
    gameState.board = Array(BOARD_SIZE).fill(null).map(() => Array(BOARD_SIZE).fill(null));
    gameState.currentPlayer = 'black';
    gameState.gameActive = true;
    gameState.moveHistory = [];
    gameState.startTime = Date.now();
    
    // Track game start for analytics
    if (typeof trackGameStart === 'function') {
        trackGameStart('gomoku'); // No match data for single-player game
    }
    
    // Clear AI cache
    if (window.GomokuAI) {
        GomokuAI.clearCache();
    }
    
    // Reset UI - remove all stones
    document.querySelectorAll('.stone').forEach(p => p.remove());
    
    // Show game screen and hide others
    elements.startScreen.classList.add('hidden');
    elements.gameScreen.classList.remove('hidden');
    elements.winScreen.classList.add('hidden');
    elements.loseScreen.classList.add('hidden');
    elements.statsScreen.classList.add('hidden');
    
    updateUI();
    startTimer();
    saveProgress();
    
    // Remove any existing grace period notification
    const notification = document.querySelector('.grace-period-notification');
    if (notification) notification.remove();

    // Force layout recalculation now that game screen is visible
    // Use double RAF to ensure DOM is fully updated and styles applied
    requestAnimationFrame(() => {
        requestAnimationFrame(() => {
            if (window.gameLayout) {
                window.gameLayout.performLayout();
            }
        });
    });
}

function handleCellClick(row, col) {
    if (!gameState.gameActive || gameState.currentPlayer !== 'black' || gameState.board[row][col]) return;

    makeMove(row, col, 'black');
    
    if (gameState.gameActive) {
        gameState.currentPlayer = 'white';
        updateUI();
        
        // AI Turn
        setTimeout(() => {
            const aiMove = GomokuAI.getBestMove(gameState);
            
            if (aiMove) {
                makeMove(aiMove.row, aiMove.col, 'white');
                gameState.currentPlayer = 'black';
                updateUI();
            }
        }, 500);
    }
}

function makeMove(row, col, player) {
    gameState.board[row][col] = player;
    gameState.moveHistory.push({ row, col, player });
    saveProgress(); // Save state after each move
    
    // Render Stone
    const cell = document.querySelector(`.cell[data-row="${row}"][data-col="${col}"]`);
    const stone = document.createElement('div');
    stone.className = `stone ${player}`;
    
    cell.appendChild(stone);
    
    // Check Win
    if (checkWin(row, col, player)) {
        endGame(player);
    } else if (checkDraw()) {
        endGame('draw');
    }
}

function undoMove() {
    if (!gameState.gameActive || gameState.moveHistory.length < 2) return;
    
    // Undo last two moves (AI and Player)
    for (let i = 0; i < 2; i++) {
        const move = gameState.moveHistory.pop();
        gameState.board[move.row][move.col] = null;
        const cell = document.querySelector(`.cell[data-row="${move.row}"][data-col="${move.col}"]`);
        cell.innerHTML = '';
    }
    saveProgress(); // Save state after undo
}

function checkWin(row, col, player) {
    const directions = [
        [0, 1],  // Horizontal
        [1, 0],  // Vertical
        [1, 1],  // Diagonal \
        [1, -1]  // Diagonal /
    ];

    for (const [dx, dy] of directions) {
        let count = 1;
        
        // Check forward
        for (let i = 1; i < WIN_LENGTH; i++) {
            const r = row + i * dx;
            const c = col + i * dy;
            if (isValidPos(r, c) && gameState.board[r][c] === player) count++;
            else break;
        }
        
        // Check backward
        for (let i = 1; i < WIN_LENGTH; i++) {
            const r = row - i * dx;
            const c = col - i * dy;
            if (isValidPos(r, c) && gameState.board[r][c] === player) count++;
            else break;
        }
        
        if (count >= WIN_LENGTH) return true;
    }
    return false;
}

function checkDraw() {
    return gameState.moveHistory.length === BOARD_SIZE * BOARD_SIZE;
}

function isValidPos(row, col) {
    return row >= 0 && row < BOARD_SIZE && col >= 0 && col < BOARD_SIZE;
}

function endGame(winner) {
    gameState.gameActive = false;
    clearInterval(gameState.timerInterval);
    localStorage.removeItem('gomoku_active_game'); // Clear active game state
    
    const elapsed = Math.floor((Date.now() - gameState.startTime) / 1000);
    const duration = Date.now() - gameState.startTime;
    
    // Track game end for analytics
    if (typeof trackGameEnd === 'function') {
        let result = 'draw';
        if (winner === 'black') result = 'win';
        else if (winner === 'white') result = 'loss';
        
        trackGameEnd('gomoku', duration, {
            metrics: {
                difficulty: gameState.difficulty,
                totalMoves: gameState.moveHistory.length,
                result: result
            }
        });
    }
    const difficulty = gameState.difficulty;

    if (winner === 'black') {
        gameState.wins++;
        gameState.stats[difficulty].wins++;
        
        if (gameState.stats[difficulty].bestWin === null || elapsed < gameState.stats[difficulty].bestWin) {
            gameState.stats[difficulty].bestWin = elapsed;
        }
        
        // Unlock next level
        const nextLevel = unlockNextLevel(difficulty);
        
        saveProgress();
        showScreen('win');
    } else if (winner === 'white') {
        gameState.stats[difficulty].losses++;
        
        // Update Total Losses Display
        if (elements.totalLossesDisplay) {
            const totalLosses = Object.values(gameState.stats).reduce((acc, curr) => acc + curr.losses, 0);
            elements.totalLossesDisplay.textContent = totalLosses;
        }
        
        if (gameState.stats[difficulty].worstLose === null || elapsed < gameState.stats[difficulty].worstLose) {
            gameState.stats[difficulty].worstLose = elapsed;
        }

        saveProgress();
        showScreen('lose');
    } else {
        showNotification('Game Draw!', 'info');
    }
}



// ========================
// UI & UTILS
// ========================

function updateUI() {
    elements.difficultyDisplay.textContent = gameState.difficulty.charAt(0).toUpperCase() + gameState.difficulty.slice(1);
    elements.winsDisplay.textContent = gameState.wins;
    
    // Update turn indicator
    if (gameState.currentPlayer === 'black') {
        elements.playerIndicator.classList.add('active');
        elements.aiIndicator.classList.remove('active');
    } else {
        elements.playerIndicator.classList.remove('active');
        elements.aiIndicator.classList.add('active');
    }
    
    updateTimerDisplay();
}

function updateTimerDisplay() {
    if (!gameState.startTime) {
        elements.timerDisplay.textContent = '00:00';
        return;
    }
    const elapsed = Math.floor((Date.now() - gameState.startTime) / 1000);
    const mins = Math.floor(elapsed / 60).toString().padStart(2, '0');
    const secs = (elapsed % 60).toString().padStart(2, '0');
    elements.timerDisplay.textContent = `${mins}:${secs}`;
}

function startTimer() {
    if (gameState.timerInterval) clearInterval(gameState.timerInterval);
    
    updateTimerDisplay(); // Initial update
    
    gameState.timerInterval = setInterval(() => {
        updateTimerDisplay();
        saveProgress(); // Save state every second
    }, 1000);
}

function showScreen(screen) {
    // Hide all screens
    elements.startScreen.classList.add('hidden');
    elements.gameScreen.classList.add('hidden');
    elements.winScreen.classList.add('hidden');
    elements.loseScreen.classList.add('hidden');
    elements.statsScreen.classList.add('hidden');
    
    if (screen === 'start') {
        elements.startScreen.classList.remove('hidden');
        updateDifficultyCardsUI(); // Update locked/unlocked states
    } else if (screen === 'win') {
        elements.winScreen.classList.remove('hidden');
        document.getElementById('win-time').textContent = elements.timerDisplay.textContent;
        document.getElementById('win-difficulty').textContent = elements.difficultyDisplay.textContent;
        
        // Show/hide Next Level button
        const nextLevelBtn = document.getElementById('next-level-btn');
        const nextLevel = getNextLevel(gameState.difficulty);
        if (nextLevelBtn) {
            if (nextLevel) {
                nextLevelBtn.classList.remove('hidden');
                // Update button text with next level name
                const nextLevelName = nextLevel.charAt(0).toUpperCase() + nextLevel.slice(1);
                const btnText = nextLevelBtn.querySelector('span');
                if (btnText) {
                    btnText.textContent = `Next: ${nextLevelName}`;
                }
            } else {
                nextLevelBtn.classList.add('hidden');
            }
        }
    } else if (screen === 'lose') {
        elements.loseScreen.classList.remove('hidden');
        document.getElementById('lose-time').textContent = elements.timerDisplay.textContent;
        document.getElementById('lose-difficulty').textContent = elements.difficultyDisplay.textContent;
    }
}

function showMainMenu() {
    // Only save if game was active AND had moves
    if (gameState.gameActive && gameState.moveHistory.length > 0) {
        // Explicitly save with timestamp
        const activeState = {
            board: gameState.board,
            currentPlayer: gameState.currentPlayer,
            moveHistory: gameState.moveHistory,
            difficulty: gameState.difficulty,
            startTime: gameState.startTime,
            elapsedTime: Math.floor((Date.now() - gameState.startTime) / 1000),
            timestamp: Date.now()
        };
        localStorage.setItem('gomoku_active_game', JSON.stringify(activeState));
    }

    // Mark game as inactive
    gameState.gameActive = false;
    clearInterval(gameState.timerInterval);
    
    showScreen('start');
}

function showNotification(message, type) {
    const notification = document.createElement('div');
    notification.className = `game-notification ${type} show`;
    notification.textContent = message;
    document.body.appendChild(notification);
    setTimeout(() => {
        notification.classList.remove('show');
        setTimeout(() => notification.remove(), 300);
    }, 3000);
}

// Grace Period Notification Logic
let gracePeriodInterval = null;

function startGracePeriodChecker() {
    if (gracePeriodInterval) clearInterval(gracePeriodInterval);
    
    // Check every second
    gracePeriodInterval = setInterval(checkGracePeriod, 1000);
    
    // Also check immediately
    checkGracePeriod();
}

function checkGracePeriod() {
    // If game is active in current session, don't show notification
    if (gameState.gameActive && !document.hidden) {
        const notification = document.querySelector('.grace-period-notification');
        if (notification) notification.remove();
        return;
    }

    const activeGame = localStorage.getItem('gomoku_active_game');
    if (!activeGame) {
        const notification = document.querySelector('.grace-period-notification');
        if (notification) notification.remove();
        return;
    }

    try {
        const savedState = JSON.parse(activeGame);
        const GRACE_PERIOD_MS = 10000;
        const now = Date.now();
        const savedTime = savedState.timestamp || 0;
        const timeDiff = now - savedTime;
        const remainingTime = Math.ceil((GRACE_PERIOD_MS - timeDiff) / 1000);

        // If expired
        if (remainingTime <= 0) {
            localStorage.removeItem('gomoku_active_game');
            const notification = document.querySelector('.grace-period-notification');
            if (notification) notification.remove();
            return;
        }

        // If we are in the menu (game not active in memory) OR page is hidden
        // But we have an active game in storage that is valid
        if (!gameState.gameActive || document.hidden) {
            showGracePeriodNotification(remainingTime, savedState.difficulty);
        }
    } catch (e) {
        console.error('Error checking grace period:', e);
    }
}

function showGracePeriodNotification(remainingTime, difficulty) {
    let notification = document.querySelector('.grace-period-notification');
    const GRACE_PERIOD_MS = 10000;
    const progressPercent = (remainingTime / (GRACE_PERIOD_MS / 1000)) * 100;
    
    if (!notification) {
        notification = document.createElement('div');
        notification.className = 'game-notification grace-period-notification show';
        notification.innerHTML = `
            <div class="notification-icon"><i class="fas fa-clock"></i></div>
            <div class="notification-content">
                <div class="notification-title">Game Session Active</div>
                <div class="notification-message">Resuming ${difficulty} game...</div>
            </div>
            <div class="notification-timer">${remainingTime}s</div>
            <div class="notification-progress-bar" style="width: ${progressPercent}%"></div>
        `;
        
        notification.addEventListener('click', () => {
            // Resume game
            startGame(difficulty);
            notification.remove();
        });
        
        document.body.appendChild(notification);
    } else {
        // Update existing notification
        const timer = notification.querySelector('.notification-timer');
        if (timer) timer.textContent = `${remainingTime}s`;
        
        const progressBar = notification.querySelector('.notification-progress-bar');
        if (progressBar) progressBar.style.width = `${progressPercent}%`;
    }
}

function saveProgress() {
    localStorage.setItem('gomoku_wins', gameState.wins);
    localStorage.setItem('gomoku_stats', JSON.stringify(gameState.stats));
    localStorage.setItem('gomoku_unlocked_levels', JSON.stringify(gameState.unlockedLevels));
    
    // Save active game state
    // Only save if game is active AND has moves (don't save empty board)
    if (gameState.gameActive && gameState.moveHistory.length > 0) {
        const activeState = {
            board: gameState.board,
            currentPlayer: gameState.currentPlayer,
            moveHistory: gameState.moveHistory,
            difficulty: gameState.difficulty,
            startTime: gameState.startTime,
            elapsedTime: Math.floor((Date.now() - gameState.startTime) / 1000),
            timestamp: Date.now() // Add timestamp for grace period check
        };
        localStorage.setItem('gomoku_active_game', JSON.stringify(activeState));
    }
}

async function loadGameStats() {
    try {
        const response = await fetch('/api/sessions/game-stats/gomoku');
        if (response.ok) {
            const data = await response.json();
            
            // Update wins/losses displays
            if (elements.totalWinsDisplay) {
                elements.totalWinsDisplay.textContent = data.totalWins || 0;
            }
            if (elements.winsDisplay) {
                elements.winsDisplay.textContent = data.totalWins || 0;
            }
            if (elements.totalLossesDisplay) {
                elements.totalLossesDisplay.textContent = data.totalLosses || 0;
            }
        }
    } catch (error) {
        console.error('Error loading game stats:', error);
    }
}

function loadProgress() {
    const wins = localStorage.getItem('gomoku_wins');
    if (wins) {
        gameState.wins = parseInt(wins);
        elements.totalWinsDisplay.textContent = wins;
        elements.winsDisplay.textContent = wins;
    }

    const stats = localStorage.getItem('gomoku_stats');
    if (stats) {
        gameState.stats = JSON.parse(stats);
    }
    
    const unlockedLevels = localStorage.getItem('gomoku_unlocked_levels');
    if (unlockedLevels) {
        gameState.unlockedLevels = JSON.parse(unlockedLevels);
    }
    
    // Update UI to reflect unlocked levels
    // Update UI to reflect unlocked levels
    updateDifficultyCardsUI();
    
    // Calculate and display total losses
    const totalLosses = Object.values(gameState.stats).reduce((acc, curr) => acc + curr.losses, 0);
    if (elements.totalLossesDisplay) {
        elements.totalLossesDisplay.textContent = totalLosses;
    }
    
    // Load active game state
    const activeGame = localStorage.getItem('gomoku_active_game');
    if (activeGame) {
        try {
            const savedState = JSON.parse(activeGame);
            
            // Check grace period (10 seconds)
            const GRACE_PERIOD_MS = 10000;
            const now = Date.now();
            const savedTime = savedState.timestamp || 0;
            const timeDiff = now - savedTime;
            
            console.log('Loading Game State:', {
                now,
                savedTime,
                timeDiff,
                gracePeriod: GRACE_PERIOD_MS,
                isExpired: timeDiff > GRACE_PERIOD_MS
            });
            
            if (timeDiff > GRACE_PERIOD_MS) {
                // Grace period expired, clear state
                console.log('Game state expired (grace period exceeded)');
                localStorage.removeItem('gomoku_active_game');
                return;
            }

            gameState.board = savedState.board;
            gameState.currentPlayer = savedState.currentPlayer;
            gameState.moveHistory = savedState.moveHistory;
            gameState.difficulty = savedState.difficulty;
            // Adjust start time to preserve elapsed time
            const elapsed = savedState.elapsedTime || 0;
            gameState.startTime = Date.now() - (elapsed * 1000);
            gameState.gameActive = true;
            
            // Restore UI
            restoreGameUI();
        } catch (e) {
            console.error('Error loading saved game:', e);
            localStorage.removeItem('gomoku_active_game');
        }
    }
}

function restoreGameUI() {
    // Restore game UI elements
    elements.startScreen.classList.add('hidden');
    elements.gameScreen.classList.remove('hidden');
    elements.winScreen.classList.add('hidden');
    elements.loseScreen.classList.add('hidden');
    elements.board.classList.remove('hidden');
    elements.infoPanel.classList.remove('hidden');
    elements.controlsPanel.classList.remove('hidden');
    elements.mainMenuBtn.classList.remove('hidden');
    
    // Clear existing stones first to avoid duplicates
    document.querySelectorAll('.stone').forEach(p => p.remove());

    // Re-render board stones
    gameState.moveHistory.forEach((move) => {
        const cell = document.querySelector(`.cell[data-row="${move.row}"][data-col="${move.col}"]`);
        if (cell) {
            const stone = document.createElement('div');
            stone.className = `stone ${move.player}`;
            cell.appendChild(stone);
        }
    });
    
        updateUI();
    startTimer();
}

function showStats() {
    // Fetch fresh stats from API and display
    fetch('/api/sessions/game-stats/gomoku')
        .then(response => response.json())
        .then(data => {
            elements.statsTableBody.innerHTML = '';
            
            // Use detailed stats from API if available, otherwise fall back to localStorage
            const statsToDisplay = data.detailedStats && Object.keys(data.detailedStats).length > 0 
                ? data.detailedStats 
                : gameState.stats;
            
            // Define level order for consistent display
            const levelOrder = ['beginner', 'easy', 'medium', 'hard', 'expert'];
            
            levelOrder.forEach(level => {
                const levelStats = statsToDisplay[level];
                if (!levelStats) return; // Skip if no data
                
                const row = document.createElement('tr');
                const levelName = level.charAt(0).toUpperCase() + level.slice(1);
                
                row.innerHTML = `
                    <td>${levelName}</td>
                    <td class="stat-highlight">${levelStats.wins || 0}</td>
                    <td>${levelStats.losses || 0}</td>
                    <td>${formatTime(levelStats.bestTime)}</td>
                `;
                elements.statsTableBody.appendChild(row);
            });
            
            elements.statsScreen.classList.remove('hidden');
        })
        .catch(error => {
            console.error('Error fetching stats:', error);
            // Fall back to localStorage stats
            displayLocalStats();
        });
}

function displayLocalStats() {
    elements.statsTableBody.innerHTML = '';
    const levelOrder = ['beginner', 'easy', 'medium', 'hard', 'expert'];
    
    levelOrder.forEach(level => {
        const levelStats = gameState.stats[level];
        const row = document.createElement('tr');
        const levelName = level.charAt(0).toUpperCase() + level.slice(1);
        
        row.innerHTML = `
            <td>${levelName}</td>
            <td class="stat-highlight">${levelStats.wins}</td>
            <td>${levelStats.losses}</td>
            <td>${formatTime(levelStats.bestWin)}</td>
        `;
        elements.statsTableBody.appendChild(row);
    });
    
    elements.statsScreen.classList.remove('hidden');
}

function formatTime(seconds) {
    if (seconds === null) return '-';
    const mins = Math.floor(seconds / 60).toString().padStart(2, '0');
    const secs = (seconds % 60).toString().padStart(2, '0');
    return `${mins}:${secs}`;
}


// ========================
// RESPONSIVE LAYOUT LOGIC
// ========================

// Initialize Responsive Layout Module
const layout = new ResponsiveGameLayout({
    gameScreenId: 'game-screen',
    topBarSelector: '.game-top-bar',
    bottomBarSelector: '.control-panel',
    boardWrapperSelector: '.game-board-wrapper',
    boardId: 'game-board',
    hasTopLeftBar: true,
    hasBottomRightBar: true,
    boardSizeMode: 'square',
    gap: 24
});

// Expose layout instance for manual updates if needed
window.gameLayout = layout;

// Start
initGame();
