/**
 * Demo Chat Widget - Functional Chat Interface for KI Demo Section
 * Connects to N8N webhook via send.php
 */

class DemoChat {
    constructor() {
        this.sessionId = this.generateSessionId();
        this.isTyping = false;
        this.messages = [];
        this.chatMessages = null;
        this.chatInput = null;
        this.sendBtn = null;
        
        this.init();
    }
    
    init() {
        // Wait for DOM to be ready
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.setup());
        } else {
            this.setup();
        }
    }
    
    setup() {
        // Get demo chat elements - try multiple selectors for compatibility
        this.chatMessages = document.querySelector('.chat-demo .chat-messages') 
            || document.querySelector('.chat-demo .chat-preview .chat-messages');
        this.chatInput = document.querySelector('.chat-demo .chat-input-field')
            || document.querySelector('.chat-demo input[type="text"]');
        this.sendBtn = document.querySelector('.chat-demo .chat-send-btn')
            || document.querySelector('.chat-demo button');
        
                
        if (!this.chatMessages || !this.chatInput || !this.sendBtn) {
                        return;
        }
        
        this.bindEvents();
    }
    
    generateSessionId() {
        return 'demo_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    }
    
    bindEvents() {
        // Send on button click
        this.sendBtn.addEventListener('click', (e) => {
            e.preventDefault();
            this.sendMessage();
        });
        
        // Send on Enter key
        this.chatInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                this.sendMessage();
            }
        });
    }
    
    addMessageToUI(sender, text) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `chat-bubble ${sender === 'user' ? 'user-bubble' : ''}`;
        messageDiv.innerHTML = `<span>${this.escapeHtml(text)}</span>`;
        this.chatMessages.appendChild(messageDiv);
        this.scrollToBottom();
    }
    
    async sendMessage() {
        const message = this.chatInput?.value?.trim();
        
        if (!message || this.isTyping) return;
        
        // Add user message to UI
        this.addMessageToUI('user', message);
        this.chatInput.value = '';
        
        // Show typing indicator
        this.showTypingIndicator();
        this.isTyping = true;
        
        try {
            // Build absolute URL to ensure correct path on any hosting
            const apiUrl = new URL('/scripts/add/send.php', window.location.origin).href;
            
            const response = await fetch(apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({
                    type: 'chat',
                    message: message,
                    session_id: this.sessionId
                })
            });
            
            const data = await response.json();
            
            if (data.success && data.data && data.data.ai_response) {
                this.addMessageToUI('ki', data.data.ai_response);
            } else {
                                this.addMessageToUI('ki', 'Entschuldigung, es gab ein Problem. Bitte versuchen Sie es später erneut.');
            }
        } catch (error) {
                        this.addMessageToUI('ki', 'Verbindung zum Server fehlgeschlagen. Bitte überprüfen Sie Ihre Internetverbindung.');
        } finally {
            this.hideTypingIndicator();
            this.isTyping = false;
        }
    }
    
    showTypingIndicator() {
        if (!this.chatMessages.querySelector('.typing-indicator')) {
            const typingDiv = document.createElement('div');
            typingDiv.className = 'chat-bubble typing-indicator';
            typingDiv.innerHTML = '<span>...</span>';
            this.chatMessages.appendChild(typingDiv);
            this.scrollToBottom();
        }
    }
    
    hideTypingIndicator() {
        const typingIndicator = this.chatMessages.querySelector('.typing-indicator');
        if (typingIndicator) {
            typingIndicator.remove();
        }
    }
    
    scrollToBottom() {
        this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
    }
    
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}

// Initialize demo chat
window.demoChat = new DemoChat();
