/*
API Handler for Scary Solitaire
-------------------------------
This file handles all API interactions for the Scary Solitaire game, including:
- Token generation and validation
- Score submission
- Activity tracking
- Session management
*/

class APIHandler {
    constructor(baseUrl = 'https://cgames.unlimitedgames.info/scarysolitaire') {
        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
        this.lastActivityTime = Date.now(); // Last user activity
        this.lastScoreSubmissionTime = 0; // When the last score was submitted
        this.lastSubmittedScore = 0; // Last score value 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);
            this.gameToken = 'emergency_token_' + Date.now();
            return this.gameToken;
        }
    }

    // Set up global activity tracking
    setupGlobalActivityTracking() {
        if (!window.inactivityChecker) {
            window.inactivityChecker = setInterval(() => {
                if (this.isInactive()) {
                    const currentScore = window.playerData?.score || this.lastSubmittedScore || 0;
                    console.log('🔵 Inactivity detected, submitting last known score:', currentScore);
                    this.handleInactivity();
                    this.submitScoreIfNeeded(currentScore);
                }
            }, 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') {
                    const currentScore = window.playerData?.score || this.lastSubmittedScore || 0;
                    console.log('🔵 Tab visibility changed - submitting score:', currentScore);
                    this.submitScoreIfNeeded(currentScore);
                }
            });
            
            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();
                }
                
                const result = await this.submitFinalScore(this.gameToken, currentScore, 
                    Math.floor((now - this.gameStartTime) / 1000));
                
                if (result.message === 'ok') {
                    this.scoreSubmitted = true;
                    console.log('✅ Score submission successful');
                    return true;
                } else {
                    console.warn('⚠️ Score submission returned:', result.message);
                    return false;
                }
            }
            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');
            }

            // Verify token before submission
            console.log('🔵 Verifying token before score submission...');
            const isValid = await this.validateToken(token);
            
            if (!isValid) {
                console.warn('⚠️ Token invalid, generating new token...');
                const newToken = await this.generateToken();
                if (!newToken) {
                    throw new Error('Failed to generate new token');
                }
                token = newToken;
                console.log('✅ New token generated:', token.substring(0, 10) + '...');
            } else {
                console.log('✅ Token is valid');
            }

            // For game end, ensure minimum duration is 10 seconds
            if (totalDuration < 10) {
                console.warn('⚠️ Game duration too short, adjusting to minimum 10 seconds');
                totalDuration = 10;
            }
            if (totalDuration > 3600) {
                console.warn('⚠️ Game duration too long, capping at 1 hour');
                totalDuration = 3600;
            }

            const url = `${this.baseUrl}/api.php/score?token=${encodeURIComponent(token)}&score=${encodeURIComponent(currentScore)}&duration=${encodeURIComponent(totalDuration)}`;
            console.log('🔵 Submitting score to:', url);

            const response = await fetch(url, {
                method: 'GET',
                headers: { 'Accept': 'application/json' },
                cache: 'no-cache',
                mode: 'cors'
            });

            if (!response.ok) {
                throw new Error(`Score submission failed with status: ${response.status}`);
            }

            const result = await response.json();
            console.log('🔵 Score submission response:', result);

            if (result.message === 'ok') {
                this.scoreSubmitted = true;
                console.log('✅ Score submitted successfully');
                return { status: 'success', message: 'ok' };
            } else {
                console.warn('⚠️ Score submission returned:', result.message);
                return { status: 'error', message: result.message };
            }
        } catch (error) {
            console.error('❌ Error in submitFinalScore:', error);
            return { status: 'error', message: error.message };
        }
    }

    // Get device information
    _getDeviceInfo() {
        if (this.cachedDeviceInfo) {
            return this.cachedDeviceInfo;
        }

        const deviceInfo = {
            userAgent: navigator.userAgent,
            platform: navigator.platform,
            language: navigator.language,
            screenWidth: window.screen.width,
            screenHeight: window.screen.height,
            colorDepth: window.screen.colorDepth,
            timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
            country: navigator.language.split('-')[1] || 'US',
            operator: 'chrome'
        };

        localStorage.setItem('deviceInfo', JSON.stringify(deviceInfo));
        this.cachedDeviceInfo = deviceInfo;
        return deviceInfo;
    }

    // Update last activity time
    updateActivity() {
        this.lastActivityTime = Date.now();
    }

    // Check if user is inactive
    isInactive(timeoutMs = 3600 * 1000) { // 1 hour inactivity timeout
        return Date.now() - this.lastActivityTime > timeoutMs;
    }

    // Handle inactivity
    handleInactivity() {
        console.log('🔵 Handling inactivity...');
        this.showInactivityMessage();
        this.pauseGame();
    }

    // Show inactivity message
    showInactivityMessage() {
        const message = document.createElement('div');
        message.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 20px;
            border-radius: 10px;
            z-index: 9999;
            text-align: center;
            font-family: Arial, sans-serif;
        `;
        message.innerHTML = `
            <h2>Game Paused</h2>
            <p>You've been inactive for a while.</p>
            <p>Click anywhere to continue playing.</p>
        `;
        document.body.appendChild(message);

        const removeMessage = () => {
            document.body.removeChild(message);
            document.removeEventListener('click', removeMessage);
            document.removeEventListener('keydown', removeMessage);
        };

        document.addEventListener('click', removeMessage);
        document.addEventListener('keydown', removeMessage);
    }

    // Pause the game
    pauseGame() {
        // Implement game-specific pause logic here
        if (window.game && typeof window.game.pause === 'function') {
            window.game.pause();
        }
    }

    // Validate token
    async validateToken(token) {
        try {
            if (!token) return false;

            const url = `${this.baseUrl}/api.php/validate?token=${encodeURIComponent(token)}`;
            console.log('🔵 Validating token at:', url);

            const response = await fetch(url, {
                method: 'GET',
                headers: { 'Accept': 'application/json' },
                cache: 'no-cache',
                mode: 'cors'
            });

            if (!response.ok) {
                throw new Error(`Token validation failed with status: ${response.status}`);
            }

            const result = await response.json();
            console.log('🔵 Token validation response:', result);

            return result.valid === true;
        } catch (error) {
            console.error('❌ Error in validateToken:', error);
            return false;
        }
    }
}

// Create and export the API handler instance
const apiHandler = new APIHandler(); 