// ─── AI CHATBOT WIDGET INIT ───
// Injects the Canifa AI Stylist chatbot DOM elements and logic into the page.

(function() {
    // 1. Inject dependencies if not present
    if (!window.DOMPurify) {
        const dpScript = document.createElement('script');
        dpScript.src = "https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.0.3/purify.min.js";
        document.head.appendChild(dpScript);
    }
    if (!window.marked) {
        const markedScript = document.createElement('script');
        markedScript.src = "https://cdn.jsdelivr.net/npm/marked/marked.min.js";
        document.head.appendChild(markedScript);
    }

    // 2. Inject HTML Elements into body
    const chatHTML = `
<!-- ═══ AI CHATBOT WIDGET ═══ -->
<button class="chat-fab" id="chatFab" onclick="window.toggleChat()" title="AI Assistant">
    <svg id="chatFabIcon" viewBox="0 0 24 24">
        <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 9h2v2H7zm4 0h2v2h-2zm4 0h2v2h-2z"/>
    </svg>
    <span class="pulse" id="chatPulse"></span>
</button>

<div class="chat-panel" id="chatPanel">
    <div class="chat-header" id="chatHeader" style="cursor: move;">
        <div class="chat-header-left">
            <div class="chat-dot"></div>
            <div>
                <div class="chat-header-title">Canifa AI Stylist</div>
                <div class="chat-header-sub">Online</div>
            </div>
        </div>
        <div class="chat-header-btns">
            <button class="chat-hdr-btn" onclick="window.toggleExpandChat()" title="Expand">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"/></svg>
            </button>
            <button class="chat-hdr-btn danger" onclick="window.clearChatHistory()" title="Clear">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 6h18M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"/></svg>
            </button>
            <button class="chat-hdr-btn" onclick="window.toggleChat()" title="Close">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 6L6 18M6 6l12 12"/></svg>
            </button>
        </div>
    </div>

    <div class="chat-messages" id="chatMsgs">
        <div class="chat-bubble ai">
            Xin chào! Tôi có thể giúp gì cho bạn?
        </div>
    </div>

    <div class="chat-typing" id="chatTyping">
        <div style="font-weight:600;font-size:0.7em">AI</div>
        <div class="typing-dots"><span></span><span></span><span></span></div>
    </div>

    <div class="chat-input-bar">
        <input type="text" class="chat-input" id="chatInput" placeholder="Nhắn tin cho AI..." onkeypress="window.handleChatKey(event)">
        <button class="chat-send-btn" id="chatSendBtn" onclick="window.sendChatMessage()">
            <svg viewBox="0 0 24 24"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/></svg>
        </button>
    </div>
</div>
`;

    // Append to body after a slight delay to ensure document readiness
    setTimeout(() => {
        document.body.insertAdjacentHTML('beforeend', chatHTML);
        
        // Setup Drag
        initDraggable('#chatPanel', '#chatHeader');
    }, 500);

    // ─── CHATBOT LOGIC ───
    let chatSessionId = localStorage.getItem('canifa_chat_session');
    if (!chatSessionId) {
        chatSessionId = 'sess_' + Math.random().toString(36).substr(2, 9);
        localStorage.setItem('canifa_chat_session', chatSessionId);
    }

    function getChatDeviceId() {
        let dId = localStorage.getItem('mcp_chat_device_id');
        if (!dId) {
            dId = 'web_' + Math.random().toString(36).substr(2, 9);
            localStorage.setItem('mcp_chat_device_id', dId);
        }
        return dId;
    }

    window.toggleChat = function() {
        const p = document.getElementById('chatPanel');
        const f = document.getElementById('chatFab');
        const pIcon = document.getElementById('chatPulse');
        const fabIcon = document.getElementById('chatFabIcon');

        if (!p) return;

        if (p.classList.contains('show')) {
            p.classList.remove('show');
            f.classList.remove('open');
            pIcon.style.display = 'block';
            fabIcon.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 9h2v2H7zm4 0h2v2h-2zm4 0h2v2h-2z"/>\`;
        } else {
            p.classList.add('show');
            f.classList.add('open');
            pIcon.style.display = 'none';
            fabIcon.innerHTML = \`<path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>\`;
            document.getElementById('chatInput').focus();
        }
    };

    window.toggleExpandChat = function() {
        document.getElementById('chatPanel').classList.toggle('expanded');
    };

    function appendMessage(text, sender) {
        const box = document.getElementById('chatMsgs');
        const msg = document.createElement('div');
        msg.className = \`chat-bubble \${sender}\`;

        if (sender === 'ai' && window.marked && window.DOMPurify) {
            const rawHtml = marked.parse(text);
            const cleanHtml = DOMPurify.sanitize(rawHtml, { USE_PROFILES: { html: true } });
            msg.innerHTML = cleanHtml;
        } else {
            msg.textContent = text;
        }

        box.appendChild(msg);
        setTimeout(() => {
            box.scrollTop = box.scrollHeight;
        }, 50);
    }

    window.sendChatMessage = async function() {
        const input = document.getElementById('chatInput');
        const text = input.value.trim();
        if (!text) return;

        appendMessage(text, 'user');
        input.value = '';
        
        document.getElementById('chatTyping').classList.add('show');
        setTimeout(() => {
            document.getElementById('chatMsgs').scrollTop = document.getElementById('chatMsgs').scrollHeight;
        }, 50);
        
        document.getElementById('chatInput').disabled = true;
        document.getElementById('chatSendBtn').disabled = true;

        try {
            const res = await fetch('/api/chat', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    message: text,
                    device_id: getChatDeviceId(),
                    session_id: chatSessionId
                })
            });

            if (!res.ok) throw new Error(\`HTTP error! status: \${res.status}\`);
            
            const data = await res.json();
            document.getElementById('chatTyping').classList.remove('show');
            
            if (data.status === 'success' && data.data && data.data.message) {
                appendMessage(data.data.message, 'ai');
            } else {
                appendMessage('❌ Lỗi phản hồi từ server.', 'ai');
            }
        } catch (e) {
            console.error('Chat error:', e);
            document.getElementById('chatTyping').classList.remove('show');
            appendMessage('⚠️ Xin lỗi, có lỗi kết nối. Hãy thử lại.', 'ai');
        } finally {
            document.getElementById('chatInput').disabled = false;
            document.getElementById('chatSendBtn').disabled = false;
            document.getElementById('chatInput').focus();
        }
    };

    window.handleChatKey = function(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            window.sendChatMessage();
        }
    };

    window.clearChatHistory = async function() {
        if (!confirm('Xóa lịch sử chat này?')) return;
        try {
            await fetch('/api/chat/history', {
                method: 'DELETE',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ device_id: getChatDeviceId(), session_id: chatSessionId })
            });
            document.getElementById('chatMsgs').innerHTML = \`<div class="chat-bubble ai">Lịch sử đã được xóa. Tôi có thể giúp gì tiếp?</div>\`;
            
            // Generate new session ID after clearing
            chatSessionId = 'sess_' + Math.random().toString(36).substr(2, 9);
            localStorage.setItem('canifa_chat_session', chatSessionId);
        } catch(e) {
            alert('Lỗi xóa lịch sử');
        }
    };

    // Drag functionality for the Chat Box (Drag by header)
    function initDraggable(dragSelector, handleSelector) {
        const el = document.querySelector(dragSelector);
        const handle = document.querySelector(handleSelector);
        if(!el || !handle) return;
        
        let isDragging = false;
        let initialX, initialY, currentX = 0, currentY = 0;
        
        handle.addEventListener('mousedown', dragStart);
        document.addEventListener('mousemove', drag);
        document.addEventListener('mouseup', dragEnd);

        function dragStart(e) {
            if (e.target.closest('.chat-header-btns')) return; // Don't drag if clicking buttons
            initialX = e.clientX - currentX;
            initialY = e.clientY - currentY;
            isDragging = true;
        }

        function drag(e) {
            if (!isDragging) return;
            e.preventDefault();
            currentX = e.clientX - initialX;
            currentY = e.clientY - initialY;
            el.style.transform = \`translate(\${currentX}px, \${currentY}px)\`;
        }

        function dragEnd() {
            isDragging = false;
        }
    }
})();
