/**
 * Dashboard Note — AI Chatbot Widget
 * Floating chat button + panel with SSE streaming
 */

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 icon = document.getElementById('chatFabIcon');

    if (chatOpen) {
        panel.classList.add('show');
        fab.classList.add('open');
        icon.innerHTML = '<line x1="18" y1="6" x2="6" y2="18" stroke="white" stroke-width="2" stroke-linecap="round"/><line x1="6" y1="6" x2="18" y2="18" stroke="white" stroke-width="2" stroke-linecap="round"/>';
        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');
        icon.innerHTML = '<path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H5.17L4 17.17V4h16v12z"/><path d="M7 9h2v2h-2zm4 0h2v2h-2zm4 0h2v2h-2z"/>';
        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');

    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>`;
        }
    });

    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();
        }
    });

    // ── Drag & Drop: FAB Button ──
    initDraggable('chatFab', null); // drag entire element
    // ── Drag & Drop: Chat Panel (via header) ──
    initDraggable('chatPanel', '.chat-header');
});

// ═══════════════════════════════════════════════════════
// DRAG & DROP ENGINE
// ═══════════════════════════════════════════════════════
function initDraggable(elementId, handleSelector) {
    const el = document.getElementById(elementId);
    if (!el) return;
    const handle = handleSelector ? el.querySelector(handleSelector) : el;
    if (!handle) return;

    let isDragging = false;
    let startX, startY, origX, origY;
    let hasMoved = false;
    const DEAD_ZONE = 5; // px threshold to distinguish click from drag

    handle.style.cursor = 'grab';

    handle.addEventListener('mousedown', onStart);
    handle.addEventListener('touchstart', onStart, { passive: false });

    function onStart(e) {
        // Don't drag if clicking buttons/inputs inside handle
        const tag = e.target.tagName.toLowerCase();
        if (['button', 'input', 'textarea', 'select', 'a'].includes(tag)) return;
        if (e.target.closest('button, input, textarea, select, a')) return;

        e.preventDefault();
        const pos = getPointer(e);
        startX = pos.x;
        startY = pos.y;
        hasMoved = false;

        const rect = el.getBoundingClientRect();
        origX = rect.left;
        origY = rect.top;

        document.addEventListener('mousemove', onMove);
        document.addEventListener('mouseup', onEnd);
        document.addEventListener('touchmove', onMove, { passive: false });
        document.addEventListener('touchend', onEnd);
    }

    function onMove(e) {
        e.preventDefault();
        const pos = getPointer(e);
        const dx = pos.x - startX;
        const dy = pos.y - startY;

        if (!hasMoved && Math.abs(dx) < DEAD_ZONE && Math.abs(dy) < DEAD_ZONE) return;

        if (!hasMoved) {
            hasMoved = true;
            isDragging = true;
            handle.style.cursor = 'grabbing';
            el.style.transition = 'none';
            // Switch from bottom/right to top/left for free positioning
            el.style.position = 'fixed';
        }

        let newX = origX + dx;
        let newY = origY + dy;

        // Clamp to viewport
        const w = el.offsetWidth;
        const h = el.offsetHeight;
        newX = Math.max(0, Math.min(window.innerWidth - w, newX));
        newY = Math.max(0, Math.min(window.innerHeight - h, newY));

        el.style.left = newX + 'px';
        el.style.top = newY + 'px';
        el.style.right = 'auto';
        el.style.bottom = 'auto';
    }

    function onEnd() {
        document.removeEventListener('mousemove', onMove);
        document.removeEventListener('mouseup', onEnd);
        document.removeEventListener('touchmove', onMove);
        document.removeEventListener('touchend', onEnd);
        handle.style.cursor = 'grab';
        el.style.transition = '';
        isDragging = false;

        // If we dragged the FAB, suppress the click (toggleChat)
        if (hasMoved && elementId === 'chatFab') {
            el.addEventListener('click', suppressClick, { capture: true, once: true });
        }
    }

    function suppressClick(e) {
        e.stopPropagation();
        e.preventDefault();
    }

    function getPointer(e) {
        if (e.touches && e.touches.length) return { x: e.touches[0].clientX, y: e.touches[0].clientY };
        return { x: e.clientX, y: e.clientY };
    }
}
