class ChatWidget {
    constructor(containerId = 'chat-widget-container') {
        // Tự động tạo container nếu không tìm thấy
        this.container = document.getElementById(containerId);
        if (!this.container) {
            this.container = document.createElement('div');
            this.container.id = containerId;
            document.body.appendChild(this.container);
        }

        // Khởi tạo các biến trạng thái
        this.isOpen = false;
        this.isProcessing = false;
        this.chatId = null;
        this.initialWindowHeight = window.innerHeight;

        // Tạo widget
        this.createChatWidget();

        // Bind các event handlers
        this.handleResize = this.handleResize.bind(this);
        window.addEventListener('resize', this.handleResize);
    }

    createChatWidget() {
       // Tạo nút chat
        this.chatButton = document.createElement('div');
        this.chatButton.className = 'chat-button';
        // Tạo container cho animation
        this.chatButton.innerHTML = '<div id="robot-animation"></div>';
        this.container.appendChild(this.chatButton);
    
        // Load animation
        this.loadRobotAnimation();

        // Tạo cửa sổ chat
        this.chatWindow = document.createElement('div');
        this.chatWindow.className = 'chat-window';
        this.chatWindow.style.display = 'none';
        this.chatWindow.innerHTML = `
        <div class="chat-header">
            <span>Chat with AI Assistant</span>
            <div class="header-buttons">
                <button class="export-button" title="Export to Text">
                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                        <polyline points="7 10 12 15 17 10"></polyline>
                        <line x1="12" y1="15" x2="12" y2="3"></line>
                    </svg>
                </button>
                <button class="close-button">×</button>
            </div>
        </div>
        <div class="chat-messages"></div>
        <div class="chat-input-container">
            <textarea class="chat-input" placeholder="Type your message..." rows="1"></textarea>
            <button class="send-button" disabled>
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <line x1="22" y1="2" x2="11" y2="13"></line>
                    <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
                </svg>
            </button>
        </div>
 
     `;
        // Thêm reference cho export button
        this.exportButton = this.chatWindow.querySelector('.export-button');
        
        // Thêm event listener cho export button
        this.exportButton.addEventListener('click', () => this.exportToText());
     
        this.container.appendChild(this.chatWindow);

        // Lấy reference đến các elements
        this.chatMessages = this.chatWindow.querySelector('.chat-messages');
        this.chatInput = this.chatWindow.querySelector('.chat-input');
        this.sendButton = this.chatWindow.querySelector('.send-button');
        this.closeButton = this.chatWindow.querySelector('.close-button');

        // Thêm event listeners
        this.chatButton.addEventListener('click', () => this.toggleChat());
        this.closeButton.addEventListener('click', () => this.toggleChat());
        this.chatInput.addEventListener('input', () => this.handleInput());
        this.chatInput.addEventListener('keypress', (e) => this.handleKeyPress(e));
        this.sendButton.addEventListener('click', () => this.handleSend());
        this.chatInput.addEventListener('focus', () => this.handleInputFocus());
        this.chatInput.addEventListener('blur', () => this.handleInputBlur());
    }
    loadRobotAnimation() {
    // Tải và cấu hình animation
    this.robotAnimation = lottie.loadAnimation({
        container: document.getElementById('robot-animation'),
        renderer: 'svg',
        loop: true,
        autoplay: true,
        path: 'https://lottie.host/29158e95-2031-421c-8c93-60f04c2a46e6/i18uUMtYps.json' // Robot animation
    });

    // Thêm hover effect
    this.chatButton.addEventListener('mouseenter', () => {
        this.robotAnimation.setSpeed(1.5); // Tăng tốc độ animation khi hover
    });

    this.chatButton.addEventListener('mouseleave', () => {
        this.robotAnimation.setSpeed(1); // Trở về tốc độ bình thường
    });
    }
    handleInputFocus() {
        if (window.innerWidth <= 480) {
            this.chatWindow.classList.add('keyboard-visible');
            setTimeout(() => {
                this.chatInput.scrollIntoView({ behavior: 'smooth' });
            }, 300);
        }
    }

    handleInputBlur() {
        if (window.innerWidth <= 480) {
            this.chatWindow.classList.remove('keyboard-visible');
        }
    }

    handleResize() {
        if (window.innerWidth <= 480) {
            const isKeyboardVisible = window.innerHeight < this.initialWindowHeight;
            
            if (isKeyboardVisible) {
                this.chatWindow.classList.add('keyboard-visible');
                setTimeout(() => {
                    this.chatInput.scrollIntoView({ behavior: 'smooth' });
                }, 100);
            } else {
                this.chatWindow.classList.remove('keyboard-visible');
                this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
            }
        }
    }

toggleChat() {
    this.isOpen = !this.isOpen;
    this.chatWindow.style.display = this.isOpen ? 'flex' : 'none';
    
    if (this.isOpen) {
        this.chatInput.focus();
        
        // Kiểm tra nếu chat messages trống thì thêm lời chào
        if (this.chatMessages.children.length === 0) {
            const welcomeMessage = `
                <h3>Chào bạn! 👋</h3>
                <p>Tôi là trợ lý AI của bạn để tìm hiểu về tiếp thị mạng lưới. Tôi có thể giúp bạn:</p>
                <br>• Hiểu về tiếp thị mạng lưới
                <br>• Các chiến lược và bí quyết kinh doanh
                <br>• Các phương thức làm việc hiệu quả
                <br>• Và nhiều nội dung khác nữa!
                <br><br>Hãy cùng khám phá nhé. Bạn có câu hỏi gì không?
            `;
            this.addMessage(welcomeMessage, false);
        }

        // Scroll to bottom
        setTimeout(() => {
            this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
        }, 100);

        // Xử lý viewport trên mobile
        if (window.innerWidth <= 480) {
            document.body.style.overflow = 'hidden';
            this.initialWindowHeight = window.innerHeight;
            this.chatWindow.classList.remove('keyboard-visible');
        }
    } else {
        document.body.style.overflow = '';
    }
}

    handleInput() {
        this.chatInput.style.height = 'auto';
        this.chatInput.style.height = this.chatInput.scrollHeight + 'px';
        this.sendButton.disabled = !this.chatInput.value.trim();
    }

    handleKeyPress(event) {
        if (event.key === 'Enter' && !event.shiftKey) {
            event.preventDefault();
            if (!this.sendButton.disabled) {
                this.handleSend();
            }
        }
    }
async exportToText() {
    try {
        // Disable button and show loading state
        this.exportButton.disabled = true;
        this.exportButton.innerHTML = `
            <svg class="spinning" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <line x1="12" y1="2" x2="12" y2="6"></line>
                <line x1="12" y1="18" x2="12" y2="22"></line>
                <line x1="4.93" y1="4.93" x2="7.76" y2="7.76"></line>
                <line x1="16.24" y1="16.24" x2="19.07" y2="19.07"></line>
                <line x1="2" y1="12" x2="6" y2="12"></line>
                <line x1="18" y1="12" x2="22" y2="12"></line>
                <line x1="4.93" y1="19.07" x2="7.76" y2="16.24"></line>
                <line x1="16.24" y1="7.76" x2="19.07" y2="4.93"></line>
            </svg>
        `;

        // Create content
        let content = "NỘI DUNG CUỘC TRÒ CHUYỆN\n";
        content += `Ngày xuất: ${new Date().toLocaleString('vi-VN')}\n`;
        content += "=".repeat(50) + "\n\n";

        // Get all messages
        const messages = this.chatMessages.children;
        
        // Process each message
        Array.from(messages).forEach((msg) => {
            const isUser = msg.classList.contains('user-message');
            const text = msg.innerText.trim();
            content += `${isUser ? 'Bạn' : 'AI'}: ${text}\n\n`;
        });

        // Create UTF-8 BOM bytes
        const bom = new Uint8Array([0xEF, 0xBB, 0xBF]);
        
        // Convert content to bytes
        const contentBytes = new TextEncoder().encode(content);
        
        // Combine BOM and content
        const fullContent = new Uint8Array(bom.length + contentBytes.length);
        fullContent.set(bom, 0);
        fullContent.set(contentBytes, bom.length);

        // Create blob with explicit headers matching PHP
        const blob = new Blob([fullContent], {
            type: 'text/plain; charset=UTF-8'
        });

        // Download file
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `cuoc-tro-chuyen-${new Date().toISOString().slice(0,10)}.txt`;
        
        // Force download with same headers as PHP
        const headers = new Headers({
            'Content-Type': 'text/plain; charset=UTF-8',
            'Content-Disposition': `attachment; filename="${a.download}"`
        });
        
        document.body.appendChild(a);
        a.click();
        URL.revokeObjectURL(url);
        document.body.removeChild(a);

    } catch (error) {
        console.error('Failed to export text:', error);
        alert('Không thể xuất file. Vui lòng thử lại.');
    } finally {
        // Restore button state
        this.exportButton.disabled = false;
        this.exportButton.innerHTML = `
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                <polyline points="7 10 12 15 17 10"></polyline>
                <line x1="12" y1="15" x2="12" y2="3"></line>
            </svg>
        `;
    }
}
    async handleSend() {
        if (this.isProcessing) return;

        const message = this.chatInput.value.trim();
        if (!message) return;

        this.isProcessing = true;
        this.sendButton.disabled = true;
        this.chatInput.disabled = true;

        // Thêm tin nhắn người dùng
        this.addMessage(message, true);

        // Clear input
        this.chatInput.value = '';
        this.chatInput.style.height = 'auto';

        try {
            // Gửi tin nhắn đến server
            const response = await fetch('/chatbot/api/chat-send.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    message: message,
                    chat_id: this.chatId
                }),
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            if (!data.success) {
                throw new Error(data.error || 'Unknown error occurred');
            }

            // Cập nhật chat ID nếu có
            if (data.chat_id) {
                this.chatId = data.chat_id;
            }

            // Thêm phản hồi của bot
            this.addMessage(data.response, false);

        } catch (error) {
            console.error('Failed to send message:', error);
            this.addMessage('Sorry, an error occurred. Please try again later.', false);
        } finally {
            this.isProcessing = false;
            this.sendButton.disabled = false;
            this.chatInput.disabled = false;
            this.chatInput.focus();
        }
    }

    addMessage(message, isUser) {
        const messageDiv = document.createElement('div');
        messageDiv.className = isUser ? 'user-message' : 'bot-message';
        
        if (isUser) {
            messageDiv.textContent = message;
        } else {
            messageDiv.innerHTML = message;
            
            // Style cho các elements được format
            const headings = messageDiv.querySelectorAll('h3');
            headings.forEach(heading => {
                heading.style.margin = '15px 0';
                heading.style.fontWeight = 'bold';
            });
            
            const paragraphs = messageDiv.querySelectorAll('p');
            paragraphs.forEach(p => {
                p.style.margin = '10px 0';
            });
            
            const lists = messageDiv.querySelectorAll('ul, ol');
            lists.forEach(list => {
                list.style.marginLeft = '20px';
            });
        }
        
        this.chatMessages.appendChild(messageDiv);
        setTimeout(() => {
            this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
        }, 100);
    }
}

// Khởi tạo chat widget
document.addEventListener('DOMContentLoaded', () => {
    new ChatWidget();
});