let sessionId = '';

$(document).ready(function() {
    $('#message-form').on('submit', function(e) {
        e.preventDefault();
        
        var message = $('#message-input').val().trim();
        
        if (message) {
            appendMessage('user', message);
            $('#message-input').val('');

            // Show loading animation
            var loadingMessage = appendMessage('assistant', '<div class="loading-dots"><span>.</span><span>.</span><span>.</span></div>');

            $.ajax({
                url: 'app.php',
                method: 'POST',
                data: { message: message, sessionId: sessionId },
                dataType: 'json',
                beforeSend: function() {
                    $('#message-input').prop('disabled', true);
                    $('button[type="submit"]').prop('disabled', true);
                },
                success: function(response) {
                    // Remove loading animation
                    loadingMessage.remove();

                    if (response.error) {
                        appendMessage('error', 'Error: ' + response.message);
                    } else {
                        appendMessage('assistant', response.output);
                        if (response.sessionId) {
                            sessionId = response.sessionId;
                        }
                    }
                },
                error: function() {
                    // Remove loading animation
                    loadingMessage.remove();

                    appendMessage('error', 'حدث خطأ أثناء إرسال الرسالة.');
                },
                complete: function() {
                    $('#message-input').prop('disabled', false);
                    $('button[type="submit"]').prop('disabled', false);
                    $('#message-input').focus();
                }
            });
        }
    });

    function appendMessage(sender, message) {
        var icon = sender === 'user' ? '<i class="fas fa-user-circle"></i>' : '<i class="fas fa-robot"></i>';
        var alignClass = sender === 'user' ? 'text-left' : 'text-right';
        var bgClass = sender === 'user' ? 'bg-blue-100' : (sender === 'assistant' ? 'bg-green-100' : 'bg-red-100');

        var messageElement = $('<div>')
            .addClass('mb-4 p-4 rounded-lg ' + alignClass + ' ' + bgClass)
            .html('<span class="font-bold">' + icon + ' ' + (sender === 'user' ? 'أنت' : 'المساعد') + ':</span> ' + message);

        $('#chat-messages').append(messageElement);
        $('#chat-messages').scrollTop($('#chat-messages')[0].scrollHeight);

        return messageElement;
    }
});

// Add this CSS to the head of the document
$('head').append(`
    <style>
        .loading-dots span {
            animation-name: blink;
            animation-duration: 1.4s;
            animation-iteration-count: infinite;
            animation-fill-mode: both;
        }

        .loading-dots span:nth-child(2) {
            animation-delay: .2s;
        }

        .loading-dots span:nth-child(3) {
            animation-delay: .4s;
        }

        @keyframes blink {
            0% {
                opacity: .2;
            }
            20% {
                opacity: 1;
            }
            100% {
                opacity: .2;
            }
        }
    </style>
`);