<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Smart Conversation</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/htmx.org@1.9.11"></script>
    <script src="https://unpkg.com/htmx.org/dist/ext/ws.js"></script>
    <style>
        /* Custom scrollbar styles */
        #message-list::-webkit-scrollbar {
            width: 6px;
        }

        #message-list::-webkit-scrollbar-track {
            background: #f1f1f1;
        }

        #message-list::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 3px;
        }

        #message-list::-webkit-scrollbar-thumb:hover {
            background: #555;
        }
    </style>
</head>
<body class="bg-gray-100">
<div class="flex h-screen">
    <div class="flex-1 flex flex-col bg-white overflow-hidden shadow-lg rounded-lg m-4"
         hx-ext="ws"
         ws-connect="/polly/ws/smart-gpt-admin/?user_id={{ request.user.id }}&conversation_id={{ conversation_id }}">
        <div class="bg-indigo-600 text-white p-4 shadow-md">
            <h2 class="text-xl font-bold">{{ conversation_title }}</h2>
        </div>
        <div id="message-list" class="p-6 flex-1 overflow-y-auto space-y-4">
            <!-- Messages will be inserted here by the consumer -->
        </div>

        <form id="chat-form" class="border-t-2 border-gray-200 bg-gray-50 p-4" ws-send>
            <div class="relative flex items-center">
                <input type="text"
                       id="message-input"
                       placeholder="Type your message here..."
                       name="message"
                       class="pl-4 pr-10 py-3 rounded-full border-2 border-indigo-300 w-full focus:outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 shadow-sm">
                <button id="send-button" type="submit"
                        class="ml-2 bg-indigo-600 text-white rounded-full px-6 py-3 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 transition duration-150 ease-in-out shadow-md disabled:opacity-50 disabled:cursor-not-allowed">
                    Send
                </button>
            </div>
        </form>
    </div>
</div>

<script>
    const messageInput = document.getElementById('message-input');
    const sendButton = document.getElementById('send-button');
    const chatForm = document.getElementById('chat-form');
    const messageList = document.getElementById('message-list');

    function scrollToBottom() {
        messageList.scrollTop = messageList.scrollHeight;
    }

    // Scroll to bottom initially
    scrollToBottom();

    document.body.addEventListener('htmx:wsAfterSend', function (event) {
        console.log('Message sent, clearing input and disabling button');
        messageInput.value = '';
        sendButton.disabled = true;
        scrollToBottom();
    });

    document.body.addEventListener('htmx:wsAfterMessage', function (event) {
        console.log('Received message:', event.detail.message);
        try {
            const message = JSON.parse(event.detail.message);
            if (message.type === "assistant_message_complete") {
                console.log('Assistant message complete, enabling button');
                sendButton.disabled = false;
            }
        } catch (error) {
            console.error('Error parsing message:', error);
        }
        // Scroll to bottom after receiving any message
        scrollToBottom();
    });

    chatForm.addEventListener('submit', function (event) {
        if (messageInput.value.trim() === '') {
            event.preventDefault();
        }
    });

    // Additional event listener for any WebSocket message
    document.body.addEventListener('htmx:wsMessage', function (event) {
        console.log('WebSocket message received:', event.detail.message);
        // Scroll to bottom after any WebSocket message
        scrollToBottom();
    });

    // MutationObserver to watch for changes in the message list
    const observer = new MutationObserver(function (mutations) {
        mutations.forEach(function (mutation) {
            if (mutation.type === 'childList') {
                scrollToBottom();
            }
        });
    });

    // Configure the observer to watch for child changes in the message list
    const config = {childList: true, subtree: true};
    observer.observe(messageList, config);
</script>
</body>
</html>