// ═══════════════════════════════════════════════════════
const API = '/api/notes/v2';
let currentTag = '';
let currentSearch = '';
let newTags = [];
let searchTimer = null;
let activeTab = 'memos';

// ═══════════════════════════════════════════════════════
// INIT
// ═══════════════════════════════════════════════════════
document.addEventListener('DOMContentLoaded', () => {
    loadAll();
    setupTagInput();
    setupShortcuts();
});

function loadAll() {
    loadNotes();
    loadStats();
    loadTags();
}

// ═══════════════════════════════════════════════════════
// TAB SWITCHING
// ═══════════════════════════════════════════════════════
function switchTab(btn) {
    const tab = btn.dataset.tab;
    activeTab = tab;

    // Update nav
    document.querySelectorAll('.nav-btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');

    // Show/hide sections
    document.querySelectorAll('.page-section').forEach(s => s.classList.remove('active'));
    document.getElementById(`tab-${tab}`).classList.add('active');

    // Update topbar
    const titles = { memos: 'Memos', explore: 'Explore', archived: 'Archived', settings: 'Settings', inbox: '📬 Inbox' };
    document.getElementById('topbarTitle').textContent = titles[tab] || tab;

    // Load tab-specific data
    if (tab === 'archived') loadArchived();
    if (tab === 'explore') loadExplore();
    if (tab === 'settings') loadSettingsData();
    if (tab === 'inbox') loadInbox();
}

// ═══════════════════════════════════════════════════════
// API LAYER
// ═══════════════════════════════════════════════════════
async function apiGet(path) {
    const res = await fetch(`${API}${path}`);
    return res.json();
}
async function apiPost(path, body) {
    const res = await fetch(`${API}${path}`, {
        method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify(body)
    });
    return res.json();
}
async function apiPatch(path, body) {
    const res = await fetch(`${API}${path}`, {
        method: 'PATCH', headers: {'Content-Type':'application/json'}, body: JSON.stringify(body)
    });
    return res.json();
}
async function apiDelete(path) {
    const res = await fetch(`${API}${path}`, { method: 'DELETE' });
    return res.json();
}

// ═══════════════════════════════════════════════════════
// LOAD DATA
// ═══════════════════════════════════════════════════════
async function loadNotes() {
    let p = '/?limit=100';
    if (currentTag) p += `&tag=${encodeURIComponent(currentTag)}`;
    if (currentSearch) p += `&search=${encodeURIComponent(currentSearch)}`;

    const data = await apiGet(p);
    renderNotes(data.data || [], 'noteList', 'emptyMemos');
}

async function loadArchived() {
    const data = await apiGet('/?include_archived=true&limit=100');
    const archived = (data.data || []).filter(n => n.row_status === 'ARCHIVED');
    renderNotes(archived, 'archivedList', 'emptyArchived', true);
}

async function loadExplore() {
    const data = await apiGet('/?limit=100');
    const pub = (data.data || []).filter(n => n.visibility === 'PUBLIC' || n.visibility === 'PROTECTED');
    renderNotes(pub, 'exploreList', 'emptyExplore');
}

async function loadStats() {
    const data = await apiGet('/stats');
    const s = data.data || {};
    document.getElementById('sTotal').textContent = s.total || 0;
    document.getElementById('sPinned').textContent = s.pinned || 0;
    document.getElementById('sArchived').textContent = s.archived || 0;

    const ab = document.getElementById('archivedBadge');
    if (s.archived > 0) { ab.textContent = s.archived; ab.style.display = ''; }
    else { ab.style.display = 'none'; }
}

async function loadTags() {
    const data = await apiGet('/tags');
    const tags = data.data || [];
    const bar = document.getElementById('filterRow');
    bar.querySelectorAll('.filter-pill.dyn').forEach(e => e.remove());

    tags.forEach(tag => {
        const el = document.createElement('span');
        el.className = `filter-pill dyn${currentTag === tag ? ' active' : ''}`;
        el.dataset.tag = tag;
        el.textContent = `#${tag}`;
        el.onclick = () => filterByTag(el);
        bar.appendChild(el);
    });
}

async function loadSettingsData() {
    const data = await apiGet('/stats');
    const s = data.data || {};
    document.getElementById('settingTotal').textContent = s.total || 0;
    document.getElementById('settingPinned').textContent = s.pinned || 0;
    document.getElementById('settingArchived').textContent = s.archived || 0;

    const tagData = await apiGet('/tags');
    document.getElementById('settingTags').textContent = (tagData.data || []).length;
}

// ═══════════════════════════════════════════════════════
// RENDER
// ═══════════════════════════════════════════════════════
function renderNotes(notes, containerId, emptyId, isArchivedView) {
    const list = document.getElementById(containerId);
    const empty = document.getElementById(emptyId);

    if (!notes.length) {
        list.innerHTML = '';
        if (empty) empty.style.display = '';
        return;
    }
    if (empty) empty.style.display = 'none';

    list.innerHTML = notes.map(note => {
        const html = marked.parse(note.content || '', { breaks: true });
        const time = note.created_at ? new Date(note.created_at).toLocaleString('vi-VN') : '';
        const tags = (note.tags || []).map(t =>
            `<span class="note-tag" onclick="filterByTag(null, '${t}')">#${t}</span>`
        ).join('');
        const pinClass = note.pinned ? ' pinned' : '';
        const pinLabel = note.pinned ? 'Unpin' : 'Pin';
        const creatorId = note.creator_id || 'system';
        const initials = creatorId.slice(0,2).toUpperCase();
        const commentCount = note.comment_count || 0;
        const visClass = (note.visibility||'PRIVATE').toLowerCase();
        const visLabel = (note.visibility||'PRIVATE');

        let menuItems = '';
        if (isArchivedView) {
            menuItems = `
                <button class="action-menu-item" onclick="restoreNote('${note.uid}')">↩ Restore</button>
                <div class="menu-separator"></div>
                <button class="action-menu-item danger" onclick="hardDeleteNote('${note.uid}')">🗑 Delete forever</button>`;
        } else {
            menuItems = `
                <button class="action-menu-item" onclick="startEdit('${note.uid}')">✏️ Edit</button>
                <button class="action-menu-item" onclick="pinNote('${note.uid}')">${note.pinned ? '📌 Unpin' : '📌 Pin'}</button>
                <button class="action-menu-item" onclick="shareNoteLink('${note.uid}')">🔗 Copy link</button>
                <div class="menu-separator"></div>
                <button class="action-menu-item danger" onclick="deleteNote('${note.uid}')">📦 Archive</button>`;
        }

        return `
        <div class="note-card${pinClass}" id="note-${note.uid}">
            <div class="note-header-row">
                <div class="note-creator">
                    <div class="creator-avatar">${initials}</div>
                    <div class="creator-info">
                        <span class="creator-name">${esc(creatorId)}</span>
                        <span class="creator-time">${time} <span class="vis-icon ${visClass}">${visLabel}</span></span>
                    </div>
                </div>
                <div class="action-menu-container">
                    <button class="action-menu-trigger" onclick="toggleActionMenu(event,'menu-${note.uid}')">⋯</button>
                    <div class="action-menu-dropdown" id="menu-${note.uid}">${menuItems}</div>
                </div>
            </div>
            ${note.pinned ? '<div class="pin-badge">📌 Pinned</div>' : ''}
            <div class="note-body" onclick="openMemoDetail('${note.uid}')" style="cursor:pointer">${html}</div>
            <div class="edit-panel">
                <textarea id="edit-${note.uid}">${esc(note.content || '')}</textarea>
                <div class="edit-btns">
                    <button onclick="cancelEdit('${note.uid}')">Cancel</button>
                    <button class="btn-ok" onclick="confirmEdit('${note.uid}')">Save</button>
                </div>
            </div>
            <div class="note-footer">
                <div class="note-footer-left">
                    <div class="note-tags">${tags}</div>
                    <button class="comment-count-btn" onclick="openMemoDetail('${note.uid}')" title="Comments">💬 ${commentCount}</button>
                </div>
            </div>
        </div>`;
    }).join('');
}

// ═══════════════════════════════════════════════════════
// CREATE
// ═══════════════════════════════════════════════════════
async function saveNote() {
    const input = document.getElementById('noteInput');
    const content = input.value.trim();
    if (!content) return;

    const vis = document.getElementById('visibilitySelect').value;
    const btn = document.getElementById('btnSave');
    btn.disabled = true;
    try {
        await apiPost('/', { content, tags: [...newTags], visibility: vis });
        input.value = '';
        newTags = [];
        renderNewTags();
        toast('Đã lưu ghi chú');
        loadAll();
    } catch { toast('Lỗi khi lưu'); }
    finally { btn.disabled = false; }
}

// ═══════════════════════════════════════════════════════
// EDIT
// ═══════════════════════════════════════════════════════
function startEdit(uid) { document.getElementById(`note-${uid}`).classList.add('editing'); }
function cancelEdit(uid) { document.getElementById(`note-${uid}`).classList.remove('editing'); }

async function confirmEdit(uid) {
    const content = document.getElementById(`edit-${uid}`).value.trim();
    if (!content) return;
    await apiPatch(`/${uid}`, { content });
    toast('Đã cập nhật');
    loadNotes();
}

// ═══════════════════════════════════════════════════════
// PIN / DELETE / RESTORE
// ═══════════════════════════════════════════════════════
async function pinNote(uid) {
    await apiPost(`/${uid}/pin`);
    toast('Đã cập nhật ghim');
    loadAll();
}

async function deleteNote(uid) {
    if (!confirm('Archive ghi chú này?')) return;
    await apiDelete(`/${uid}`);
    toast('Đã archive');
    loadAll();
}

async function restoreNote(uid) {
    await apiPatch(`/${uid}`, { row_status: 'NORMAL' });
    toast('Đã khôi phục');
    loadArchived();
    loadStats();
}

async function hardDeleteNote(uid) {
    if (!confirm('Xóa vĩnh viễn?')) return;
    await apiDelete(`/${uid}?hard=true`);
    toast('Đã xóa vĩnh viễn');
    loadArchived();
    loadStats();
}

// ═══════════════════════════════════════════════════════
// FILTER / SEARCH
// ═══════════════════════════════════════════════════════
function filterByTag(el, tagName) {
    const tag = tagName || (el ? el.dataset.tag : '');
    currentTag = tag;
    document.querySelectorAll('.filter-pill').forEach(t => t.classList.remove('active'));
    if (el) el.classList.add('active');
    else document.querySelectorAll('.filter-pill').forEach(t => { if (t.dataset.tag === tag) t.classList.add('active'); });
    loadNotes();
}

function debounceSearch() {
    clearTimeout(searchTimer);
    searchTimer = setTimeout(() => {
        currentSearch = document.getElementById('searchInput').value.trim();
        loadNotes();
    }, 300);
}

// ═══════════════════════════════════════════════════════
// TAG INPUT
// ═══════════════════════════════════════════════════════
function setupTagInput() {
    const input = document.getElementById('tagInput');
    input.addEventListener('keydown', e => {
        if (e.key === 'Enter' && input.value.trim()) {
            e.preventDefault();
            const tag = input.value.trim().replace(/^#/, '');
            if (tag && !newTags.includes(tag)) { newTags.push(tag); renderNewTags(); }
            input.value = '';
        }
    });
}

function renderNewTags() {
    document.getElementById('newTagChips').innerHTML = newTags.map((t, i) =>
        `<span class="tag-chip removable" onclick="removeNewTag(${i})">#${t}</span>`
    ).join('');
}
function removeNewTag(i) { newTags.splice(i, 1); renderNewTags(); }

// ═══════════════════════════════════════════════════════
// KEYBOARD SHORTCUTS
// ═══════════════════════════════════════════════════════
function setupShortcuts() {
    document.addEventListener('keydown', e => {
        if (e.ctrlKey && e.key === 'Enter' && document.activeElement.id === 'noteInput') {
            e.preventDefault(); saveNote();
        }
        if (e.ctrlKey && e.key === 'k') {
            e.preventDefault(); document.getElementById('searchInput').focus();
        }
    });
}

// ═══════════════════════════════════════════════════════
// UTILS
// ═══════════════════════════════════════════════════════
function esc(s) { return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }

function toast(msg) {
    const t = document.getElementById('toast');
    t.textContent = msg;
    t.classList.add('show');
    setTimeout(() => t.classList.remove('show'), 2400);
}

// ═══ MARKED CONFIG ═══
marked.setOptions({
    highlight: (code, lang) => {
        if (lang && hljs.getLanguage(lang)) return hljs.highlight(code, { language: lang }).value;
        return hljs.highlightAuto(code).value;
    },
    breaks: true,
    gfm: true,
});

// ═══════════════════════════════════════════════════════
// SOCIAL FEATURES — Memo Detail, Comments, Inbox, Share
// ═══════════════════════════════════════════════════════
let currentMemoUid = null;
let currentInboxFilter = 'all';

// ── Action Menu ──
function toggleActionMenu(e, menuId) {
    e.stopPropagation();
    document.querySelectorAll('.action-menu-dropdown.show').forEach(m => {
        if (m.id !== menuId) m.classList.remove('show');
    });
    document.getElementById(menuId).classList.toggle('show');
}
document.addEventListener('click', () => {
    document.querySelectorAll('.action-menu-dropdown.show').forEach(m => m.classList.remove('show'));
});

// ── Share ──
function shareNoteLink(uid) {
    const url = `${location.origin}${location.pathname}?memo=${uid}`;
    navigator.clipboard.writeText(url).then(() => toast('📋 Đã copy link!')).catch(() => toast('Copy failed'));
    document.querySelectorAll('.action-menu-dropdown.show').forEach(m => m.classList.remove('show'));
}
function shareMemo() {
    if (!currentMemoUid) return;
    shareNoteLink(currentMemoUid);
}

// ── Memo Detail Modal ──
async function openMemoDetail(uid) {
    currentMemoUid = uid;
    try {
        const data = await apiGet(`/${uid}`);
        const note = data.data;
        if (!note) { toast('Không tìm thấy note'); return; }

        const creatorId = note.creator_id || 'system';
        document.getElementById('modalAvatar').textContent = creatorId.slice(0,2).toUpperCase();
        document.getElementById('modalCreatorName').textContent = creatorId;
        document.getElementById('modalTime').textContent = note.created_at ? new Date(note.created_at).toLocaleString('vi-VN') : '';
        document.getElementById('modalContent').innerHTML = marked.parse(note.content || '', { breaks: true });

        const tagsHtml = (note.tags || []).map(t => `<span class="note-tag">#${t}</span>`).join('');
        document.getElementById('modalTags').innerHTML = tagsHtml;

        document.getElementById('memoModalOverlay').classList.add('show');
        document.body.style.overflow = 'hidden';

        loadComments(uid);
        hideCommentEditor();
    } catch (e) {
        console.error('Open memo detail error:', e);
        toast('Lỗi khi mở chi tiết');
    }
}

function closeMemoModal() {
    document.getElementById('memoModalOverlay').classList.remove('show');
    document.body.style.overflow = '';
    currentMemoUid = null;
}
function closeMemoModalOutside(e) {
    if (e.target.id === 'memoModalOverlay') closeMemoModal();
}

// ── Comments ──
async function loadComments(uid) {
    try {
        const data = await apiGet(`/${uid}/comments`);
        const comments = data.data || [];
        document.getElementById('commentsCountBadge').textContent = comments.length;

        if (comments.length === 0) {
            document.getElementById('commentList').innerHTML = '';
            document.getElementById('emptyComments').style.display = '';
        } else {
            document.getElementById('emptyComments').style.display = 'none';
            document.getElementById('commentList').innerHTML = comments.map(c => {
                const name = c.creator_name || c.creator_id || 'Ẩn danh';
                const initials = name.slice(0,2).toUpperCase();
                const time = c.created_at ? new Date(c.created_at).toLocaleString('vi-VN') : '';
                const content = marked.parse(c.content || '', { breaks: true });
                return `
                <div class="comment-item">
                    <div class="comment-avatar">${initials}</div>
                    <div class="comment-body">
                        <div class="comment-meta">
                            <span class="comment-author">${esc(name)}</span>
                            <span class="comment-time">${time}</span>
                        </div>
                        <div class="comment-content">${content}</div>
                    </div>
                </div>`;
            }).join('');
        }
    } catch (e) {
        console.error('Load comments error:', e);
    }
}

function showCommentEditor() {
    document.getElementById('commentCTA').style.display = 'none';
    document.getElementById('commentEditorWrap').style.display = '';
    // Restore saved name
    const saved = localStorage.getItem('commentDisplayName');
    if (saved) document.getElementById('commentNameInput').value = saved;
    document.getElementById('commentTextarea').focus();
}
function hideCommentEditor() {
    document.getElementById('commentCTA').style.display = '';
    document.getElementById('commentEditorWrap').style.display = 'none';
    document.getElementById('commentTextarea').value = '';
}

async function submitComment() {
    if (!currentMemoUid) return;
    const content = document.getElementById('commentTextarea').value.trim();
    if (!content) return;

    const name = document.getElementById('commentNameInput').value.trim() || null;
    if (name) localStorage.setItem('commentDisplayName', name);

    const btn = document.getElementById('commentSubmitBtn');
    btn.disabled = true;
    try {
        await apiPost(`/${currentMemoUid}/comments`, {
            content,
            creator_name: name,
            creator_id: 'anonymous',
        });
        document.getElementById('commentTextarea').value = '';
        toast('💬 Đã gửi bình luận!');
        loadComments(currentMemoUid);
        hideCommentEditor();
        // Refresh note list to update comment count
        loadNotes();
    } catch (e) {
        console.error('Submit comment error:', e);
        toast('Lỗi khi gửi bình luận');
    } finally {
        btn.disabled = false;
    }
}

// ── Inbox / Notifications ──
async function loadInbox() {
    try {
        let url = '/notifications/list?recipient_id=system';
        if (currentInboxFilter === 'UNREAD') url += '&status=UNREAD';
        const data = await apiGet(url);
        const notifications = data.data || [];
        const unread = data.unread_count || 0;

        // Update badge
        const badge = document.getElementById('inboxBadge');
        if (unread > 0) { badge.textContent = unread; badge.style.display = ''; }
        else { badge.style.display = 'none'; }

        if (notifications.length === 0) {
            document.getElementById('notificationList').innerHTML = '';
            document.getElementById('emptyInbox').style.display = '';
            return;
        }
        document.getElementById('emptyInbox').style.display = 'none';

        document.getElementById('notificationList').innerHTML = notifications.map(n => {
            const name = n.sender_name || n.sender_id || 'Someone';
            const initials = name.slice(0,2).toUpperCase();
            const time = n.created_at ? new Date(n.created_at).toLocaleString('vi-VN') : '';
            const isUnread = n.status === 'UNREAD';
            return `
            <div class="notification-item${isUnread ? ' unread' : ''}" onclick="openNotification(${n.id}, '${n.note_uid}')">
                <div class="notification-avatar">${initials}</div>
                <div class="notification-body">
                    <div class="notification-text"><strong>${esc(name)}</strong> commented on your note</div>
                    <div class="notification-time">${time}</div>
                </div>
            </div>`;
        }).join('');
    } catch (e) {
        console.error('Load inbox error:', e);
    }
}

function filterInbox(btn, filter) {
    currentInboxFilter = filter;
    document.querySelectorAll('.inbox-filter-btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    loadInbox();
}

async function markAllRead() {
    try {
        await apiPost('/notifications/read-all?recipient_id=system', {});
        toast('✅ Đã đánh dấu tất cả đã đọc');
        loadInbox();
    } catch (e) { console.error(e); }
}

async function openNotification(notifId, noteUid) {
    try { await apiPatch(`/notifications/${notifId}/read`, {}); } catch {}
    closeMemoModal();
    openMemoDetail(noteUid);
    loadInbox();
}

// ── Load inbox badge on init ──
async function loadInboxBadge() {
    try {
        const data = await apiGet('/notifications/list?recipient_id=system&limit=1');
        const unread = data.unread_count || 0;
        const badge = document.getElementById('inboxBadge');
        if (unread > 0) { badge.textContent = unread; badge.style.display = ''; }
        else { badge.style.display = 'none'; }
    } catch {}
}

// ── Deep link support ──
function checkDeepLink() {
    const params = new URLSearchParams(location.search);
    const memoUid = params.get('memo');
    if (memoUid) openMemoDetail(memoUid);
}

// Patch init
const _origLoadAll = loadAll;
loadAll = function() {
    _origLoadAll();
    loadInboxBadge();
    checkDeepLink();
};

// ═══════════════════════════════════════════════════════
// AI CHATBOT WIDGET
// ═══════════════════════════════════════════════════════
let chatOpen = false;
let chatExpanded = false;
let chatMessages = [];
let chatLoading = false;
let chatHistoryCursor = null;
let chatHistoryLoading = false;

function toggleChat() {
    chatOpen = !chatOpen;
    const panel = document.getElementById('chatPanel');
    const fab = document.getElementById('chatFab');
    const pulse = document.getElementById('chatPulse');
    const fabIcon = document.getElementById('chatFabIcon');

    if (chatOpen) {
        panel.classList.add('show');
        fab.classList.add('open');
        fabIcon.textContent = 'X';
        pulse.style.display = 'none';
        if (chatMessages.length === 0) loadChatHistory(true);
        setTimeout(() => document.getElementById('chatInput').focus(), 200);
    } else {
        panel.classList.remove('show');
        fab.classList.remove('open');
        fabIcon.textContent = 'Chat';
        pulse.style.display = '';
        chatExpanded = false;
        panel.classList.remove('expanded');
    }
}

function toggleExpand() {
    chatExpanded = !chatExpanded;
    const panel = document.getElementById('chatPanel');
    const btn = document.getElementById('btnExpand');
    if (chatExpanded) {
        panel.classList.add('expanded');
        btn.textContent = 'Collapse';
    } else {
        panel.classList.remove('expanded');
        btn.textContent = 'Expand';
    }
}

function renderChatMessages() {
    const container = document.getElementById('chatMessages');
    const loadMoreEl = document.getElementById('chatLoadMore');

    let html = '';
    chatMessages.forEach(msg => {
        if (msg.role === 'user') {
            html += `<div class="chat-bubble user">${esc(msg.content)}</div>`;
        } else {
            const parsed = marked.parse(msg.content || '', { breaks: true });
            html += `<div class="chat-bubble ai">${parsed}</div>`;
        }
    });

    // Keep load-more button, then add messages
    const loadMoreHtml = chatHistoryCursor
        ? '<div class="chat-load-more"><button onclick="loadOlderHistory()">Load older messages</button></div>'
        : '';
    container.innerHTML = loadMoreHtml + html;
    container.scrollTop = container.scrollHeight;
}

function addChatMessage(role, content) {
    chatMessages.push({ role, content });
    renderChatMessages();
}

function updateLastAI(content) {
    if (chatMessages.length && chatMessages[chatMessages.length - 1].role === 'ai') {
        chatMessages[chatMessages.length - 1].content = content;
        renderChatMessages();
    }
}

function appendLastAI(token) {
    if (chatMessages.length && chatMessages[chatMessages.length - 1].role === 'ai') {
        chatMessages[chatMessages.length - 1].content += token;
        renderChatMessages();
    }
}

// ── Chat History ──
async function loadChatHistory(isRefresh) {
    if (chatHistoryLoading) return;
    chatHistoryLoading = true;

    try {
        const cursor = isRefresh ? null : chatHistoryCursor;
        let url = '/api/history/me?limit=20';
        if (cursor) url += `&before_id=${cursor}`;

        const res = await fetch(url);
        if (!res.ok) throw new Error('Failed');
        const data = await res.json();

        const items = Array.isArray(data.data) ? data.data : [];
        chatHistoryCursor = data.next_cursor || null;

        if (items.length === 0) {
            if (isRefresh && chatMessages.length === 0) {
                chatMessages = [{ role: 'ai', content: 'Xin chào! Mình là Canifa Assistant. Bạn muốn tìm ghi chú gì hôm nay?' }];
            }
            renderChatMessages();
            return;
        }

        const batch = items.reverse().map(item => {
            if (item.is_human) return { role: 'user', content: String(item.message || '') };
            let content = String(item.message || '');
            try {
                const p = JSON.parse(content);
                if (p && p.ai_response) content = p.ai_response;
            } catch {}
            return { role: 'ai', content };
        });

        if (isRefresh) {
            chatMessages = batch;
        } else {
            chatMessages = [...batch, ...chatMessages];
        }
        renderChatMessages();
    } catch (e) {
        console.error('History load error:', e);
        if (isRefresh && chatMessages.length === 0) {
            chatMessages = [{ role: 'ai', content: 'Xin chào! Mình là Canifa Assistant. Bạn có thể hỏi mình bất cứ điều gì.' }];
            renderChatMessages();
        }
    } finally {
        chatHistoryLoading = false;
    }
}

function loadOlderHistory() { loadChatHistory(false); }

async function clearChatHistory() {
    try {
        await fetch('/api/history/me', { method: 'DELETE' });
        chatMessages = [{ role: 'ai', content: 'Đã xóa lịch sử chat! Mình có thể giúp gì cho bạn?' }];
        chatHistoryCursor = null;
        renderChatMessages();
    } catch (e) {
        console.error('Clear history error:', e);
    }
}

// ── Send Message (SSE Streaming) ──
async function sendChatMessage() {
    const input = document.getElementById('chatInput');
    const msg = input.value.trim();
    if (!msg || chatLoading) return;

    input.value = '';
    chatLoading = true;
    document.getElementById('chatSendBtn').disabled = true;
    document.getElementById('chatTyping').classList.add('show');

    addChatMessage('user', msg);
    addChatMessage('ai', '');  // placeholder

    try {
        const res = await fetch('/api/agent/chat/stream', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ user_query: msg }),
        });

        if (!res.ok || !res.body) throw new Error('Stream failed');

        const reader = res.body.getReader();
        const decoder = new TextDecoder();
        let buffer = '';

        while (true) {
            const { done, value } = await reader.read();
            if (done) break;

            buffer += decoder.decode(value, { stream: true });
            const lines = buffer.split('\n');
            buffer = lines.pop() || '';

            for (const line of lines) {
                const trimmed = line.trim();
                if (!trimmed.startsWith('data: ')) continue;
                try {
                    const d = JSON.parse(trimmed.slice(6));
                    if (d.token) appendLastAI(d.token);
                    if (d.done && d.ai_response) updateLastAI(d.ai_response);
                    if (d.error) throw new Error(d.error);
                } catch {}
            }
        }
    } catch (e) {
        console.error('Chat error:', e);
        if (chatMessages.length && chatMessages[chatMessages.length - 1].role === 'ai' && !chatMessages[chatMessages.length - 1].content) {
            updateLastAI('Xin lỗi, đang gặp sự cố kết nối. Vui lòng thử lại.');
        }
    } finally {
        chatLoading = false;
        document.getElementById('chatSendBtn').disabled = false;
        document.getElementById('chatTyping').classList.remove('show');
    }
}

// Chat input Enter key
document.addEventListener('DOMContentLoaded', () => {
    document.getElementById('chatInput').addEventListener('keydown', e => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendChatMessage();
        }
    });
});