/**
 * SSE (Server-Sent Events) Client for Real-time Chat
 * 
 * Provides real-time communication using EventSource API
 * Falls back to polling if SSE is not supported
 */

class SSEChatClient {
    constructor(options = {}) {
        this.sessionId = options.sessionId || '';
        this.ajaxUrl = options.ajaxUrl || '';
        this.nonce = options.nonce || '';
        this.onMessage = options.onMessage || function () { };
        this.onTyping = options.onTyping || function () { };
        this.onConnect = options.onConnect || function () { };
        this.onDisconnect = options.onDisconnect || function () { };
        this.onError = options.onError || function () { };

        this.eventSource = null;
        this.isConnected = false;
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
        this.reconnectDelay = 1000; // Start with 1 second
        this.lastMessageTime = null;
        this.heartbeatTimeout = null;

        // Fallback polling
        this.pollingInterval = null;
        this.pollingDelay = 3000; // 3 seconds for fallback

        this.init();
    }

    /**
     * Initialize the SSE client
     */
    init() {
        if (!this.sessionId || !this.ajaxUrl || !this.nonce) {
            console.error('SSE Client: Missing required configuration');
            return;
        }

        // Check if EventSource is supported
        if (this.isSSESupported()) {
            console.log('SSE Client: Using Server-Sent Events');
            this.connectSSE();
        } else {
            console.log('SSE Client: EventSource not supported, falling back to polling');
            this.startPolling();
        }
    }

    /**
     * Check if SSE is supported by the browser
     */
    isSSESupported() {
        return typeof EventSource !== 'undefined';
    }

    /**
     * Connect to SSE stream
     */
    
}

// Export for use in other scripts
window.SSEChatClient = SSEChatClient;