// GRACE PERIOD COUNTDOWN SYSTEM
// Shows visual countdown when player navigates away from active game
// Matches single-player game experience

const GRACE_PERIOD_MS = 10000; // 10 seconds (matches server)
let gracePeriodInterval = null;

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

function checkGracePeriod() {
    // Show notification on start screen OR lobby (anywhere except active game)
    // We check if we are NOT in the game screen
    const gameScreenEl = document.getElementById('game-screen');
    const inGameScreen = gameScreenEl && !gameScreenEl.classList.contains('hidden');
    const isGameHash = window.location.hash === '#/game';
    
    if (inGameScreen || isGameHash) {
        // In game screen (or rejoining), hide notification if it exists
        const notification = document.querySelector('.grace-period-notification');
        if (notification) notification.remove();
        return;
    }
    
    // Check if we have a saved session
    const sessionData = localStorage.getItem('ludo_session');
    if (!sessionData) {
        const notification = document.querySelector('.grace-period-notification');
        if (notification) notification.remove();
        return;
    }
    
    let savedSession;
    try {
        savedSession = JSON.parse(sessionData);
    } catch (e) {
        const notification = document.querySelector('.grace-period-notification');
        if (notification) notification.remove();
        return;
    }
    
    // Check disconnect time
    const disconnectTime = localStorage.getItem('ludo_disconnect_time');
    if (!disconnectTime) {
        const notification = document.querySelector('.grace-period-notification');
        if (notification) notification.remove();
        return;
    }
    
    const now = Date.now();
    const disconnectedAt = parseInt(disconnectTime);
    const timeDiff = now - disconnectedAt;
    const remainingTime = Math.ceil((GRACE_PERIOD_MS - timeDiff) / 1000);
    
    // If grace period expired, clean up
    if (remainingTime <= 0) {
        console.log('Grace period expired, clearing session');
        clearSession();
        localStorage.removeItem('ludo_disconnect_time');
        const notification = document.querySelector('.grace-period-notification');
        if (notification) notification.remove();
        return;
    }
    
    // Show notification with countdown
    showGracePeriodNotification(remainingTime, savedSession);
}

function showGracePeriodNotification(remainingTime, savedSession) {
    let notification = document.querySelector('.grace-period-notification');
    const progressPercent = (remainingTime / (GRACE_PERIOD_MS / 1000)) * 100;
    
    // Color emojis for Ludo
    const colorMap = {
        'red': '🔴',
        'blue': '🔵',
        'green': '🟢',
        'yellow': '🟡'
    };
    const colorEmoji = colorMap[savedSession.color] || '⚫';
    const colorName = savedSession.color.charAt(0).toUpperCase() + savedSession.color.slice(1);
    
    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">Rejoining as ${colorEmoji} ${colorName}...</div>
            </div>
            <div class="notification-timer">${remainingTime}s</div>
            <div class="notification-progress-bar" style="width: ${progressPercent}%"></div>
        `;
        
        notification.addEventListener('click', () => {
            console.log('Notification clicked, attempting rejoin');
            // Just trigger rejoin, let joined_room handler navigate to #/game
            socket.emit('join_room', {
                roomId: savedSession.roomId,
                password: savedSession.password,
                color: savedSession.color,
                playerName: savedSession.playerName
            });
            localStorage.removeItem('ludo_disconnect_time');
            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}%`;
    }
}

// Start the grace period checker
startGracePeriodChecker();
