/** * EDUrocks 3.0 - Game Play Tracker * Tracks game play time and sends to backend */ let gameStartTime = null; let currentGameId = null; let currentGameName = null; let trackingInterval = null; const MIN_SESSION_TIME = 30; // Minimum 30 seconds to record // Track game as recently played async function trackRecentlyPlayed(gameId, gameName, gameImage) { if (!window.Auth || !window.Auth.isLoggedIn()) { return; } try { await window.Auth.trackRecentlyPlayed(gameId, gameName, gameImage); console.log(`Tracked recently played: ${gameName}`); } catch (error) { console.error('Failed to track recently played:', error); } } export function startTrackingGame(gameId, gameName, gameImage = '') { if (!window.Auth || !window.Auth.isLoggedIn()) { return; // Don't track if not logged in } // Stop any existing tracking stopTrackingGame(); currentGameId = gameId; currentGameName = gameName; gameStartTime = Date.now(); console.log(`Started tracking: ${gameName}`); // Track as recently played immediately when game starts trackRecentlyPlayed(gameId, gameName, gameImage); // Set up auto-save every 5 minutes trackingInterval = setInterval(() => { saveCurrentSession(false); }, 5 * 60 * 1000); // 5 minutes } export function stopTrackingGame() { if (!gameStartTime || !currentGameId) { return; } // Save final session saveCurrentSession(true); // Clear tracking clearInterval(trackingInterval); gameStartTime = null; currentGameId = null; currentGameName = null; trackingInterval = null; } async function saveCurrentSession(isFinal) { if (!gameStartTime || !currentGameId || !window.Auth) { return; } const playTime = Math.floor((Date.now() - gameStartTime) / 1000); // in seconds if (playTime < MIN_SESSION_TIME) { console.log('Session too short, not recording'); if (isFinal) { gameStartTime = null; // Reset for final save } return; } try { await window.Auth.recordGameSession(currentGameId, currentGameName, playTime); console.log(`Recorded ${playTime}s for ${currentGameName}`); // Dispatch event to notify other components document.dispatchEvent(new CustomEvent('gameSessionRecorded', { detail: { gameId: currentGameId, gameName: currentGameName, playTime } })); // Reset start time for continuous tracking if (!isFinal) { gameStartTime = Date.now(); } } catch (error) { console.error('Failed to record session:', error); } } // Auto-save on page unload window.addEventListener('beforeunload', () => { if (gameStartTime && currentGameId) { const playTime = Math.floor((Date.now() - gameStartTime) / 1000); if (playTime >= MIN_SESSION_TIME && window.Auth && window.Auth.isLoggedIn()) { // Use sendBeacon for async send on page unload const token = window.Auth.getToken(); const apiUrl = document.querySelector('script[src*="auth.js"]')?.getAttribute('data-api-url') || `https://backendapi.${window.location.hostname.replace(/^www\./, '')}/userauth/api.php`; const data = JSON.stringify({ gameId: currentGameId, gameName: currentGameName, playTime: playTime }); navigator.sendBeacon( `${apiUrl}?action=recordGameSession`, new Blob([data], { type: 'application/json' }) ); } } }); // Pause tracking when tab loses focus document.addEventListener('visibilitychange', () => { if (document.hidden && gameStartTime) { // Save current session when tab is hidden saveCurrentSession(false); } else if (!document.hidden && currentGameId) { // Reset timer when tab becomes visible again gameStartTime = Date.now(); } }); // Make functions globally available window.startTrackingGame = startTrackingGame; window.stopTrackingGame = stopTrackingGame; export { startTrackingGame as trackGame, stopTrackingGame as untrackGame };