/**
 * Mementor TTS Statistics Tracking
 * 
 * This file handles player statistics tracking when enabled.
 * Loaded conditionally only when statistics are enabled.
 * 
 * @package Mementor_TTS
 * @since 1.4.2
 */

(function($) {
    'use strict';
    
    // Debug: Log statistics configuration
    
    // Only proceed if statistics are enabled
    if (typeof mementorTTSStats === 'undefined' || !mementorTTSStats.playerStatsNonce) {
        return;
    }
    
    // Generate unique session ID for tracking
    function generateSessionId() {
        return 'sess_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    }
    
    // Session ID for this page load
    const sessionId = generateSessionId();
    
    // Event queue for batching
    let eventQueue = [];
    let flushTimeout = null;
    
    /**
     * Track player statistics event
     * Events are queued and sent in batches to reduce server requests
     */
    window.mementorTTSTrackEvent = function(postId, eventType, eventData) {
        if (!postId || !eventType) return;
        
        // Add event to queue
        eventQueue.push({
            post_id: postId,
            event_type: eventType,
            session_id: sessionId,
            event_data: eventData || {},
            timestamp: Date.now()
        });
        
        // Clear existing timeout
        if (flushTimeout) {
            clearTimeout(flushTimeout);
        }
        
        // Set new timeout to flush events after 2 seconds of inactivity
        // or immediately if we have 10+ events queued
        if (eventQueue.length >= 10) {
            flushEvents();
        } else {
            flushTimeout = setTimeout(flushEvents, 2000);
        }
    };
    
    /**
     * Flush queued events to server
     */
    function flushEvents() {
        if (eventQueue.length === 0) return;
        
        // Copy events and clear queue
        const events = eventQueue.slice();
        eventQueue = [];
        
        // Send batch request
        $.ajax({
            url: mementorTTSStats.ajaxurl,
            type: 'POST',
            data: {
                action: 'mementor_tts_track_player_events_batch',
                nonce: mementorTTSStats.playerStatsNonce,
                events: JSON.stringify(events)
            },
            // Fire and forget - don't wait for response
            timeout: 5000
        });
    }
    
    // Flush events before page unload
    $(window).on('beforeunload', function() {
        if (eventQueue.length > 0) {
            // Use sendBeacon if available for reliability
            if (navigator.sendBeacon) {
                const data = new FormData();
                data.append('action', 'mementor_tts_track_player_events_batch');
                data.append('nonce', mementorTTSStats.playerStatsNonce);
                data.append('events', JSON.stringify(eventQueue));
                
                navigator.sendBeacon(mementorTTSStats.ajaxurl, data);
            } else {
                // Fallback to synchronous AJAX
                $.ajax({
                    url: mementorTTSStats.ajaxurl,
                    type: 'POST',
                    async: false,
                    data: {
                        action: 'mementor_tts_track_player_events_batch',
                        nonce: mementorTTSStats.playerStatsNonce,
                        events: JSON.stringify(eventQueue)
                    },
                    timeout: 1000
                });
            }
        }
    });
    
    /**
     * Set up audio event tracking
     */
    window.mementorTTSSetupTracking = function(audioElement, postId) {
        if (!audioElement || !postId) {
            return;
        }
        
        // Check if tracking is already set up for this element
        const $audio = $(audioElement);
        if ($audio.data('statistics-tracking-setup')) {
            return; // Already set up, don't add duplicate listeners
        }
        
        
        // Mark as set up
        $audio.data('statistics-tracking-setup', true);
        
        let playStartTime = null;
        let totalPlayTime = 0;
        let lastProgressUpdate = 0;
        let isEnding = false; // Flag to prevent pause event when audio ends naturally
        
        // Remove any existing statistics event listeners first
        $audio.off('.statistics');
        
        // Track play event
        $audio.on('play.statistics', function() {
            playStartTime = Date.now();
            isEnding = false;
            mementorTTSTrackEvent(postId, 'play');
        });
        
        // Track pause event (only user-initiated pauses)
        $audio.on('pause.statistics', function() {
            // Don't track pause if audio is ending naturally
            if (!isEnding && playStartTime && !audioElement.ended) {
                const duration = (Date.now() - playStartTime) / 1000; // Convert to seconds
                totalPlayTime += duration;
                mementorTTSTrackEvent(postId, 'pause', { duration: duration });
                playStartTime = null;
            }
        });
        
        // Track ended event (completion)
        $audio.on('ended.statistics', function() {
            if (playStartTime) {
                const duration = (Date.now() - playStartTime) / 1000;
                totalPlayTime += duration;
                playStartTime = null;
            }
            mementorTTSTrackEvent(postId, 'ended', { 
                total_play_time: totalPlayTime,
                duration: totalPlayTime // Also send as duration for aggregation
            });
            totalPlayTime = 0; // Reset for replay
            isEnding = false;
        });
        
        // Combined timeupdate handler
        $audio.on('timeupdate.statistics', function() {
            const currentTime = audioElement.currentTime;
            
            // Check if we're near the end (within 0.5 seconds)
            if (audioElement.duration && currentTime >= audioElement.duration - 0.5) {
                isEnding = true;
            }
            
            // Track progress periodically (every 30 seconds)
            if (currentTime - lastProgressUpdate >= 30) {
                mementorTTSTrackEvent(postId, 'progress', { 
                    current_time: currentTime,
                    duration: audioElement.duration || 0
                });
                lastProgressUpdate = currentTime;
            }
        });
        
        // Track download if download button exists
        const $player = $audio.closest('.mementor-tts-player');
        const $downloadBtn = $player.find('.mementor-tts-download-button');
        if ($downloadBtn.length) {
            $downloadBtn.off('click.statistics').on('click.statistics', function() {
                mementorTTSTrackEvent(postId, 'download');
            });
        }
    };
    
    // Track initial page view with players
    $(document).ready(function() {
        
        // Function to check for players and set up tracking
        function checkForPlayers() {
            const players = $('.mementor-tts-player audio');
            
            if (players.length > 0) {
                players.each(function() {
                    const $audio = $(this);
                    const audioElement = this;
                    
                    // Get post ID
                    const $container = $audio.closest('.mementor-tts-player-container');
                    let postId = $container.data('post-id');
                    
                    // If not found, try the player element itself
                    if (!postId) {
                        const $player = $audio.closest('.mementor-tts-player');
                        postId = $player.data('post-id');
                    }
                    
                    // Fallback to global postId
                    if (!postId) {
                        postId = mementorTTSStats.postId;
                    }
                    
                    
                    if (postId) {
                        // Track player initialization if not already tracked
                        if (!$audio.data('statistics-init-tracked')) {
                            $audio.data('statistics-init-tracked', true);
                            mementorTTSTrackEvent(postId, 'player_init');
                        }
                        
                        // Set up event tracking for this audio element
                        // This is important for players that were initialized before statistics script loaded
                        mementorTTSSetupTracking(audioElement, postId);
                    }
                });
            }
        }
        
        // Check immediately
        checkForPlayers();
        
        // Also check after a delay to catch dynamically inserted players
        setTimeout(checkForPlayers, 500);
        setTimeout(checkForPlayers, 1000);
        setTimeout(checkForPlayers, 2000);
        
        // Also set up tracking for any players that were initialized before this script loaded
        // This is important because the main script might initialize players before statistics script loads
        $(document).ready(function() {
            // Find all audio elements in TTS players
            $('.mementor-tts-player audio').each(function() {
                const audioElement = this;
                const $audio = $(audioElement);
                
                // Skip if tracking is already set up
                if ($audio.data('statistics-tracking-setup')) {
                    return;
                }
                
                // Get post ID from various sources
                let postId = null;
                const $container = $audio.closest('.mementor-tts-player-container');
                
                if ($container.length && $container.data('post-id')) {
                    postId = $container.data('post-id');
                } else {
                    const $player = $audio.closest('.mementor-tts-player');
                    if ($player.length && $player.data('post-id')) {
                        postId = $player.data('post-id');
                    }
                }
                
                // Fallback to global postId
                if (!postId && mementorTTSStats.postId) {
                    postId = mementorTTSStats.postId;
                }
                
                if (postId) {
                    mementorTTSSetupTracking(audioElement, postId);
                }
            });
        });
        
        // Watch for new players being added with debouncing
        let observerTimeout;
        const observer = new MutationObserver(function(mutations) {
            // Clear existing timeout
            if (observerTimeout) {
                clearTimeout(observerTimeout);
            }
            
            // Debounce the check to avoid too many calls
            observerTimeout = setTimeout(function() {
                // Check if any of the mutations actually added a player
                let playerAdded = false;
                mutations.forEach(function(mutation) {
                    if (mutation.addedNodes.length) {
                        mutation.addedNodes.forEach(function(node) {
                            if (node.nodeType === 1 && (
                                node.classList && node.classList.contains('mementor-tts-player-container') ||
                                node.querySelector && node.querySelector('.mementor-tts-player-container')
                            )) {
                                playerAdded = true;
                            }
                        });
                    }
                });
                
                if (playerAdded) {
                    checkForPlayers();
                }
            }, 100);
        });
        
        // Start observing the document body for added nodes
        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    });
    
})(jQuery);