/**
 * AniWorld - Queue Socket Handler Module
 *
 * Handles WebSocket events specific to the queue page.
 *
 * Dependencies: constants.js, websocket-client.js, ui-utils.js, queue-renderer.js, progress-handler.js
 */

var AniWorld = window.AniWorld || {};

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

    const WS_EVENTS = AniWorld.Constants.WS_EVENTS;

    // Reference to queue app for data reloading
    let queueApp = null;

    /**
     * Initialize socket handler
     * @param {Object} app - Reference to queue app
     */
    function init(app) {
        queueApp = app;
        setupSocketHandlers();
    }

    /**
     * Set up WebSocket event handlers
     */
    function setupSocketHandlers() {
        const socket = AniWorld.WebSocketClient.getSocket();
        if (!socket) {
            console.warn('Socket not available for handler setup');
            return;
        }

        // Connection events
        socket.on('connect', function() {
            AniWorld.UI.showToast('Connected to server', 'success');
        });

        socket.on('disconnect', function() {
            AniWorld.UI.showToast('Disconnected from server', 'warning');
        });

        // Queue update events - handle both old and new message types
        socket.on('queue_updated', function(data) {
            AniWorld.QueueRenderer.updateQueueDisplay(data);
        });

        socket.on('queue_status', function(data) {
            // New backend sends queue_status messages with nested structure
            if (data.status && data.statistics) {
                const queueData = {
                    ...data.status,
                    statistics: data.statistics
                };
                AniWorld.QueueRenderer.updateQueueDisplay(queueData);
            } else if (data.queue_status) {
                AniWorld.QueueRenderer.updateQueueDisplay(data.queue_status);
            } else {
                AniWorld.QueueRenderer.updateQueueDisplay(data);
            }
        });

        // Download started events
        socket.on('download_started', function() {
            AniWorld.UI.showToast('Download queue started', 'success');
            if (queueApp) queueApp.loadQueueData();
        });

        socket.on('queue_started', function() {
            AniWorld.UI.showToast('Download queue started', 'success');
            if (queueApp) queueApp.loadQueueData();
        });

        // Download progress
        socket.on('download_progress', function(data) {
            console.log('Received download progress:', data);
            const success = AniWorld.ProgressHandler.updateDownloadProgress(data);
            if (!success && queueApp) {
                // Card not found, reload queue
                queueApp.loadQueueData();
            }
        });

        // Download complete events
        const handleDownloadComplete = function(data) {
            const serieName = data.serie_name || data.serie || 'Unknown';
            const episode = data.episode || '';
            AniWorld.UI.showToast('Completed: ' + serieName + (episode ? ' - Episode ' + episode : ''), 'success');

            // Clear pending progress updates
            const downloadId = data.item_id || data.download_id || data.id;
            if (downloadId) {
                AniWorld.ProgressHandler.clearPendingUpdate(downloadId);
            }

            if (queueApp) queueApp.loadQueueData();
        };
        socket.on(WS_EVENTS.DOWNLOAD_COMPLETED, handleDownloadComplete);
        socket.on(WS_EVENTS.DOWNLOAD_COMPLETE, handleDownloadComplete);

        // Download error events
        const handleDownloadError = function(data) {
            const message = data.error || data.message || 'Unknown error';
            AniWorld.UI.showToast('Download failed: ' + message, 'error');

            // Clear pending progress updates
            const downloadId = data.item_id || data.download_id || data.id;
            if (downloadId) {
                AniWorld.ProgressHandler.clearPendingUpdate(downloadId);
            }

            if (queueApp) queueApp.loadQueueData();
        };
        socket.on(WS_EVENTS.DOWNLOAD_ERROR, handleDownloadError);
        socket.on(WS_EVENTS.DOWNLOAD_FAILED, handleDownloadError);

        // Queue completed events
        socket.on(WS_EVENTS.DOWNLOAD_QUEUE_COMPLETED, function() {
            AniWorld.UI.showToast('All downloads completed!', 'success');
            if (queueApp) queueApp.loadQueueData();
        });

        socket.on(WS_EVENTS.QUEUE_COMPLETED, function() {
            AniWorld.UI.showToast('All downloads completed!', 'success');
            if (queueApp) queueApp.loadQueueData();
        });

        // Download stop requested
        socket.on(WS_EVENTS.DOWNLOAD_STOP_REQUESTED, function() {
            AniWorld.UI.showToast('Stopping downloads...', 'info');
        });

        // Queue stopped events
        const handleQueueStopped = function() {
            AniWorld.UI.showToast('Download queue stopped', 'success');
            if (queueApp) queueApp.loadQueueData();
        };
        socket.on(WS_EVENTS.DOWNLOAD_STOPPED, handleQueueStopped);
        socket.on(WS_EVENTS.QUEUE_STOPPED, handleQueueStopped);

        // Queue paused/resumed
        socket.on(WS_EVENTS.QUEUE_PAUSED, function() {
            AniWorld.UI.showToast('Queue paused', 'info');
            if (queueApp) queueApp.loadQueueData();
        });

        socket.on(WS_EVENTS.QUEUE_RESUMED, function() {
            AniWorld.UI.showToast('Queue resumed', 'success');
            if (queueApp) queueApp.loadQueueData();
        });
    }

    // Public API
    return {
        init: init
    };
})();
