// API Handler for Awesome Tennis Game
class APIHandler {
    constructor(baseUrl = 'https://cgames.unlimitedgames.info/awesometennis') {
        this.baseUrl = baseUrl; // Base URL without /api.php
        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; // Flag to track if score has been submitted
        this.gameStartTime = Date.now(); // When the game session started - initialize immediately
        this.lastActivityTime = Date.now(); // Initialize with current time
        this.lastScoreSubmissionTime = 0; // Track when the last score was submitted
        this.lastSubmittedScore = 0; // Track the last score value that was submitted
        this.lastSubmittedLevel = null; // Track the last level that was submitted
        this.lastSubmittedWorld = null; // Track the last world that was submitted
        this.lastSubmittedTrack = null; // Track the last track that was submitted
        this.gameToken = null; // Will store the verified token
        
        // Start tracking activity immediately
        this.setupGlobalActivityTracking();
        
        console.log('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);
            
            // Create an emergency token even if verification fails
            console.log('Generating emergency token due to verification failure');
            this.gameToken = 'emergency_token_' + Date.now();
            return this.gameToken;
        }
    }
    
    // Set up global activity tracking
    setupGlobalActivityTracking() {
        // Set up global activity event listeners
        if (!window.activityTrackingInitialized) {
            // Track common user interactions
            document.addEventListener('click', () => this.updateActivity());
            document.addEventListener('keydown', () => this.updateActivity());
            document.addEventListener('touchstart', () => this.updateActivity());
            document.addEventListener('mousemove', () => this.updateActivity());
            
            // Add visibility change listener for tab switching
            document.addEventListener('visibilitychange', () => {
                if (document.visibilityState === 'hidden') {
                    console.log('Tab visibility changed - submitting score');
                    this.submitScoreIfNeeded();
                }
            });
            
            // Mark tracking as initialized to prevent duplicates
            window.activityTrackingInitialized = true;
        }
    }
    
    // Handle inactivity
    handleInactivity() {
        if (document.getElementById('inactivity-overlay')) {
            return;
        }
        
        console.log('Session inactive for too long - displaying message');
        this.attemptPauseGame();
        this.submitScoreIfNeeded();
        this.showInactivityMessage();
    }
    
    // Attempt to pause the game
    attemptPauseGame() {
        try {
            if (typeof window.pauseGame === 'function') {
                window.pauseGame();
                console.log('Game paused using window.pauseGame()');
                return true;
            }
            
            if (window.game && typeof window.game.pause === 'function') {
                window.game.pause();
                console.log('Game paused using game.pause()');
                return true;
            }
            
            const originalRAF = window.requestAnimationFrame;
            window.requestAnimationFrame = function(callback) {
                console.log('RequestAnimationFrame intercepted due to inactivity');
                return null;
            };
            
            window._originalRequestAnimationFrame = originalRAF;
            console.log('Game attempted to pause by overriding requestAnimationFrame');
            return true;
        } catch (error) {
            console.error('Failed to pause game:', error);
            return false;
        }
    }
    
    // Submit score if needed
    async submitScoreIfNeeded(currentScore = window.playerData?.score || 0) {
        try {
            if (!this.gameToken) {
                this.gameToken = await this.generateToken().catch(e => {
                    console.warn('Failed to generate token for score submission:', e);
                    return null;
                });
            }

            let isValid = false;
            if (this.gameToken) {
                isValid = await this.validateToken(this.gameToken).catch(() => false);
            }
            if (!isValid) {
                console.warn('Token invalid before score submission, generating new token');
                this.gameToken = await this.generateToken().catch(e => {
                    console.warn('Failed to generate token for score submission:', e);
                    return null;
                });
            }

            if (!this.gameToken || this.scoreSubmitted) {
                console.log('Score not submitted: ', 
                    !this.gameToken ? 'No valid token' : 'Already submitted');
                return false;
            }

            console.log('Current score to submit:', currentScore);
            const scoreChanged = currentScore !== this.lastSubmittedScore;
            const now = Date.now();
            const recentlySubmitted = (now - this.lastScoreSubmissionTime) < 5000;

            if (!scoreChanged && recentlySubmitted) {
                console.log('Score unchanged and recently submitted - skipping');
                return false;
            }

            const hasNewData = scoreChanged || 
                             (window.playerData && 
                              (window.playerData.level !== this.lastSubmittedLevel || 
                               window.playerData.world !== this.lastSubmittedWorld || 
                               window.playerData.track !== this.lastSubmittedTrack));

            if (!hasNewData) {
                console.log('No new data to submit - skipping');
                return false;
            }

            this.lastScoreSubmissionTime = now;
            this.lastSubmittedScore = currentScore;
            if (window.playerData) {
                this.lastSubmittedLevel = window.playerData.level;
                this.lastSubmittedWorld = window.playerData.world;
                this.lastSubmittedTrack = window.playerData.track;
            }
            
            const result = await this.submitFinalScore(
                this.gameToken, 
                currentScore, 
                Math.floor((now - this.gameStartTime) / 1000));
            return result;
        } catch (error) {
            console.error('Error in submitScoreIfNeeded:', error);
            return false;
        }
    }
    
    // Check if game is inactive
    isInactive(durationMs = 60 * 60 * 1000) {
        const inactiveTime = Date.now() - this.lastActivityTime;
        return inactiveTime > durationMs;
    }
    
    // Update activity timestamp
    updateActivity() {
        this.lastActivityTime = Date.now();
    }
    
    // Get device info
    _getDeviceInfo() {
        if (this.cachedDeviceInfo) {
            return this.cachedDeviceInfo;
        }
        
        const deviceInfo = {
            handset_os: 'unknown',
            device_brand: 'unknown',
            device_model: 'browser'
        };
        
        try {
            const userAgent = navigator.userAgent;
            
            if (/Windows/.test(userAgent)) {
                deviceInfo.handset_os = 'windows';
            } else if (/Android/.test(userAgent)) {
                deviceInfo.handset_os = 'android';
            } else if (/iPhone|iPad|iPod/.test(userAgent)) {
                deviceInfo.handset_os = 'ios';
            } else if (/Mac OS X/.test(userAgent)) {
                deviceInfo.handset_os = 'macos';
            } else if (/Linux/.test(userAgent)) {
                deviceInfo.handset_os = 'linux';
            }
            
            if (/Chrome/.test(userAgent)) {
                deviceInfo.device_brand = 'chrome';
            } else if (/Firefox/.test(userAgent)) {
                deviceInfo.device_brand = 'firefox';
            } else if (/Safari/.test(userAgent)) {
                deviceInfo.device_brand = 'safari';
            } else if (/Edge/.test(userAgent)) {
                deviceInfo.device_brand = 'edge';
            } else if (/Opera|OPR/.test(userAgent)) {
                deviceInfo.device_brand = 'opera';
            } else if (/MSIE|Trident/.test(userAgent)) {
                deviceInfo.device_brand = 'ie';
            }
            
            if (/Mobi|Android/.test(userAgent)) {
                deviceInfo.device_model = 'mobile_browser';
            }
            
            localStorage.setItem('deviceInfo', JSON.stringify(deviceInfo));
            this.cachedDeviceInfo = deviceInfo;
            
            return deviceInfo;
        } catch (error) {
            console.error('Error getting device info:', error);
            return deviceInfo;
        }
    }
    
    // Generate token
    async generateToken() {
        try {
            if (this.cachedToken) {
                const isValid = await this.validateToken(this.cachedToken).catch(() => false);
                
                if (isValid) {
                    console.log('Using cached token:', this.cachedToken.substring(0, 10) + '...');
                    this.gameToken = this.cachedToken;
                    return this.cachedToken;
                } else {
                    console.log('Cached token invalid, generating new token');
                    localStorage.removeItem('gameToken');
                    this.cachedToken = null;
                }
            }
            
            const deviceInfo = this._getDeviceInfo();
            const { handset_os, device_brand, device_model } = deviceInfo;
            
            const msisdn = '9800000000';
            const country = 'US';
            const operator = device_brand;
            
            const url = `${this.baseUrl}/api.php/protoken?handset_os=${encodeURIComponent(handset_os)}&device_brand=${encodeURIComponent(device_brand)}&device_model=${encodeURIComponent(device_model)}&msisdn=${encodeURIComponent(msisdn)}&_country=${encodeURIComponent(country)}&_operator=${encodeURIComponent(operator)}`;
            
            console.log('Generating token from URL:', url);
            
            try {
                const response = await fetch(url, {
                    method: 'GET',
                    headers: {
                        'Accept': 'application/json',
                        'Cache-Control': 'no-cache'
                    }
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const responseClone = response.clone();
                const textResponse = await response.text();
                console.log('Token API response received');
                
                if (textResponse && textResponse.length > 10 && !textResponse.includes('{') && !textResponse.includes(':')) {
                    const token = textResponse.trim();
                    console.log('Direct token received:', token.substring(0, 10) + '...');
                    
                    localStorage.setItem('gameToken', token);
                    this.cachedToken = token;
                    this.gameToken = token;
                    this.gameStartTime = Date.now();
                    
                    return token;
                }
                
                try {
                    const data = JSON.parse(textResponse);
                    
                    if (data && data.token) {
                        console.log('Token extracted from JSON:', data.token.substring(0, 10) + '...');
                        
                        localStorage.setItem('gameToken', data.token);
                        this.cachedToken = data.token;
                        this.gameToken = data.token;
                        this.gameStartTime = Date.now();
                        
                        return data.token;
                    }
                } catch (jsonError) {
                    const tokenMatch = textResponse.match(/"token"\s*:\s*"([^"]+)"/i);
                    if (tokenMatch && tokenMatch[1]) {
                        const extractedToken = tokenMatch[1];
                        console.log('Extracted token from text response:', extractedToken.substring(0, 10) + '...');
                        
                        localStorage.setItem('gameToken', extractedToken);
                        this.cachedToken = extractedToken;
                        this.gameToken = extractedToken;
                        this.gameStartTime = Date.now();
                        
                        return extractedToken;
                    }
                }
                
                console.log('Could not extract token from response, using fallback');
                const fallbackToken = 'fallback_token_' + Date.now();
                this.gameToken = fallbackToken;
                return fallbackToken;
            } catch (fetchError) {
                console.warn('API error during token generation:', fetchError.message);
                
                const devToken = 'dev_token_' + Date.now();
                console.log('Using development token:', devToken);
                
                localStorage.setItem('gameToken', devToken);
                this.cachedToken = devToken;
                this.gameToken = devToken;
                
                return devToken;
            }
        } catch (error) {
            console.error('Error in generateToken:', error);
            throw error;
        }
    }
    
    // Validate token
    async validateToken(token) {
        if (!token) {
            console.warn('No token provided for validation');
            return false;
        }
        try {
            const url = `${this.baseUrl}/api.php/chktoken?token=${encodeURIComponent(token)}`;
            console.log('Validating token at URL:', url);
            const response = await fetch(url, { 
                method: 'GET',
                headers: {
                    'Cache-Control': 'no-cache',
                    'Pragma': 'no-cache'
                }
            });
            
            if (!response.ok) {
                console.warn('Token validation failed with status:', response.status);
                return false;
            }
            
            const validationText = await response.text();
            const isValid = validationText.trim().toLowerCase() === 'valid';
            console.log('Token validation result:', isValid ? 'valid' : 'invalid');
            return isValid;
        } catch (error) {
            console.error('Error validating token:', error);
            return false;
        }
    }
    
    // Check token validity
    isTokenValid(token) {
        return token && 
               token.length > 10 && 
               !token.startsWith('emergency_token_') && 
               !token.startsWith('fallback_token_') && 
               !token.startsWith('dev_token_');
    }
    
    // Submit final score
    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.warn('⚠️ Cannot submit score: missing token or duration');
                return { status: 'error', message: 'Missing token or duration' };
            }
            
            console.log('🔵 SUBMIT SCORE: Valid token and duration');
            console.log('🔵 SUBMIT SCORE: Starting submission for score:', currentScore);
            
            const deviceInfo = this._getDeviceInfo();
            const { handset_os, device_brand, device_model } = deviceInfo;
            console.log('🔵 SUBMIT SCORE: Device info:', { handset_os, device_brand, device_model });
            
            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 formattedStartTime = formatDate(gameStartTime);
            const formattedEndTime = formatDate(gameEndTime);
            
            console.log('gamestarttime');
            console.log(formattedStartTime);
            console.log('gameendtime');
            console.log(formattedEndTime);

            let gameLevelNumber = 1;
            
            if (window.gameData && typeof window.gameData.challengeNum !== 'undefined') {
                gameLevelNumber = window.gameData.challengeNum;
                console.log('Using level from gameData.challengeNum:', gameLevelNumber);
            } else if (window.gameData && typeof window.gameData.levelNum !== 'undefined') {
                gameLevelNumber = window.gameData.levelNum;
                console.log('Using level from gameData.levelNum:', gameLevelNumber);
            } else if (window.playerData?.categoryIndex !== undefined) {
                gameLevelNumber = window.playerData.categoryIndex;
                console.log('Using level from playerData.categoryIndex:', gameLevelNumber);
            } else if (window.playerData?.level !== undefined) {
                gameLevelNumber = window.playerData.level;
                console.log('Using level from playerData.level:', gameLevelNumber);
            } else if (window.game?.level !== undefined) {
                gameLevelNumber = window.game.level;
                console.log('Using level from game.level:', gameLevelNumber);
            } else if (window.currentLevel !== undefined) {
                gameLevelNumber = window.currentLevel;
                console.log('Using level from window.currentLevel:', gameLevelNumber);
            }
            
            gameLevelNumber = Math.max(1, parseInt(gameLevelNumber) || 1);
            console.log('Final level number to submit:', gameLevelNumber);

            const params = [
                `handset_os=${encodeURIComponent(handset_os || 'android')}`,
                `device_brand=${encodeURIComponent(device_brand || 'samsung')}`,
                `device_model=${encodeURIComponent(device_model || 'browser')}`,
                `gamename=awesometennis`,
                `gamelevel=${encodeURIComponent(gameLevelNumber)}`,
                `gamestarttime=${encodeURIComponent(formattedStartTime)}`,
                `gameendtime=${encodeURIComponent(formattedEndTime)}`,
                `gduration=${totalDuration}`,
                `gscore=${currentScore}`,
                `session_id=${this.session_id}`
            ];

            const url = `${this.baseUrl}/api.php/scorepost?${params.join('&')}`;
            console.log('SUBMIT SCORE: Submitting to API');
            
            try {
                const response = await fetch(url, {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json',
                        'Cache-Control': 'no-cache, no-store, must-revalidate',
                        'Pragma': 'no-cache',
                        'Expires': '0'
                    },
                    cache: 'no-cache'
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                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 (fetchError) {
                console.warn('⚠️ API error during score submission:', fetchError.message);
                
                console.log('✅ FALLBACK: Recording score locally');
                this.scoreSubmitted = true;
                
                return { 
                    status: 'success', 
                    message: 'Development mode: Score recorded locally', 
                    score: currentScore,
                    timestamp: new Date().toISOString()
                };
            }
        } catch (error) {
            console.error('❌ SUBMIT SCORE: Error in score submission:', error);
            return { status: 'error', message: error.message };
        }
    }

    // Legacy method for compatibility
    async submitScore(score) {
        console.log('submitScore called with score:', score);
        return this.submitScoreIfNeeded(score);
    }
}

// Create apiHandler with the correct base URL
const API_BASE_URL = 'https://cgames.unlimitedgames.info/awesometennis';
window.apiHandler = new APIHandler(API_BASE_URL);

// Initialize activity tracking when page loads
document.addEventListener('DOMContentLoaded', () => {
    console.log("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();
    }
}); 