/**
 * Analytics Tracking Script
 * Automatically tracks page views and provides API for game event tracking
 */
(function() {
    'use strict';

    class AnalyticsTracker {
        constructor() {
            this.endpoint = '/api/track';
            this.userId = this.getUserId();
            this.sessionId = this.generateSessionId();
            this.gameStartTime = null;
            this.offlineQueue = [];
            
            // Auto-track page view
            this.trackPageView();
            
            // Track page unload
            window.addEventListener('beforeunload', () => this.handlePageUnload());
        }

        /**
         * Get or create user ID
         */
        getUserId() {
            let userId = localStorage.getItem('analytics_user_id');
            if (!userId) {
                userId = this.generateUserId();
                localStorage.setItem('analytics_user_id', userId);
            }
            return userId;
        }

        /**
         * Generate a random user ID
         */
        generateUserId() {
            return 'user_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        }

        /**
         * Generate a session ID
         */
        generateSessionId() {
            return 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        }

        /**
         * Send tracking data to server
         */
        async sendEvent(eventType, data = {}) {
            const payload = {
                eventType,
                userId: this.userId,
                sessionId: this.sessionId,
                timestamp: new Date().toISOString(),
                url: window.location.pathname,
                ...data
            };

            try {
                const response = await fetch(this.endpoint, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(payload),
                    keepalive: true // Important for beforeunload
                });

                if (!response.ok) {
                    throw new Error('Tracking request failed');
                }

                // Process offline queue if any
                if (this.offlineQueue.length > 0) {
                    this.processOfflineQueue();
                }

                return true;
            } catch (error) {
                // Queue for retry if offline
                this.offlineQueue.push(payload);
                console.warn('Analytics tracking failed, queued for retry');
                return false;
            }
        }

        /**
         * Process offline queue
         */
        async processOfflineQueue() {
            while (this.offlineQueue.length > 0) {
                const payload = this.offlineQueue.shift();
                try {
                    await fetch(this.endpoint, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(payload)
                    });
                } catch (error) {
                    // Put back in queue
                    this.offlineQueue.unshift(payload);
                    break;
                }
            }
        }

        /**
         * Track page view
         */
        trackPageView() {
            const gameName = this.getGameNameFromPath();
            this.sendEvent('page_view', { gameName });
        }

        /**
         * Track game start
         */
        trackGameStart(gameName, extraData = {}) {
            // Generate NEW sessionId for each game start
            this.sessionId = this.generateSessionId();
            this.gameStartTime = Date.now();
            
            // Extract match data if provided
            const { matchId, playerRole } = extraData;
            
            this.sendEvent('game_start', { 
                gameName,
                matchId,
                playerRole
            });
        }

        /**
         * Track game end
         */
        trackGameEnd(gameName, customDuration = null, extraData = {}) {
            const duration = customDuration || (this.gameStartTime ? Date.now() - this.gameStartTime : 0);
            this.sendEvent('game_end', { 
                gameName, 
                duration,
                ...extraData
            });
            this.gameStartTime = null;
        }

        /**
         * Track custom event
         */
        trackCustomEvent(eventName, data = {}) {
            this.sendEvent('custom', { 
                eventName, 
                ...data 
            });
        }

        /**
         * Extract game name from URL path
         */
        getGameNameFromPath() {
            const path = window.location.pathname;
            const match = path.match(/\/games\/([^/]+)/);
            return match ? match[1] : 'portal';
        }

        /**
         * Handle page unload
         */
        handlePageUnload() {
            // Track game end if game was started
            if (this.gameStartTime) {
                const gameName = this.getGameNameFromPath();
                const duration = Date.now() - this.gameStartTime;
                
                // Use sendBeacon for reliable tracking on page unload
                const payload = {
                    eventType: 'game_end',
                    userId: this.userId,
                    sessionId: this.sessionId,
                    timestamp: new Date().toISOString(),
                    url: window.location.pathname,
                    gameName,
                    duration
                };

                if (navigator.sendBeacon) {
                    const blob = new Blob([JSON.stringify(payload)], { type: 'application/json' });
                    navigator.sendBeacon(this.endpoint, blob);
                }
            }
        }
    }

    // Create global tracker instance
    window.analyticsTracker = new AnalyticsTracker();

    // Expose tracking methods globally
    window.trackGameStart = function(gameName, extraData) {
        window.analyticsTracker.trackGameStart(gameName, extraData);
    };

    window.trackGameEnd = function(gameName, duration, extraData) {
        window.analyticsTracker.trackGameEnd(gameName, duration, extraData);
    };

    window.trackCustomEvent = function(eventName, data) {
        window.analyticsTracker.trackCustomEvent(eventName, data);
    };

})();
