{% extends 'base/layout.html' %}

{% block content %}
    <div class="card">
        <div class="card-header">WebSocket Test</div>
        <div class="card-body">
            <p>FastAPI URL: {{ fastapi_url }}</p>
            <p>WebSocket URL: {{ fastapi_websocket_url }}</p>
            <form id="message-form">
                <input id="message-input" class="form-control mb-2" type="text" placeholder="Message">
                <button class="btn btn-primary" type="submit">Send</button>
            </form>
            <ul id="chat-room" class="mt-3"></ul>
        </div>
    </div>
    <script>
        const socket = new WebSocket("{{ fastapi_websocket_url|escapejs }}/test");
        const form = document.getElementById("message-form");
        const input = document.getElementById("message-input");
        const room = document.getElementById("chat-room");

        form.addEventListener("submit", (event) => {
            event.preventDefault();
            if (socket.readyState === WebSocket.OPEN && input.value) {
                socket.send(input.value);
                input.value = "";
            }
        });

        socket.addEventListener("message", (event) => {
            const item = document.createElement("li");
            item.textContent = event.data;
            room.appendChild(item);
        });
    </script>
{% endblock %}
