/**
 * AniWorld - Progress Handler Module
 *
 * Handles real-time download progress updates.
 *
 * Dependencies: constants.js, ui-utils.js
 */

var AniWorld = window.AniWorld || {};

AniWorld.ProgressHandler = (function() {
    'use strict';

    // Store progress updates waiting for cards
    let pendingProgressUpdates = new Map();

    /**
     * Update download progress in real-time
     * @param {Object} data - Progress data from WebSocket
     */
    function updateDownloadProgress(data) {
        console.log('updateDownloadProgress called with:', JSON.stringify(data, null, 2));

        // Extract download ID - prioritize metadata.item_id (actual item ID)
        let downloadId = null;

        // First try metadata.item_id (this is the actual download item ID)
        if (data.metadata && data.metadata.item_id) {
            downloadId = data.metadata.item_id;
        }

        // Fallback to other ID fields
        if (!downloadId) {
            downloadId = data.item_id || data.download_id;
        }

        // If ID starts with "download_", extract the actual ID
        if (!downloadId && data.id) {
            if (data.id.startsWith('download_')) {
                downloadId = data.id.substring(9);
            } else {
                downloadId = data.id;
            }
        }

        // Check if data is wrapped in another 'data' property
        if (!downloadId && data.data) {
            if (data.data.metadata && data.data.metadata.item_id) {
                downloadId = data.data.metadata.item_id;
            } else if (data.data.item_id) {
                downloadId = data.data.item_id;
            } else if (data.data.id && data.data.id.startsWith('download_')) {
                downloadId = data.data.id.substring(9);
            } else {
                downloadId = data.data.id || data.data.download_id;
            }
            data = data.data;
        }

        if (!downloadId) {
            console.warn('No download ID in progress data');
            console.warn('Data structure:', data);
            console.warn('Available keys:', Object.keys(data));
            return;
        }

        console.log('Looking for download card with ID: ' + downloadId);

        // Find the download card in active downloads
        const card = document.querySelector('[data-download-id="' + downloadId + '"]');
        if (!card) {
            console.warn('Download card not found for ID: ' + downloadId);

            // Debug: Log all existing download cards
            const allCards = document.querySelectorAll('[data-download-id]');
            console.log('Found ' + allCards.length + ' download cards:');
            allCards.forEach(function(c) {
                console.log('  - ' + c.getAttribute('data-download-id'));
            });

            // Store this progress update to retry after queue loads
            console.log('Storing progress update for ' + downloadId + ' to retry after reload');
            pendingProgressUpdates.set(downloadId, data);

            return false;
        }

        console.log('Found download card for ID: ' + downloadId + ', updating progress');

        // Extract progress information
        const progress = data.progress || data;
        const percent = progress.percent || 0;
        const metadata = progress.metadata || data.metadata || {};

        // Check data format
        let speed;

        if (progress.downloaded_mb !== undefined && progress.total_mb !== undefined) {
            // yt-dlp detailed format
            speed = progress.speed_mbps ? progress.speed_mbps.toFixed(1) : '0.0';
        } else if (progress.current !== undefined && progress.total !== undefined) {
            // ProgressService basic format
            speed = metadata.speed_mbps ? metadata.speed_mbps.toFixed(1) : '0.0';
        } else {
            // Fallback
            speed = metadata.speed_mbps ? metadata.speed_mbps.toFixed(1) : '0.0';
        }

        // Update progress bar
        const progressFill = card.querySelector('.progress-fill');
        if (progressFill) {
            progressFill.style.width = percent + '%';
        }

        // Update progress text
        const progressInfo = card.querySelector('.progress-info');
        if (progressInfo) {
            const percentSpan = progressInfo.querySelector('span:first-child');
            const speedSpan = progressInfo.querySelector('.download-speed');

            if (percentSpan) {
                percentSpan.textContent = percent > 0 ? percent.toFixed(1) + '%' : 'Starting...';
            }
            if (speedSpan) {
                speedSpan.textContent = speed + ' MB/s';
            }
        }

        console.log('Updated progress for ' + downloadId + ': ' + percent.toFixed(1) + '%');
        return true;
    }

    /**
     * Process pending progress updates
     */
    function processPendingProgressUpdates() {
        if (pendingProgressUpdates.size === 0) {
            return;
        }

        console.log('Processing ' + pendingProgressUpdates.size + ' pending progress updates...');

        // Process each pending update
        const processed = [];
        pendingProgressUpdates.forEach(function(data, downloadId) {
            // Check if card now exists
            const card = document.querySelector('[data-download-id="' + downloadId + '"]');
            if (card) {
                console.log('Retrying progress update for ' + downloadId);
                updateDownloadProgress(data);
                processed.push(downloadId);
            } else {
                console.log('Card still not found for ' + downloadId + ', will retry on next reload');
            }
        });

        // Remove processed updates
        processed.forEach(function(id) {
            pendingProgressUpdates.delete(id);
        });

        if (processed.length > 0) {
            console.log('Successfully processed ' + processed.length + ' pending updates');
        }
    }

    /**
     * Clear all pending progress updates
     */
    function clearPendingUpdates() {
        pendingProgressUpdates.clear();
    }

    /**
     * Clear pending update for specific download
     * @param {string} downloadId - Download ID
     */
    function clearPendingUpdate(downloadId) {
        pendingProgressUpdates.delete(downloadId);
    }

    // Public API
    return {
        updateDownloadProgress: updateDownloadProgress,
        processPendingProgressUpdates: processPendingProgressUpdates,
        clearPendingUpdates: clearPendingUpdates,
        clearPendingUpdate: clearPendingUpdate
    };
})();
