// API Handler for Chess Pro
// --------------------------------
// This file handles all API interactions for the Chess Pro game
// It manages token generation, score submission, and session tracking

class APIHandler {
    constructor(baseUrl = 'https://cgames.unlimitedgames.info/chesspro') {
        this.baseUrl = baseUrl;
        this.session_id = Date.now().toString();
        this.cachedToken = localStorage.getItem('gameToken');
        this.cachedDeviceInfo = localStorage.getItem('deviceInfo') ? JSON.parse(localStorage.getItem('deviceInfo')) : null;
        this.scoreSubmitted = false;
        this.gameStartTime = Date.now();
        this.lastActivityTime = Date.now();
        this.lastScoreSubmissionTime = 0;
        this.lastSubmittedScore = 0;
        this.gameToken = null;
        
        this.setupGlobalActivityTracking();
        
        console.log('Chess Pro API Handler initialized with session_id:', this.session_id);
        console.log('Using base URL:', this.baseUrl);
    }

    // Verify token at game start
    async verifyTokenAtStart() {
        try {
            this.gameToken = await this.generateToken();
            console.log('Token verified at game start:', this.gameToken ? this.gameToken.substring(0, 10) + '...' : 'null');
            return this.gameToken;
        } catch (error) {
            console.error('Failed to verify token at game start:', error);
            this.gameToken = 'emergency_token_' + Date.now();
            return this.gameToken;
        }
    }

    // Set up global activity tracking
    setupGlobalActivityTracking() {
        if (!window.inactivityChecker) {
            window.inactivityChecker = setInterval(() => {
                if (this.isInactive()) {
                    this.handleInactivity();
                    this.submitScoreIfNeeded();
                }
            }, 10000);
        }
        
        if (!window.activityTrackingInitialized) {
            document.addEventListener('click', () => this.updateActivity());
            document.addEventListener('keydown', () => this.updateActivity());
            document.addEventListener('touchstart', () => this.updateActivity());
            document.addEventListener('mousemove', () => this.updateActivity());
            
            document.addEventListener('visibilitychange', () => {
                if (document.visibilityState === 'hidden') {
                    console.log('Tab visibility changed - submitting score');
                    this.submitScoreIfNeeded();
                }
            });
            
            window.activityTrackingInitialized = true;
        }
    }

    // Generate a token for the game session
    async generateToken() {
        try {
            if (this.cachedToken) {
                console.log('🔵 Found cached token, verifying...');
                const isValid = await this.validateToken(this.cachedToken);
                if (isValid) {
                    console.log('✅ Cached token is valid. Using it.');
                    this.gameToken = this.cachedToken;
                    return this.cachedToken;
                } else {
                    console.warn('❌ Cached token is invalid. Generating new token.');
                    localStorage.removeItem('gameToken');
                }
            }

            const deviceInfo = this._getDeviceInfo();
            const msisdn = '9800000000';
            const country = deviceInfo.country || 'US';
            const operator = deviceInfo.operator || 'chrome';

            console.log('🔵 Generating new token with device info:', deviceInfo);
            
            const url = `${this.baseUrl}/api.php/protoken?msisdn=${encodeURIComponent(msisdn)}&_country=${encodeURIComponent(country)}&_operator=${encodeURIComponent(operator)}`;
            console.log('🔵 Token URL:', url);

            const response = await fetch(url, {
                method: 'GET',
                headers: { 'Accept': 'text/plain' },
                cache: 'no-cache',
                mode: 'cors'
            });
            
            if (!response.ok) {
                throw new Error(`Token request failed with status: ${response.status}`);
            }

            const token = (await response.text()).trim();
            if (!token) throw new Error('Token response is empty');

            localStorage.setItem('gameToken', token);
            this.cachedToken = token;
            this.gameToken = token;
            console.log('✅ New token received and saved:', token.substring(0, 10) + '...');
            
            this.gameStartTime = Date.now();
            this.lastActivityTime = Date.now();
            
            return token;
        } catch (error) {
            console.error('❌ Error in generateToken:', error);
            const fallbackToken = 'dev_token_' + Date.now() + '_' + Math.random().toString(36).substring(2, 15);
            this.gameToken = fallbackToken;
            this.cachedToken = fallbackToken;
            localStorage.setItem('gameToken', fallbackToken);
            console.log('⚠️ Using fallback token:', fallbackToken.substring(0, 10) + '...');
            return fallbackToken;
        }
    }

    // Submit score if needed based on conditions
    async submitScoreIfNeeded(currentScore = window.playerData?.score || 0) {
        try {
            const now = Date.now();
            const timeSinceLastSubmit = now - this.lastScoreSubmissionTime;
            
            if (timeSinceLastSubmit >= 10 * 60 * 1000 || currentScore !== this.lastSubmittedScore) {
                console.log('Submitting score due to:', 
                    timeSinceLastSubmit >= 10 * 60 * 1000 ? '10-minute interval' : 'score change',
                    'Current score:', currentScore);
                
                this.lastSubmittedScore = currentScore;
                this.lastScoreSubmissionTime = now;
                
                if (!this.gameToken) {
                    console.log('No token found, generating new one before submitting score');
                    this.gameToken = await this.generateToken();
                }
                
                await this.submitFinalScore(this.gameToken, currentScore, 
                    Math.floor((now - this.gameStartTime) / 1000));
                return true;
            }
            return false;
        } catch (error) {
            console.error('Error in submitScoreIfNeeded:', error);
            return false;
        }
    }

    // Submit final score for the game
    async submitFinalScore(token, currentScore, totalDuration) {
        try {
            if (this.scoreSubmitted) {
                console.warn('⚠️ Score has already been submitted for this session');
                return { status: 'skipped', message: 'Score already submitted for this session' };
            }
            
            if (!token || totalDuration === undefined) {
                console.error('❌ Missing required score submission parameters');
                throw new Error('Missing required score submission parameters');
            }

            if (totalDuration < 5) {
                console.warn('⚠️ Suspicious: Game finished too quickly');
                throw new Error('Suspicious: Game finished too quickly');
            }
            if (totalDuration > 3600) {
                console.warn('⚠️ Suspicious: Game duration too long');
                throw new Error('Suspicious: Game duration too long');
            }

            console.log('🔵 SUBMIT SCORE: Starting submission for score:', currentScore);
            const deviceInfo = this._getDeviceInfo();
            const { handset_os, device_brand, device_model } = deviceInfo;
            
            const gameStartTime = this.gameStartTime || (Date.now() - totalDuration * 1000);
            const gameEndTime = Date.now();

            const formatDate = (date) => {
                const d = new Date(date);
                const local = new Date(d.getTime() - d.getTimezoneOffset() * 60000);
                return `${local.getFullYear()}-${String(local.getMonth() + 1).padStart(2, '0')}-${String(local.getDate()).padStart(2, '0')}+${String(local.getHours()).padStart(2, '0')}:${String(local.getMinutes()).padStart(2, '0')}:${String(local.getSeconds()).padStart(2, '0')}`;
            };

            const params = [
                `handset_os=${encodeURIComponent(handset_os)}`,
                `device_brand=${encodeURIComponent(device_brand)}`,
                `device_model=${encodeURIComponent(device_model)}`,
                `gamename=chesspro`,
                `gscore=${currentScore}`,
                `gduration=${totalDuration}`,
                `session_id=${this.session_id}`,
                `gamestarttime=${formatDate(gameStartTime)}`,
                `gameendtime=${formatDate(gameEndTime)}`
            ];

            const url = `${this.baseUrl}/api.php/scorepost?${params.join('&')}`;
            console.log('🔵 SUBMIT SCORE: Submitting to URL:', url);

            const response = await fetch(url, {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                },
                cache: 'no-cache'
            });

            console.log('🔵 SUBMIT SCORE: Response status:', response.status);
            
            if (!response.ok) {
                const errorText = await response.text();
                console.error('❌ SUBMIT SCORE: Submission failed with response:', errorText);
                throw new Error(`Score submission failed: ${errorText}`);
            }

            this.scoreSubmitted = true;
            console.log('✅ SUBMIT SCORE: Score successfully submitted!');
            
            try {
                const data = await response.json();
                console.log('✅ SUBMIT SCORE: Server response:', data);
                return data;
            } catch (parseError) {
                const textResponse = await response.text();
                console.log('✅ SUBMIT SCORE: Server text response:', textResponse);
                return { status: 'success', message: textResponse };
            }
        } catch (error) {
            console.error('❌ SUBMIT SCORE: Error in score submission:', error);
            return { status: 'error', message: error.message };
        }
    }

    // Get device info
    _getDeviceInfo() {
        if (this.cachedDeviceInfo) {
            return this.cachedDeviceInfo;
        }
        
        const userAgent = navigator.userAgent.toLowerCase();
        
        let device_type = 'unknown';
        let handset_os = 'unknown';
        let device_brand = 'unknown';
        let device_model = 'unknown';
        let country = 'US';
        let operator = 'unknown';
        
        if (userAgent.indexOf('android') > -1) {
            handset_os = 'android';
        } else if (
            userAgent.indexOf('iphone') > -1 || 
            userAgent.indexOf('ipad') > -1 || 
            userAgent.indexOf('ipod') > -1 || 
            (userAgent.indexOf('mac') > -1 && 'ontouchend' in document)
        ) {
            handset_os = 'ios';
        } else if (userAgent.indexOf('windows') > -1) {
            handset_os = 'windows';
        } else if (userAgent.indexOf('mac') > -1) {
            handset_os = 'macos';
        } else if (userAgent.indexOf('linux') > -1) {
            handset_os = 'linux';
        }
        
        if (userAgent.includes('mobile')) {
            device_type = 'mobile';
        } else if (userAgent.includes('tablet')) {
            device_type = 'tablet';
        } else {
            device_type = 'desktop';
        }
        
        if (handset_os === 'android') {
            if (userAgent.includes('samsung')) {
                device_brand = 'samsung';
                const modelMatch = userAgent.match(/sm-[a-z0-9]+/i) || userAgent.match(/gt-[a-z0-9]+/i);
                device_model = modelMatch ? modelMatch[0].toUpperCase() : 'Galaxy';
            } else if (userAgent.includes('huawei') || userAgent.includes('honor')) {
                device_brand = 'huawei';
                const modelMatch = userAgent.match(/(huawei|honor)[- ]([\w-]+)/i);
                device_model = modelMatch ? modelMatch[2].toUpperCase() : 'Unknown Model';
            } else if (userAgent.includes('xiaomi') || userAgent.includes('redmi') || userAgent.includes('mi')) {
                device_brand = 'xiaomi';
                const modelMatch = userAgent.match(/(redmi|mi)[- ]([\w-]+)/i);
                device_model = modelMatch ? modelMatch[2].toUpperCase() : 'Unknown Model';
            }
        } else if (handset_os === 'ios') {
            device_brand = 'apple';
            if (userAgent.includes('iphone')) {
                device_model = 'iPhone';
            } else if (userAgent.includes('ipad')) {
                device_model = 'iPad';
            } else if (userAgent.includes('ipod')) {
                device_model = 'iPod';
            }
        }
        
        if (navigator.language) {
            const langParts = navigator.language.split('-');
            if (langParts.length > 1) {
                country = langParts[1].toUpperCase();
            }
        }
        
        operator = device_brand !== 'unknown' ? device_brand : 'chrome';
        
        const deviceInfo = { 
            handset_os,
            device_brand,
            device_model,
            device_type,
            country,
            operator
        };
        
        this.cachedDeviceInfo = deviceInfo;
        localStorage.setItem('deviceInfo', JSON.stringify(deviceInfo));
        
        return deviceInfo;
    }

    // Update activity timestamp
    updateActivity() {
        this.lastActivityTime = Date.now();
    }
    
    // Check if session is inactive
    isInactive(timeoutMs = 60 * 1000) {
        if (!this.lastActivityTime) return false;
        return (Date.now() - this.lastActivityTime) > timeoutMs;
    }

    // Handle inactivity
    handleInactivity() {
        if (document.getElementById('inactivity-overlay')) {
            return;
        }
        
        console.log("INACTIVE DETECTED! Showing message.");
        this.showInactivityMessage();
        
        const event = new CustomEvent('game:inactivity');
        document.dispatchEvent(event);
        
        if (window.inactivityChecker) {
            clearInterval(window.inactivityChecker);
            window.inactivityChecker = null;
        }
    }

    // Show inactivity message
    showInactivityMessage() {
        if (document.getElementById('inactivity-overlay')) {
            return;
        }
        
        this.pauseGame();
        
        const overlay = document.createElement('div');
        overlay.id = 'inactivity-overlay';
        overlay.style.position = 'fixed';
        overlay.style.top = '0';
        overlay.style.left = '0';
        overlay.style.width = '100%';
        overlay.style.height = '100%';
        overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.9)';
        overlay.style.color = 'white';
        overlay.style.display = 'flex';
        overlay.style.flexDirection = 'column';
        overlay.style.justifyContent = 'center';
        overlay.style.alignItems = 'center';
        overlay.style.zIndex = '99999';
        overlay.style.fontFamily = 'Arial, sans-serif';
        
        const message = document.createElement('h2');
        message.textContent = "You've been inactive. Click refresh to continue.";
        message.style.marginBottom = '20px';
        
        const subMessage = document.createElement('p');
        subMessage.textContent = 'Please refresh the page to start a new game';
        subMessage.style.marginBottom = '30px';
        
        const button = document.createElement('button');
        button.textContent = 'Refresh Page';
        button.style.padding = '10px 20px';
        button.style.fontSize = '16px';
        button.style.cursor = 'pointer';
        button.style.backgroundColor = '#4CAF50';
        button.style.color = 'white';
        button.style.border = 'none';
        button.style.borderRadius = '4px';
        button.onclick = () => {
            window.location.reload();
        };
        
        overlay.appendChild(message);
        overlay.appendChild(subMessage);
        overlay.appendChild(button);
        document.body.appendChild(overlay);
        
        const blocker = document.createElement('div');
        blocker.id = 'game-blocker';
        blocker.style.position = 'fixed';
        blocker.style.top = '0';
        blocker.style.left = '0';
        blocker.style.width = '100%';
        blocker.style.height = '100%';
        blocker.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
        blocker.style.zIndex = '99998';
        document.body.appendChild(blocker);
        
        if (window.requestAnimationFrame) {
            const oldRequestAnimationFrame = window.requestAnimationFrame;
            window.requestAnimationFrame = function() {
                return 0;
            };
            window.origRequestAnimationFrame = oldRequestAnimationFrame;
        }
    }

    // Pause the game
    pauseGame() {
        try {
            if (window.pauseGame && typeof window.pauseGame === 'function') {
                console.log('Pausing game via global pauseGame function');
                window.pauseGame();
            }
            
            if (window.createjs && window.createjs.Ticker) {
                console.log('Pausing game via CreateJS Ticker');
                window.createjs.Ticker.paused = true;
            }
            
            if (window.game && typeof window.game.pause === 'function') {
                console.log('Pausing game via game.pause method');
                window.game.pause();
            }
            
            if (window.Phaser && window.game instanceof Phaser.Game) {
                console.log('Pausing Phaser game');
                window.game.paused = true;
            }
            
            if (window.THREE && window.renderer && window.animationId) {
                console.log('Cancelling Three.js animation frame');
                cancelAnimationFrame(window.animationId);
            }
            
            console.log('Game paused via multiple methods');
        } catch (error) {
            console.error('Error pausing game:', error);
        }
    }
}

// Create apiHandler immediately when the script is loaded
window.apiHandler = new APIHandler();

// Ensure inactivity tracking is active from the moment the page loads
document.addEventListener('DOMContentLoaded', () => {
    console.log("Chess Pro page loaded - activity tracking initialized");
    if (window.apiHandler) {
        window.apiHandler.updateActivity();
    }
});

// Handle tab changes
document.addEventListener('game:tabchange', (event) => {
    console.log('Tab change detected:', event.detail?.message || 'No details');
    if (window.apiHandler) {
        window.apiHandler.submitScoreIfNeeded();
    }
});

// Handle page unload
document.addEventListener('game:unload', (event) => {
    console.log('Page unload detected:', event.detail?.message || 'No details');
    if (window.apiHandler) {
        window.apiHandler.submitScoreIfNeeded();
    }
}); 