// ===== Feedback Logic =====

        function handleLike(msgId, btn) {
            const area = document.getElementById('fb-area-' + msgId.split('-')[1]);
            const btns = area.querySelectorAll('.fb-btn');
            btns.forEach(b => b.classList.remove('active-like', 'active-dislike'));
            btn.classList.add('active-like');

            // Close comment form if open
            const form = document.getElementById('comment-form-' + msgId);
            if (form) form.classList.remove('open');

            showToast(msgId, '? C?m on b?n d� d�nh gi�! Feedback d� du?c ghi nh?n.');
            console.log(`[Feedback] LIKE for ${msgId} ? s? POST /api/feedback {trace_id, rating: 1}`);
        }

        function handleDislike(msgId, btn) {
            const area = document.getElementById('fb-area-' + msgId.split('-')[1]);
            const btns = area.querySelectorAll('.fb-btn');
            btns.forEach(b => b.classList.remove('active-like', 'active-dislike'));
            btn.classList.add('active-dislike');

            // Auto-open comment form for dislike
            toggleCommentForm(msgId, true);
            console.log(`[Feedback] DISLIKE for ${msgId}`);
        }

        function toggleCommentForm(msgId, forceOpen = false) {
            const form = document.getElementById('comment-form-' + msgId);
            if (!form) return;

            if (forceOpen) {
                form.classList.add('open');
            } else {
                form.classList.toggle('open');
            }

            // Scroll into view
            if (form.classList.contains('open')) {
                setTimeout(() => form.scrollIntoView({ behavior: 'smooth', block: 'nearest' }), 100);
            }
        }

        function selectChip(chip, msgId) {
            const chips = document.querySelectorAll(`#chips-${msgId} .category-chip`);
            chips.forEach(c => c.classList.remove('selected'));
            chip.classList.add('selected');
        }

        function submitFeedback(msgId) {
            const textarea = document.getElementById('textarea-' + msgId);
            const comment = textarea ? textarea.value : '';
            const selectedChip = document.querySelector(`#chips-${msgId} .category-chip.selected`);
            const category = selectedChip ? selectedChip.textContent.trim() : 'Chua ch?n';

            console.log(`[Feedback] SUBMIT for ${msgId}:`);
            console.log(`  Category: ${category}`);
            console.log(`  Comment: ${comment}`);
            console.log(`  ? s? POST /api/feedback {trace_id, rating: 0, category, comment}`);
            console.log(`  ? AI Classifier s? ph�n lo?i ? Langfuse score`);

            // Close form + show toast
            const form = document.getElementById('comment-form-' + msgId);
            form.classList.remove('open');

            showToast(msgId, `? Ph?n h?i d� g?i! AI dang ph�n lo?i: "${category}"`);

            // Simulate AI processing
            setTimeout(() => {
                showToast(msgId, `? AI d� ph�n lo?i: ${category} | Severity: HIGH | �� ghi v�o h? th?ng ?`);
            }, 2000);
        }

        function showToast(msgId, message) {
            const toast = document.getElementById('toast-' + msgId);
            if (!toast) return;
            toast.textContent = message;
            toast.className = 'fb-toast success';
            toast.style.display = 'inline-block';
            setTimeout(() => { toast.style.display = 'none'; }, 5000);
        }

        function sendDemo() {
            const input = document.getElementById('chatInput');
            if (!input.value.trim()) return;

            const messages = document.getElementById('chatMessages');
            const msgId = 'msg-' + Date.now();

            // User message
            const userGroup = document.createElement('div');
            userGroup.className = 'msg-group user';
            userGroup.innerHTML = `
                <span class="msg-label">B?n</span>
                <div class="msg-bubble user">${input.value}</div>
            `;
            messages.appendChild(userGroup);

            // Bot response (simulated)
            setTimeout(() => {
                const botGroup = document.createElement('div');
                botGroup.className = 'msg-group bot';
                botGroup.id = msgId;
                botGroup.innerHTML = `
                    <span class="msg-label">Canifa AI</span>
                    <div class="msg-bubble bot">
                        D?, em d� nh?n c�u h?i c?a anh/ch? ?! ��y l� b?n demo n�n em chua x? l� du?c, nhung feedback s? ho?t d?ng b�nh thu?ng nh� ??
                    </div>
                    <div class="feedback-area" id="fb-area-${msgId}">
                        <button class="fb-btn" onclick="handleLike('${msgId}', this)">
                            <span class="icon">??</span> H?u �ch
                        </button>
                        <button class="fb-btn" onclick="handleDislike('${msgId}', this)">
                            <span class="icon">??</span>
                        </button>
                        <button class="fb-btn-comment" onclick="toggleCommentForm('${msgId}')">
                            <span class="icon">??</span> Ph�n n�n
                        </button>
                    </div>
                    <div class="feedback-comment-form" id="comment-form-${msgId}">
                        <div class="feedback-comment-inner">
                            <div class="fc-label">Ch?n lo?i ph?n h?i:</div>
                            <div class="feedback-category-chips" id="chips-${msgId}">
                                <button class="category-chip" onclick="selectChip(this, '${msgId}')">?? Thi?u d? li?u</button>
                                <button class="category-chip" onclick="selectChip(this, '${msgId}')">?? D? li?u sai</button>
                                <button class="category-chip" onclick="selectChip(this, '${msgId}')">?? Bot kh�ng hi?u</button>
                                <button class="category-chip" onclick="selectChip(this, '${msgId}')">? Kh�c</button>
                            </div>
                            <textarea class="feedback-textarea" id="textarea-${msgId}" placeholder="M� t? chi ti?t v?n d? b?n g?p..."></textarea>
                            <div class="feedback-submit-row">
                                <button class="fb-submit-btn fb-cancel-btn" onclick="toggleCommentForm('${msgId}')">H?y</button>
                                <button class="fb-submit-btn fb-send-btn" onclick="submitFeedback('${msgId}')">G?i ph?n h?i</button>
                            </div>
                        </div>
                    </div>
                    <div class="fb-toast" id="toast-${msgId}"></div>
                `;
                messages.appendChild(botGroup);
                botGroup.scrollIntoView({ behavior: 'smooth' });
            }, 800);

            input.value = '';
            messages.scrollTop = messages.scrollHeight;
        }