/**
 * Enhanced Frontend Chat with SSE (Server-Sent Events) Support
 * 
 * This replaces the polling mechanism with real-time SSE communication
 * while maintaining backward compatibility with the existing chat system.
 */

jQuery(document).ready(function ($) {
    // Chat widget functionality with SSE integration
    $(".askany-chat-widget").each(function () {
        var $widget = $(this);
        var $toggle = $widget.find(".askany-chat-toggle");
        var $container = $widget.find(".askany-chat-container");
        var $messagesContainer = $widget.find(".askany-chat-messages");
        var $productsContainer = $widget.find(".askany-chat-products");
        var $form = $widget.find("#askany-chat-form");
        var $input = $form.find("input");
        var sessionId = "";
        var apiProvider = $widget.data('api-provider');
        var fallbackEnabled = $widget.data('fallback-enabled') === 'true';

        // SSE Client instance
        var sseClient = null;
        var isUserScrolling = false;
        var processedMessageIds = new Set();

        // Initialize session management (keeping existing logic)
        var browserIdKey = 'askany_browser_id';
        var sessionKey = 'askany_chat_session_id';
        var userNameKey = 'askany_username';

        function getOrCreateBrowserId() {
            var browserId = localStorage.getItem(browserIdKey);
            if (!browserId) {
                browserId = 'browser_' + Math.random().toString(36).substr(2, 9) + '_' + Date.now();
                localStorage.setItem(browserIdKey, browserId);
            }
            return browserId;
        }

        var browserId = getOrCreateBrowserId();


        // Send chat message function (keeping existing AJAX logic)
        function sendChatMessage(message) {
            var formData = new FormData();
            formData.append('action', 'askany_chat_response');
            formData.append('message', message);
            formData.append('session_id', sessionId);
            formData.append('nonce', askanyData.nonce);

            if (apiProvider) {
                formData.append('api_provider', apiProvider);
            }

            // Add user data if available
            var userName = localStorage.getItem(userNameKey);
            if (userName) {
                formData.append('user_name', userName);
            }

            $.ajax({
                url: askanyData.ajaxUrl,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function (response) {
                    if (response.success) {
                        // AI response will come via SSE, so we don't need to add it here
                        console.log('SSE Chat: Message sent successfully');
                    } else {
                        console.error('SSE Chat: Failed to send message:', response.data);
                        // Show error message
                        addMessageWithAnimation('Sorry, there was an error sending your message. Please try again.', false, false);
                    }
                },
                error: function (xhr, status, error) {
                    console.error('SSE Chat: AJAX error:', error);
                    addMessageWithAnimation('Sorry, there was a connection error. Please try again.', false, false);
                }
            });
        }

        // Widget toggle functionality (keeping existing logic)
        $toggle.on('click', function () {
            if ($container.is(':visible')) {
                $container.slideUp();
                stopChatSession();
            } else {
                $container.slideDown();
                $widget.find(".notification-badge").fadeOut();

                // Start chat session when opening
                var activeTab = $widget.find('.main-tab-btn.active').data('tab');
                if (activeTab === 'messages' || !activeTab) {
                    startChatSession();
                }
            }
        });

        // Initialize encryption
        if (window.chatEncryption) {
            window.chatEncryption.initializeKey().then(function () {
                console.log('SSE Chat: Encryption initialized');
            }).catch(function (error) {
                console.warn('SSE Chat: Encryption initialization failed:', error);
            });
        }

        console.log('SSE Chat: Widget initialized for session:', sessionId);
    });
});