<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Live Chat - {{ video_id }}</title>
    <script
        src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.7.4/socket.io.min.js"
        integrity="sha384-Gr6Lu2Ajx28mzwyVR8CFkULdCU7kMlZ9UthllibdOSo6qAiN+yXNHqtgdTvFXMT4"
        crossorigin="anonymous"></script>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #0f0f0f; color: #fff; }
        .chat-container { display: flex; flex-direction: column; height: 100vh; max-width: 400px; margin: 0 auto; border-left: 1px solid #333; border-right: 1px solid #333; }
        .chat-header { padding: 12px 16px; background: #1a1a1a; border-bottom: 1px solid #333; font-weight: 600; display: flex; justify-content: space-between; align-items: center; }
        .chat-header .viewers { font-size: 12px; color: #aaa; }
        .chat-messages { flex: 1; overflow-y: auto; padding: 8px 16px; }
        .msg { padding: 4px 0; animation: fadeIn 0.3s; }
        .msg .author { font-weight: 600; color: #3ea6ff; margin-right: 8px; font-size: 13px; }
        .msg .text { font-size: 13px; color: #ddd; word-break: break-word; }
        .msg.super { background: linear-gradient(135deg, #ffb300 0%, #ff6f00 100%); padding: 8px 12px; border-radius: 8px; margin: 4px 0; }
        .msg.super .author { color: #fff; }
        .msg.super .text { color: #fff; }
        .msg.super .tip { font-size: 11px; color: rgba(255,255,255,0.8); }
        .msg.system { color: #888; font-size: 12px; font-style: italic; text-align: center; padding: 4px 0; }
        .chat-input { padding: 12px 16px; background: #1a1a1a; border-top: 1px solid #333; display: flex; gap: 8px; }
        .chat-input input { flex: 1; background: #272727; border: 1px solid #444; border-radius: 20px; padding: 8px 16px; color: #fff; font-size: 13px; outline: none; }
        .chat-input input:focus { border-color: #3ea6ff; }
        .chat-input button { background: #3ea6ff; border: none; border-radius: 20px; padding: 8px 16px; color: #fff; cursor: pointer; font-size: 13px; font-weight: 600; }
        .chat-input button:hover { background: #2196f3; }
        .super-btn { background: #ffb300 !important; }
        .super-btn:hover { background: #ff8f00 !important; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } }
        .mod-bar { padding: 8px 16px; background: #1a1a1a; border-top: 1px solid #333; display: flex; gap: 6px; }
        .mod-bar button { background: #333; border: none; padding: 4px 10px; border-radius: 4px; color: #aaa; cursor: pointer; font-size: 11px; }
        .mod-bar button:hover { background: #555; color: #fff; }
    </style>
</head>
<body>
    <div class="chat-container">
        <div class="chat-header">
            <span>Live Chat</span>
            <span class="viewers" id="viewer-count">0 watching</span>
        </div>
        <div class="chat-messages" id="messages"></div>
        {% if is_mod %}
        <div class="mod-bar">
            <button onclick="toggleSlowMode()">Slow Mode</button>
            <button onclick="clearChat()">Clear</button>
        </div>
        {% endif %}
        <div class="chat-input">
            <input type="text" id="msg-input" placeholder="Send a message..." maxlength="500"
                   onkeydown="if(event.key==='Enter')sendMsg()">
            <button onclick="sendMsg()">Send</button>
            <button class="super-btn" onclick="sendSuper()">$ Super</button>
        </div>
    </div>

    <script>
        const videoId = "{{ video_id }}";
        const username = "{{ username }}";
        const isMod = {{ 'true' if is_mod else 'false' }};

        const socket = io({ transports: ['websocket', 'polling'] });
        const messagesEl = document.getElementById('messages');

        socket.on('connect', () => {
            socket.emit('join', { video_id: videoId, username: username });
        });

        socket.on('new_message', (data) => {
            addMessage(data);
        });

        socket.on('system', (data) => {
            const div = document.createElement('div');
            div.className = 'msg system';
            div.textContent = data.message;
            messagesEl.appendChild(div);
            messagesEl.scrollTop = messagesEl.scrollHeight;
        });

        socket.on('error', (data) => {
            alert(data.message);
        });

        function addMessage(data) {
            const div = document.createElement('div');
            div.className = 'msg' + (data.is_super ? ' super' : '');
            let html = `<span class="author">${escapeHtml(data.username)}</span><span class="text">${escapeHtml(data.message)}</span>`;
            if (data.is_super && data.tip_amount) {
                html += `<div class="tip">${data.tip_amount} RTC</div>`;
            }
            div.innerHTML = html;
            messagesEl.appendChild(div);
            messagesEl.scrollTop = messagesEl.scrollHeight;
        }

        function sendMsg() {
            const input = document.getElementById('msg-input');
            const msg = input.value.trim();
            if (!msg) return;
            socket.emit('chat_message', { video_id: videoId, username: username, message: msg });
            input.value = '';
        }

        function sendSuper() {
            const input = document.getElementById('msg-input');
            const msg = input.value.trim();
            if (!msg) return;
            const tip = prompt('RTC tip amount:', '1');
            if (!tip) return;
            socket.emit('super_chat', { video_id: videoId, username: username, message: msg, tip_amount: parseFloat(tip) });
            input.value = '';
        }

        function toggleSlowMode() {
            socket.emit('mod_action', { action: 'slow_mode', video_id: videoId, mod_name: username });
        }

        function clearChat() {
            messagesEl.innerHTML = '';
        }

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // Load history
        fetch(`/api/chat/${videoId}/history`)
            .then(r => r.json())
            .then(msgs => msgs.forEach(addMessage))
            .catch(() => {});
    </script>
</body>
</html>
